Home > Net >  In React, can I use the set function of useState outside of a functional component?
In React, can I use the set function of useState outside of a functional component?

Time:10-15

In React, can I use the set function of useState outside of a functional component?

const WhatEver:React.FC = function() {

  const [num, setNum] = React.useState(0);
  
  return <>{num}</>;
  
}

export function changeNum(num) {

  setNum(num); //Can I use it here, is there any way?
  
 }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

No. You have to call the function in the scope it is defined in, but that's not react related, that's javascript.

You can also pass the function as a prop to a child component and use it there.

CodePudding user response:

The changeNum function currently has no way of knowing what setNum is. One way to solve this is to pass setNum as an argument.

export function changeNum(num, setNum) {
  setNum(num); //Can I use it here, is there any way?
}

Another way is to define the function within the component.

const WhatEver:React.FC = function() {

  const [num, setNum] = React.useState(0);
  function changeNum(num) {
      setNum(num); //Can I use it here, is there any way?
    }
  
  return <>{num}</>;
  
}
  • Related