DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for React hooks: useCallback
Abdullah Furkan Γ–zbek
Abdullah Furkan Γ–zbek

Posted on • Updated on • Originally published at blog.furkanozbek.com

React hooks: useCallback

1. useCallback

const memoizedCallback = useCallback(
  () => {
    doSomething(a, b);
  },
  [a, b],
);
Enter fullscreen mode Exit fullscreen mode

Pass an inline callback and an array of dependencies. useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

2. Purpose of useCallback

function MyComponent() {
  // handleClick is re-created on each render
  const handleClick = () => {
    console.log('Clicked!');
  };

  // ...
}
Enter fullscreen mode Exit fullscreen mode

handleClick is a different function object on every rendering of MyComponent.

But in some cases you need to maintain a single function instance between renderings:

  1. A functional component wrapped insideΒ React.memo()Β accepts a function object prop
  2. When the function object is a dependency to other hooks, e.g.Β useEffect(..., [callback])
  3. When the function has some internal state, e.g. when theΒ function is debounced or throttled.

That’s when useCallback(callbackFun, deps) is helpful: given the same dependency values deps, the hook returns (aka memoizes) the function instance between renderings:

import { useCallback } from 'react';

function MyComponent() {
  // handleClick is the same function object
  const handleClick = useCallback(() => {
    console.log('Clicked!');
  }, []);

  // ...
}
Enter fullscreen mode Exit fullscreen mode

3. Links

Top comments (0)

Become a ModeratorHey! We would love your help!

Fill out this survey and help us moderate our community by becoming a tag moderator here at DEV.