useMemo·续2

```js src/TodoList.js active import List from './List.js'; import { filterTodos } from './utils.js'

export default function TodoList({ todos, theme, tab }) { const visibleTodos = filterTodos(todos, tab); return (

); }


```js src/List.js
import { memo } from 'react';

function List({ items }) {
  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>
          {item.completed ?
            <s>{item.text}</s> :
            item.text
          }
        </li>
      ))}
    </ul>
  );
}

export default memo(List);

```js src/utils.js export function createTodos() { const todos = []; for (let i = 0; i < 50; i++) { todos.push({ id: i, text: "Todo " + (i + 1), completed: Math.random() > 0.5 }); } return todos; }

export function filterTodos(todos, tab) { return todos.filter(todo => { if (tab === 'all') { return true; } else if (tab === 'active') { return !todo.completed; } else if (tab === 'completed') { return todo.completed; } }); }


```css
label {
  display: block;
  margin-top: 10px;
}

.dark {
  background-color: black;
  color: white;
}

.light {
  background-color: white;
  color: black;
}

Quite often, code without memoization works fine. If your interactions are fast enough, you don't need memoization.

Keep in mind that you need to run React in production mode, disable React Developer Tools, and use devices similar to the ones your app's users have in order to get a realistic sense of what's actually slowing down your app.


Preventing an Effect from firing too often

Sometimes, you might want to use a value inside an Effect:

