Send setState from useState as a props using useCallback

Viewed 651

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.

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

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.

Related