useMemo hook in React


Objectives

Learn how to use the useMemo hook to memoize values in React components.

useMemo

The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly running. It is similar to the useCallback Hook, but instead of memoizing functions, it memoizes values.

Problem

Let's say you have a function that takes a long time to run. If you were to call this function in a component, the function would run every time the component re-renders. This is not ideal, especially if the function is not dependent on any of the component's props or state.

The code below shows a function that takes a long time to run.

Let's see what happens when we call this function in a component.

When changing the count or adding a todo, you will notice a delay in execution. What a bad user experience 😞.

How useMemo works?

The useMemo Hook accepts two arguments: a function and a dependency array. The function is the function that you want to memoize, and the dependency array is an array of values that the function depends on. The useMemo Hook will only recompute the memoized value when one of the values in the dependency array changes.

In the following example, the expensive function will only run when count is changed and not when todo's are added.

You can test this by changing the count and adding a todo. You will notice that the function only runs when the count is changed. Adding a todo does not cause the function to run. This is way better than the previous example.

Conclusion

That's a wrap! useMemo is a great hook to use when you want to memoize values in React components. Hope you learned something new 😄. If you have any questions or comments, feel free to leave a comment below. Thanks for reading!

Resources