```js {4-7,10} function ChatRoom({ roomId }) { const [message, setMessage] = useState('');

const options = { serverUrl: 'https://localhost:1234', roomId: roomId }

useEffect(() => { const connection = createConnection(options); connection.connect(); // ...


This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) However, if you declare `options` as a dependency, it will cause your Effect to constantly reconnect to the chat room:

```js {5}
  useEffect(() => {
    const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [options]); // 🔴 Problem: This dependency changes on every render
  // ...

To solve this, you can wrap the object you need to call from an Effect in useMemo:

```js {4-9,16} function ChatRoom({ roomId }) { const [message, setMessage] = useState('');

const options = useMemo(() => { return { serverUrl: 'https://localhost:1234', roomId: roomId }; }, [roomId]); // ✅ Only changes when roomId changes

useEffect(() => { const connection = createConnection(options); connection.connect(); return () => connection.disconnect(); }, [options]); // ✅ Only changes when options changes // ...


This ensures that the `options` object is the same between re-renders if `useMemo` returns the cached object.

However, since `useMemo` is performance optimization, not a semantic guarantee, React may throw away the cached value if [there is a specific reason to do that](#caveats). This will also cause the effect to re-fire, **so it's even better to remove the need for a function dependency** by moving your object *inside* the Effect:

```js {5-8,13}
function ChatRoom({ roomId }) {
  const [message, setMessage] = useState('');

useEffect(() => {
    const options = { // ✅ No need for useMemo or object dependencies!
      serverUrl: 'https://localhost:1234',
      roomId: roomId
    }

const connection = createConnection(options);
    connection.connect();
    return () => connection.disconnect();
  }, [roomId]); // ✅ Only changes when roomId changes
  // ...

Now your code is simpler and doesn't need useMemo. Learn more about removing Effect dependencies.

Memoizing a dependency of another Hook

Suppose you have a calculation that depends on an object created directly in the component body:

```js {2} function Dropdown({ allItems, text }) { const searchOptions = { matchMode: 'whole-word', text };

const visibleItems = useMemo(() => { return searchItems(allItems, searchOptions); }, [allItems, searchOptions]); // 🚩 Caution: Dependency on an object created in the component body // ...


Depending on an object like this defeats the point of memoization. When a component re-renders, all of the code directly inside the component body runs again. **The lines of code creating the `searchOptions` object will also run on every re-render.** Since `searchOptions` is a dependency of your `useMemo` call, and it's different every time, React knows the dependencies are different, and recalculate `searchItems` every time.

To fix this, you could memoize the `searchOptions` object *itself* before passing it as a dependency:

```js {2-4}
function Dropdown({ allItems, text }) {
  const searchOptions = useMemo(() => {
    return { matchMode: 'whole-word', text };
  }, [text]); // ✅ Only changes when text changes

const visibleItems = useMemo(() => {
    return searchItems(allItems, searchOptions);
  }, [allItems, searchOptions]); // ✅ Only changes when allItems or searchOptions changes
  // ...

In the example above, if the text did not change, the searchOptions object also won't change. However, an even better fix is to move the searchOptions object declaration inside of the useMemo calculation function:

```js {3} function Dropdown({ allItems, text }) { const visibleItems = useMemo(() => { const searchOptions = { matchMode: 'whole-word', text }; return searchItems(allItems, searchOptions); }, [allItems, text]); // ✅ Only changes when allItems or text changes // ...


Now your calculation depends on `text` directly (which is a string and can't "accidentally" become different).

---

### Memoizing a function

Suppose the `Form` component is wrapped in [`memo`.](/reference/react/memo) You want to pass a function to it as a prop:

```js {2-7}
export default function ProductPage({ productId, referrer }) {
  function handleSubmit(orderDetails) {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails
    });
  }

return <Form onSubmit={handleSubmit} />;
}

Just as {} creates a different object, function declarations like function() {} and expressions like () => {} produce a different function on every re-render. By itself, creating a new function is not a problem. This is not something to avoid! However, if the Form component is memoized, presumably you want to skip re-rendering it when no props have changed. A prop that is always different would defeat the point of memoization.

To memoize a function with useMemo, your calculation function would have to return another function:

```js {2-3,8-9} export default function Page({ productId, referrer }) { const handleSubmit = useMemo(() => { return (orderDetails) => { post('/product/' + productId + '/buy', { referrer, orderDetails }); }; }, [productId, referrer]);

return

; }


This looks clunky! **Memoizing functions is common enough that React has a built-in Hook specifically for that. Wrap your functions into [`useCallback`](/reference/react/useCallback) instead of `useMemo`** to avoid having to write an extra nested function:

```js {2,7}
export default function Page({ productId, referrer }) {
  const handleSubmit = useCallback((orderDetails) => {
    post('/product/' + productId + '/buy', {
      referrer,
      orderDetails
    });
  }, [productId, referrer]);

return <Form onSubmit={handleSubmit} />;
}

The two examples above are completely equivalent. The only benefit to useCallback is that it lets you avoid writing an extra nested function inside. It doesn't do anything else. Read more about useCallback.


Troubleshooting

My calculation runs twice on every re-render

In Strict Mode, React will call some of your functions twice instead of once:

```js {2,5,6} function TodoList({ todos, tab }) { // This component function will run twice for every render.

const visibleTodos = useMemo(() => { // This calculation will run twice if any of the dependencies change. return filterTodos(todos, tab); }, [todos, tab]);

// ...


This is expected and shouldn't break your code.

This **development-only** behavior helps you [keep components pure.](/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component and calculation functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice and fix the mistake.

For example, this impure calculation function mutates an array you received as a prop:

```js {2-3}
  const visibleTodos = useMemo(() => {
    // 🚩 Mistake: mutating a prop
    todos.push({ id: 'last', text: 'Go for a walk!' });
    const filtered = filterTodos(todos, tab);
    return filtered;
  }, [todos, tab]);

React calls your function twice, so you'd notice the todo is added twice. Your calculation shouldn't change any existing objects, but it's okay to change any new objects you created during the calculation. For example, if the filterTodos function always returns a different array, you can mutate that array instead:

```js {3,4} const visibleTodos = useMemo(() => { const filtered = filterTodos(todos, tab); // ✅ Correct: mutating an object you created during the calculation filtered.push({ id: 'last', text: 'Go for a walk!' }); return filtered; }, [todos, tab]);


Read [keeping components pure](/learn/keeping-components-pure) to learn more about purity.

Also, check out the guides on [updating objects](/learn/updating-objects-in-state) and [updating arrays](/learn/updating-arrays-in-state) without mutation.

---

### My `useMemo` call is supposed to return an object, but returns undefined

This code doesn't work:

```js {1-2,5}
  // 🔴 You can't return an object from an arrow function with () => {
  const searchOptions = useMemo(() => {
    matchMode: 'whole-word',
    text: text
  }, [text]);

In JavaScript, () => { starts the arrow function body, so the { brace is not a part of your object. This is why it doesn't return an object, and leads to mistakes. You could fix it by adding parentheses like ({ and }):

```js {1-2,5} // This works, but is easy for someone to break again const searchOptions = useMemo(() => ({ matchMode: 'whole-word', text: text }), [text]);


However, this is still confusing and too easy for someone to break by removing the parentheses.

To avoid this mistake, write a `return` statement explicitly:

```js {1-3,6-7}
  // ✅ This works and is explicit
  const searchOptions = useMemo(() => {
    return {
      matchMode: 'whole-word',
      text: text
    };
  }, [text]);

Every time my component renders, the calculation in useMemo re-runs

Make sure you've specified the dependency array as a second argument!

If you forget the dependency array, useMemo will re-run the calculation every time:

```js {2-3} function TodoList({ todos, tab }) { // 🔴 Recalculates every time: no dependency array const visibleTodos = useMemo(() => filterTodos(todos, tab)); // ...


This is the corrected version passing the dependency array as a second argument:

```js {2-3}
function TodoList({ todos, tab }) {
  // ✅ Does not recalculate unnecessarily
  const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
  // ...

If this doesn't help, then the problem is that at least one of your dependencies is different from the previous render. You can debug this problem by manually logging your dependencies to the console:

  const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);
  console.log([todos, tab]);

You can then right-click on the arrays from different re-renders in the console and select "Store as a global variable" for both of them. Assuming the first one got saved as temp1 and the second one got saved as temp2, you can then use the browser console to check whether each dependency in both arrays is the same:

Object.is(temp1[0], temp2[0]); // Is the first dependency the same between the arrays?
Object.is(temp1[1], temp2[1]); // Is the second dependency the same between the arrays?
Object.is(temp1[2], temp2[2]); // ... and so on for every dependency ...

When you find which dependency breaks memoization, either find a way to remove it, or memoize it as well.


I need to call useMemo for each list item in a loop, but it's not allowed

Suppose the Chart component is wrapped in memo. You want to skip re-rendering every Chart in the list when the ReportList component re-renders. However, you can't call useMemo in a loop:

```js {expectedErrors: {'react-compiler': [6]}} {5-11} function ReportList({ items }) { return (

{items.map(item => { // 🔴 You can't call useMemo in a loop like this: const data = useMemo(() => calculateReport(item), [item]); return (
); })}
); }


Instead, extract a component for each item and memoize data for individual items:

```js {5,12-18}
function ReportList({ items }) {
  return (
    <article>
      {items.map(item =>
        <Report key={item.id} item={item} />
      )}
    </article>
  );
}

function Report({ item }) {
  // ✅ Call useMemo at the top level:
  const data = useMemo(() => calculateReport(item), [item]);
  return (
    <figure>
      <Chart data={data} />
    </figure>
  );
}

Alternatively, you could remove useMemo and instead wrap Report itself in memo. If the item prop does not change, Report will skip re-rendering, so Chart will skip re-rendering too:

```js {5,6,12} function ReportList({ items }) { // ... }

const Report = memo(function Report({ item }) { const data = calculateReport(item); return (

); }); ```


Sitemap

Overview of all docs pages