useMemo·续1
```js src/TodoList.js active
import { filterTodos } from './utils.js'
export default function TodoList({ todos, theme, tab }) {
const visibleTodos = filterTodos(todos, tab);
return (
<div className={theme}>
<ul>
<p><b>Note: <code>filterTodos</code> is artificially slowed down!</b></p>
{visibleTodos.map(todo => (
<li key={todo.id}>
{todo.completed ?
<s>{todo.text}</s> :
todo.text
}
</li>
))}
</ul>
</div>
);
}
```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) { console.log('[ARTIFICIALLY SLOW] Filtering ' + todos.length + ' todos for "' + tab + '" tab.'); let startTime = performance.now(); while (performance.now() - startTime < 500) { // Do nothing for 500 ms to emulate extremely slow code }
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;
}
However, here is the same code with the artificial slowdown removed. Does the lack of useMemo feel noticeable or not?
```js src/App.js import { useState } from 'react'; import { createTodos } from './utils.js'; import TodoList from './TodoList.js';
const todos = createTodos();
export default function App() { const [tab, setTab] = useState('all'); const [isDark, setIsDark] = useState(false); return ( <> <button onClick={() => setTab('all')}> All </button> <button onClick={() => setTab('active')}> Active </button> <button onClick={() => setTab('completed')}> Completed </button> <br /> <label> <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} /> Dark mode </label> <hr /> <TodoList todos={todos} tab={tab} theme={isDark ? 'dark' : 'light'} /> </> ); }
```js src/TodoList.js active
import { filterTodos } from './utils.js'
export default function TodoList({ todos, theme, tab }) {
const visibleTodos = filterTodos(todos, tab);
return (
<div className={theme}>
<ul>
{visibleTodos.map(todo => (
<li key={todo.id}>
{todo.completed ?
<s>{todo.text}</s> :
todo.text
}
</li>
))}
</ul>
</div>
);
}
```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) { console.log('Filtering ' + todos.length + ' todos for "' + tab + '" 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 might not need memoization.
You can try increasing the number of todo items in utils.js and see how the behavior changes. This particular calculation wasn't very expensive to begin with, but if the number of todos grows significantly, most of the overhead will be in re-rendering rather than in the filtering. Keep reading below to see how you can optimize re-rendering with useMemo.
Skipping re-rendering of components
In some cases, useMemo can also help you optimize performance of re-rendering child components. To illustrate this, let's say this TodoList component passes the visibleTodos as a prop to the child List component:
```js {5} export default function TodoList({ todos, tab, theme }) { // ... return ( <div className={theme}> <List items={visibleTodos} /> </div> ); }
You've noticed that toggling the `theme` prop freezes the app for a moment, but if you remove `<List />` from your JSX, it feels fast. This tells you that it's worth trying to optimize the `List` component.
**By default, when a component re-renders, React re-renders all of its children recursively.** This is why, when `TodoList` re-renders with a different `theme`, the `List` component *also* re-renders. This is fine for components that don't require much calculation to re-render. But if you've verified that a re-render is slow, you can tell `List` to skip re-rendering when its props are the same as on last render by wrapping it in [`memo`:](/reference/react/memo)
```js {3,5}
import { memo } from 'react';
const List = memo(function List({ items }) {
// ...
});
With this change, List will skip re-rendering if all of its props are the same as on the last render. This is where caching the calculation becomes important! Imagine that you calculated visibleTodos without useMemo:
```js {2-3,6-7} export default function TodoList({ todos, tab, theme }) { // Every time the theme changes, this will be a different array... const visibleTodos = filterTodos(todos, tab); return ( <div className={theme}> {/ ... so List's props will never be the same, and it will re-render every time /} <List items={visibleTodos} /> </div> ); }
**In the above example, the `filterTodos` function always creates a *different* array,** similar to how the `{}` object literal always creates a new object. Normally, this wouldn't be a problem, but it means that `List` props will never be the same, and your [`memo`](/reference/react/memo) optimization won't work. This is where `useMemo` comes in handy:
```js {2-3,5,9-10}
export default function TodoList({ todos, tab, theme }) {
// Tell React to cache your calculation between re-renders...
const visibleTodos = useMemo(
() => filterTodos(todos, tab),
[todos, tab] // ...so as long as these dependencies don't change...
);
return (
<div className={theme}>
{/* ...List will receive the same props and can skip re-rendering */}
<List items={visibleTodos} />
</div>
);
}
By wrapping the visibleTodos calculation in useMemo, you ensure that it has the same value between the re-renders (until dependencies change). You don't have to wrap a calculation in useMemo unless you do it for some specific reason. In this example, the reason is that you pass it to a component wrapped in memo, and this lets it skip re-rendering. There are a few other reasons to add useMemo which are described further on this page.
[!INFO]
Memoizing individual JSX nodes
Instead of wrapping
Listinmemo, you could wrap the<List />JSX node itself inuseMemo:```js {3,6} export default function TodoList({ todos, tab, theme }) { const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]); const children = useMemo(() => <List items={visibleTodos} />, [visibleTodos]); return ( <div className={theme}> {children} </div> ); }
>
> The behavior would be the same. If the `visibleTodos` haven't changed, `List` won't be re-rendered.
>
> A JSX node like `<List items={visibleTodos} />` is an object like `{ type: List, props: { items: visibleTodos } }`. Creating this object is very cheap, but React doesn't know whether its contents is the same as last time or not. This is why by default, React will re-render the `List` component.
>
> However, if React sees the same exact JSX as during the previous render, it won't try to re-render your component. This is because JSX nodes are [immutable.](https://en.wikipedia.org/wiki/Immutable_object) A JSX node object could not have changed over time, so React knows it's safe to skip a re-render. However, for this to work, the node has to *actually be the same object*, not merely look the same in code. This is what `useMemo` does in this example.
>
> Manually wrapping JSX nodes into `useMemo` is not convenient. For example, you can't do this conditionally. This is usually why you would wrap components with [`memo`](/reference/react/memo) instead of wrapping JSX nodes.
>
#### Skipping re-rendering with `useMemo` and `memo`
In this example, the `List` component is **artificially slowed down** so that you can see what happens when a React component you're rendering is genuinely slow. Try switching the tabs and toggling the theme.
Switching the tabs feels slow because it forces the slowed down `List` to re-render. That's expected because the `tab` has changed, and so you need to reflect the user's new choice on the screen.
Next, try toggling the theme. **Thanks to `useMemo` together with [`memo`](/reference/react/memo), it’s fast despite the artificial slowdown!** The `List` skipped re-rendering because the `visibleTodos` array has not changed since the last render. The `visibleTodos` array has not changed because both `todos` and `tab` (which you pass as dependencies to `useMemo`) haven't changed since the last render.
```js src/App.js
import { useState } from 'react';
import { createTodos } from './utils.js';
import TodoList from './TodoList.js';
const todos = createTodos();
export default function App() {
const [tab, setTab] = useState('all');
const [isDark, setIsDark] = useState(false);
return (
<>
<button onClick={() => setTab('all')}>
All
</button>
<button onClick={() => setTab('active')}>
Active
</button>
<button onClick={() => setTab('completed')}>
Completed
</button>
<br />
<label>
<input
type="checkbox"
checked={isDark}
onChange={e => setIsDark(e.target.checked)}
/>
Dark mode
</label>
<hr />
<TodoList
todos={todos}
tab={tab}
theme={isDark ? 'dark' : 'light'}
/>
</>
);
}
```js src/TodoList.js active import { useMemo } from 'react'; import List from './List.js'; import { filterTodos } from './utils.js'
export default function TodoList({ todos, theme, tab }) { const visibleTodos = useMemo( () => filterTodos(todos, tab), [todos, tab] ); return ( <div className={theme}> <p><b>Note: <code>List</code> is artificially slowed down!</b></p> <List items={visibleTodos} /> </div> ); }
```js {expectedErrors: {'react-compiler': [5, 6]}} src/List.js
import { memo } from 'react';
const List = memo(function List({ items }) {
console.log('[ARTIFICIALLY SLOW] Rendering <List /> with ' + items.length + ' items');
let startTime = performance.now();
while (performance.now() - startTime < 500) {
// Do nothing for 500 ms to emulate extremely slow code
}
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.completed ?
<s>{item.text}</s> :
item.text
}
</li>
))}
</ul>
);
});
export default 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;
}
Always re-rendering a component
In this example, the List implementation is also artificially slowed down so that you can see what happens when some React component you're rendering is genuinely slow. Try switching the tabs and toggling the theme.
Unlike in the previous example, toggling the theme is also slow now! This is because there is no useMemo call in this version, so the visibleTodos is always a different array, and the slowed down List component can't skip re-rendering.
```js src/App.js import { useState } from 'react'; import { createTodos } from './utils.js'; import TodoList from './TodoList.js';
const todos = createTodos();
export default function App() { const [tab, setTab] = useState('all'); const [isDark, setIsDark] = useState(false); return ( <> <button onClick={() => setTab('all')}> All </button> <button onClick={() => setTab('active')}> Active </button> <button onClick={() => setTab('completed')}> Completed </button> <br /> <label> <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} /> Dark mode </label> <hr /> <TodoList todos={todos} tab={tab} theme={isDark ? 'dark' : 'light'} /> </> ); }
```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 (
<div className={theme}>
<p><b>Note: <code>List</code> is artificially slowed down!</b></p>
<List items={visibleTodos} />
</div>
);
}
```js {expectedErrors: {'react-compiler': [5, 6]}} src/List.js import { memo } from 'react';
const List = memo(function List({ items }) { console.log('[ARTIFICIALLY SLOW] Rendering <List /> with ' + items.length + ' items'); let startTime = performance.now(); while (performance.now() - startTime < 500) { // Do nothing for 500 ms to emulate extremely slow code }
return ( <ul> {items.map(item => ( <li key={item.id}> {item.completed ? <s>{item.text}</s> : item.text } </li> ))} </ul> ); });
export default 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;
}
});
}
label {
display: block;
margin-top: 10px;
}
.dark {
background-color: black;
color: white;
}
.light {
background-color: white;
color: black;
}
However, here is the same code with the artificial slowdown removed. Does the lack of useMemo feel noticeable or not?
```js src/App.js import { useState } from 'react'; import { createTodos } from './utils.js'; import TodoList from './TodoList.js';
const todos = createTodos();
export default function App() { const [tab, setTab] = useState('all'); const [isDark, setIsDark] = useState(false); return ( <> <button onClick={() => setTab('all')}> All </button> <button onClick={() => setTab('active')}> Active </button> <button onClick={() => setTab('completed')}> Completed </button> <br /> <label> <input type="checkbox" checked={isDark} onChange={e => setIsDark(e.target.checked)} /> Dark mode </label> <hr /> <TodoList todos={todos} tab={tab} theme={isDark ? 'dark' : 'light'} /> </> ); } ```
