cover-img

Learn the useCallback Hook in React

10 August, 2022

10

10

1

What is the useCallback hook?

useCallback() returns a memoized callback.

Memoization, also known as memoisation, is a technique used in computing to speed up computer programmes by caching the results of heavy function calls and returning the cached result when the same inputs are used again. Consider memoization to be the act of storing a value such that it does not have to be recalculated.

This allows us to separate resource-intensive functions so they don't have to be re-executed on every render; as a result, it will only run when one of its dependencies updates.

Syntax


When to use the useCallback hook?

One reason to use useCallback is to prevent a component from re-rendering unless its props have changed.

Using a simple Todo example:


Try running this, and click on the increment button, i.e <button onClick={increment}>+</button>

You’ll notice the Todo component re-renders even when the todo does not change.

Why does this not work? We are using memo, so the Todo component should not re-render since neither the todo state nor the addTodo function are changing when the count is incremented.

This is because of something called "referential equality".

Every time a component re-renders, its functions get recreated. Because of this, the addTodo function has actually changed.

https://res.cloudinary.com/d-a-r-k-c-o-d-e/image/upload/v1660006095/work/React%20Hooks/useCallback/w-o_callback_piyst1.gif

Solution

Wrap the addTodo() in a useCallback()


https://res.cloudinary.com/d-a-r-k-c-o-d-e/image/upload/v1660006078/work/React%20Hooks/useCallback/w-callback_lsbz9g.gif

Alternative to the useCallback hook

The useCallback() and the useMemo() are similiar. The main difference is that the useMemo() returns a memoized value while the useCallback() returns a memoized function.

react

javascript

react-hooks

10

10

1

react

javascript

react-hooks

WedDevTolu
I design and develop experiences that makes people's lives simple.

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2025. Showcase Creators Inc. All rights reserved.