React Hooks: useCallback and useMemo

In this blog post, I will introduce the React Hooks ‘useCallback’ and ‘useMemo’. These Hooks prevent unnecessary re-renders, making your code way more efficient.

Aylin Gokalp
Open Source Engineer
React
Published
April 26, 2021

In this blog post, I will introduce the React Hooks ‘useCallback’ and ‘useMemo’. These Hooks prevent unnecessary re-renders, making your code way more efficient.

But first a quick intro to Hooks! They are a new feature of React 16.8.0 that let you use class features in functional components. With Hooks, you can now create states and use lifecycles methods. ‘useState’ allows you to create states for your variables like this:

while `useEffect` allows you to create side effects:

The array given in parameters lets you fire the side effect only when the value in the array is changed. This way, you can easily create lifecycle methods.

But that is not all! With a bit of imagination, you can create Hooks that do all kind of things such as implementing a dark mode on your app or creating a form with states.

These days, there are Hooks for everything, so how do we use ‘useCallback’ and ‘useMemo’?

Both of them take a function and an array of dependencies as parameters like ‘useEffect’. The function’s return value will only be changed if one of the dependencies value changes — otherwise a cached value will be returned.

Note that passing an empty array of dependencies will cause the Hook to execute the function once but passing it no array at all will return a new value on every call.

The main difference between the two is that ‘useCallback’ returns a memoized callback and ‘useMemo’ returns a memoized value that is the result of the function parameter.

If you have to process a lot of data, ‘useMemo’ is the perfect Hook as it will do the work once at the first render and then return a cached version on every other render.

‘useCallback’, however, is used differently. Take for example a parent component that often re-renders. Inside the parent, we have a child component that takes a function-prop. At each re-render, the Child will re-execute its function prop uselessly. However, if you pass ‘useCallback’ as a prop with a dependency array, it resolves the issue because the function will be executed only when the dependency changes. Every other re-render will then get a cached function.

Here is a demo:

Now you should be ready to optimise your code with React Hooks. To recap: you should not use ‘useCallback’ and ‘useMemo’ for everything. ‘useMemo’ should be used for big data processing while ‘useCallback’ is a way to add more dependency to your code to avoid useless rendering.

Hackages is an educational platform with the mission of improving developers and businesses' skills and helping them acquire new ones.
Home
Tutorials
Blog
Webinars