javascriptreactjsreact-hooks

useCallback on function passed to a leaf element in react?


If a component has a leaf element (like button) that takes an onClick function which is coming from a custom hook, should that onClick be wrapped in useCallback?

Folder Structure

- someComponent (folder)
  
   SomeComponent.tsx (file)

   - hooks (folder)

    useSomeComponentClick.ts
//SomeComponent

const handleClick = useSomeComponentClick();

return (
  <button onClick={handleClick} />
);

// useSomeComponentClick

const useSomeComponentClick = () => {
   const handleClick = () => {
      // do something on click
   }

   return handleClick;
}
 

Now, should be wrap handleClick in useCallback?


Solution

  • useCallback is an optimisation technique. It is generally used to prevent re-renders or other recalculations.

    In you very specific case, there is nothing to optimize, the code will be slower when you use it instead because

    const handleClick = () => {
       // do something on click
    }
    

    is by itself more performant than

    const handleClick = useCallback(() => {
       // do something on click
    }, [])
    

    these is less code to execute.

    However, if the callback was used as a dependency of useMemo or useEffect or if it was passed to memo(Component) or React.PureComponent, it will make a difference.