useCallback when to use it

function ParentComponent() {
  const handleClick = () => {
    // logic  
  }

  return (
    <ChildComponent onClick={handleClick}  />
  )
}

What problem with the above code? A performance problem. Every time ParentComponent re-render, ChildComponent re-render again.

Why? Every time ParentComponent re-render, it creates a new function handle click so ChildComponent re-render because onClick prop change.

How to fix it? Use useCallback hook. useCallback cache function so when ParentComponent re-render, handleClick function still keep value and ChildComponent don't re-render.

function ParentComponent() {
  const handleClick = useCallback(() => {
    // logic  
  }, [])

  return (
    <ChildComponent onClick={handleClick}  />
  )
}

When handleClick depend on some values, we need to add it to the dependencies array.

No Comments Yet