Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send setState from useState as a props using useCallback

Tags:

reactjs

I have the next state in my component;

const [value, setValue] = useState(0);

Also inside this component i have another component as a child:

<Child setValue={setValue} />

How you can notice there i send setState as a prop.
Question: How to wrap this setState in useCallback hook and after that also to pass it as a prop in <Child/>?
I want to do this to optimize the component especially to avoid re-renders for Child component.

like image 725
Asking Avatar asked Oct 22 '25 12:10

Asking


2 Answers

assuming setState is a function defined by you

const [value, setValue] = useState(0):
const setState = useCallback((newValue) =>{
    setValue(newValue)
},[all the dependencies for the function above])

return(
   <Child
      setValue={setState}
   />
)

one more thing, DONT pass functions inside the dependency array, it will impact the performance negatively

like image 64
Kartik Malik Avatar answered Oct 25 '25 18:10

Kartik Malik


In order to see the props, you have to install the extension React developer tools. You don't need to wrap setState in use callback, because React doesn't change hook setState.

On another note I think you have to pass setValue, not setState.

like image 43
Soufiane Boutahlil Avatar answered Oct 25 '25 18:10

Soufiane Boutahlil