šŸ¤™

useLess useCallback

  1. 10 minute read
  2. Published: 2021-02-07

I found this useCallbackĀ in the one of the components at work. This is actually not needed.

const handleClick = useCallback(() => {
    setClicked(true);
}, [clicked]);

With useCallbackĀ the function you pass it is memo-ized until one of the variables in its dependency array changes, and then the function is re-memo-ized with the new value for that variable. In this example nothing in the function relies on that clickedĀ variable so we can rely on the function being pure instead of React's useCallbackSo this will be more efficient:

const handleClick = () => {
    setClicked(true);
}

useCallbackĀ would make sense to use if there was a usage of the variable in that function, like this for example

const handleClick = useCallback(() => {
  if (anotherVar) doSomething();
  setClicked(true);
}, [anotherVar]);

we need the current value of anotherVarĀ so the function cant be memoised otherwise it will always use the initial value.

Last thing, if you need a guarantee that the clickedĀ variable is current you can pass a function into the state setter.

const handleClick = () => {
    setClicked(clicked => !clicked);
}