useCallback hook to memoize functions in React

In our last blog post, we have learned how React.memo helps to avoid re-rendering of component.

We will learn how to use useCallback hook to avoid creating a new function on every re-render. Instead, the function will be created whenever the dependency value changes.

A useCallback syntax will look like this,

  () => {
    // Memoized function
  [] /* Dependency array */

We have our CounterButton component that is still re-rendering. We have added React.memo. Since the onClick function in the props changes on every re-render of the App component, the CounterButton still re-renders.

We will use useCallback to memoize the handleClick function in the App component. Only re-create if needed.

const handleClick = useCallback(() => {
  setClicks(click => click + 1);
}, []);

Now, the handleClick function won't get re-created on every re-render of the App component. So the props we pass to CounterButton also will be a static function and won't change.

Click on the click me button and see the console.log

`App` renders
`Counter` renders

It will only re-render the App and Counter component.

We have learned how useCallback helps to memoize functions. Also, helps to avoid unnecessary re-rendering.

You can check out the full example here. Play with it.