What is React's useMemo
Back

What is React's useMemo

Requirements

  • React.js (16.8 or newer)

Introduction

React's , much like memo and useCallback, is used to optimize the rendering of given React function component by memoizing it. Although every one of them have different use cases.

Problem

Let's say you have this component:

import React, { useState } from "react"; const array = [1, 2, 4, 5, 8]; export default function App() { const [localState, setLocalState] = useState(0); function sum() { return array.reduce((acc, curr) => acc + curr); } return ( <div> <p>Local State: {localState}</p> <button onClick={() => setLocalState(localState + 1)}> Change Local State </button> <h1>{sum()}</h1> </div> ); }

The example above shows a scenario that works but as you might suspect, not efficiently. The function will always return the same result, but it will be recreated at every button click, as the button is updating state, and every state update the component re-renders. Every time is recreated, it will run again in the jsx.

Solution

To avoid the function to be recreated we'll use as such:

import React, { useState, useMemo } from "react"; const array = [1, 2, 4, 5, 8]; export default function App() { const [localState, setLocalState] = useState(0); function sum() { return array.reduce((acc, curr) => acc + curr); } const memoizedSumValue = useMemo(sum, []); return ( <div> <p>Local State: {localState}</p> <button onClick={() => setLocalState(localState + 1)}> Change Local State </button> <h1>{memoizedSumValue}</h1> </div> ); }

The hook will execute the function passed as first argument and memoize its return value, if the value doesn't change, the function will not be recreated and re-executed.

TLDR

basically execute the function passed at the first argument and memoize the return

Additional Resources

2025 Andrei T.F.
with Next.js