Home > Software design >  Difference between useCallback hook and empty dependency array and just defining a function outside
Difference between useCallback hook and empty dependency array and just defining a function outside

Time:09-23

In react, we can memoize a function using useCallback so the function doesn't change every rerender

const fn = useCallback(someOtherFn, []);

Instead, can we define someOtherFn outside the component, and if it uses setState, we give that to it as an argument?

Something like

function someOtherFn(setState) {
    setState("ok")
}

function myComponenet(){
......
}

Sorry in advance if this is a stupid question.

CodePudding user response:

You can do that, but it might probably defeat the purpose, since you'd have to write another function that calls it, and that other function would be created every render. For example, perhaps you're thinking of:

function someOtherFn(setState) {
    setState("ok")
}
const MyComponent = () => {
  const [state, setState] = useState();
  return <button onClick={() => someOtherFn(setState)}>click</button>;
};

Although someOtherFn indeed wouldn't need to be created every time - it'd only need to be created once - the handler function, the

() => someOtherFn(setState)

would be created every time the component renders, which could be a problem in certain uncommon (IMO) situations.

To avoid this issue, you would have to bind the setState argument to the function persistently somehow - which would be most easily accomplished through the use useCallback.

  • Related