How to Use React.memo
Skipping unnecessary re-renders of a component with React.memo.
When a React component re-renders, all of its children re-render too, even if
their props didn't change. Usually that's fast enough not to notice. But with a
long list or a heavy component, those extra renders can make typing or scrolling
feel slow. React.memo lets a component skip a render when its props are the
same as last time.
React.memo wraps a component and only re-renders it when its props change.
Basic Usage
Wrap the component in React.memo:
import React from "react"const TodoItem = React.memo(function TodoItem({ todo }) {console.log("rendering", todo.title)return <li>{todo.title}</li>})
The component works exactly the same. The only difference is React compares the new props to the old ones before rendering it.
Seeing It Work
Here the parent re-renders on every keystroke because the input's value is in its state:
import React, { useState } from "react"function TodoApp({ initialTodos }) {const [todos, setTodos] = useState(initialTodos)const [newTodo, setNewTodo] = useState("")return (<div><input value={newTodo} onChange={(e) => setNewTodo(e.target.value)} /><ul>{todos.map((todo) => (<TodoItem key={todo.id} todo={todo} />))}</ul></div>)}
Without React.memo, every TodoItem would log on every keystroke. With it,
none of them do, since each todo is the same object it was before.
Watch Out for Functions and Objects
React.memo does a shallow comparsion. A function or object created during
render is a new one every time, so it counts as a changed prop:
<TodoItemkey={todo.id}todo={todo}onDelete={() => deleteTodo(todo.id)} // new function every render/>
This breaks the memo, and the item re-renders anyway. Wrap the function in
useCallback so it stays the same between renders (there's more on that in
When to Use useMemo and useCallback):
const handleDelete = useCallback((id) => {setTodos((prevTodos) => prevTodos.filter((todo) => todo.id !== id))}, [])// in the list<TodoItem key={todo.id} todo={todo} onDelete={handleDelete} />
Then the item calls it with its own id:
const TodoItem = React.memo(function TodoItem({ todo, onDelete }) {return (<li>{todo.title}<button onClick={() => onDelete(todo.id)}>Delete</button></li>)})
When to Use React.memo
React.memo is worth it for a component that renders often with the same props,
like items in a long list, or one that's slow to render. For small components it
adds a comparison without saving much, so there's no need to wrap everything.
Use the React DevTools Profiler to see which components are rendering more than
they should.
Have some feedback on this post? .