memo
lets you skip re-rendering a component when its props are unchanged.
const MemoizedComponent = memo(SomeComponent, arePropsEqual?)
Usage
Skipping re-rendering when props are unchanged
React normally re-renders a component whenever its parent re-renders. With memo
, you can create a component that React will not re-render when its parent re-renders so long as its new props are the same as the old props. Such a component is said to be memoized.
To memoize a component, wrap it in a call to memo
and use the value that it returns in place of your original component:
const Greeting = memo(function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
});
export default Greeting;
A React component should always have pure rendering logic. This means that it must return the same output if its props, state, and context havenât changed. By using memo
, you are telling React that your component complies with this requirement, so React doesnât need to re-render as long as its props havenât changed. When you use memo
, your component will still re-render if its own state changes or if a context that itâs using changes.
In this example, notice that the Greeting
component re-renders whenever name
is changed (because thatâs one of its props), but not when address
is changed (because itâs not passed to Greeting
as a prop):
import { memo, useEffect, useState } from 'react'; export default function MyApp() { const [name, setName] = useState(''); const [address, setAddress] = useState(''); return ( <> <label> Name{': '} <input value={name} onChange={e => setName(e.target.value)} /> </label> <label> Address{': '} <input value={address} onChange={e => setAddress(e.target.value)} /> </label> <Greeting name={name} /> </> ); } const Greeting = memo(function Greeting({ name }) { console.log("Greeting was rendered at", new Date().toLocaleTimeString()); return <h3>Hello{name && ', '}{name}!</h3>; });
Deep Dive
Should you add memo everywhere?
Should you add memo everywhere?
If your app is like this site, and most interactions are coarse (like replacing a page or an entire section), memoization is usually unnecessary. On the other hand, if your app is more like a drawing editor, and most interactions are granular (like moving shapes), then you might find memoization very helpful.
Optimizing with memo
is only valuable when your component re-renders often with the same exact props, and its re-rendering logic is expensive. If there is no perceptible lag when your component re-renders, memo
is unnecessary. Keep in mind that memo
is completely useless if the props passed to your component are always different, such as if you pass an object or a plain function defined during rendering. This is why you will often need useMemo
and useCallback
together with memo
.
There is no benefit to wrapping a component in memo
in other cases. There is no significant harm to doing that either, so some teams choose to not think about individual cases, and memoize as much as possible. The downside of this approach is that code becomes less readable. Also, not all memoization is effective: a single value thatâs âalways newâ is enough to break memoization for an entire component.
In practice, you can make a lot of memoization unnecessary by following a few principles:
- When a component visually wraps other components, let it accept JSX as children. This way, when the wrapper component updates its own state, React knows that its children donât need to re-render.
- Prefer local state and donât lift state up any further than necessary. For example, donât keep transient state like forms and whether an item is hovered at the top of your tree or in a global state library.
- Keep your rendering logic pure. If re-rendering a component causes a problem or produces some noticeable visual artifact, itâs a bug in your component! Fix the bug instead of adding memoization.
- Avoid unnecessary Effects that update state. Most performance problems in React apps are caused by chains of updates originating from Effects that cause your components to render over and over.
- Try to remove unnecessary dependencies from your Effects. For example, instead of memoization, itâs often simpler to move some object or a function inside an Effect or outside the component.
If a specific interaction still feels laggy, use the React Developer Tools profiler to see which components would benefit the most from memoization, and add memoization where needed. These principles make your components easier to debug and understand, so itâs good to follow them in any case. In the long term, weâre researching doing granular memoization automatically to solve this once and for all.
Updating a memoized component using state
Even when a component is memoized, it will still re-render when its own state changes. Memoization only has to do with props that are passed to the component from its parent.
import { memo, useEffect, useState } from 'react'; export default function MyApp() { const [name, setName] = useState(''); const [address, setAddress] = useState(''); return ( <> <label> Name{': '} <input value={name} onChange={e => setName(e.target.value)} /> </label> <label> Address{': '} <input value={address} onChange={e => setAddress(e.target.value)} /> </label> <Greeting name={name} /> </> ); } const Greeting = memo(function Greeting({ name }) { console.log('Greeting was rendered at', new Date().toLocaleTimeString()); const [greeting, setGreeting] = useState('Hello'); return ( <> <h3>{greeting}{name && ', '}{name}!</h3> <GreetingSelector value={greeting} onChange={setGreeting} /> </> ); }); function GreetingSelector({ value, onChange }) { return ( <> <label> <input type="radio" checked={value === 'Hello'} onChange={e => onChange('Hello')} /> Regular greeting </label> <label> <input type="radio" checked={value === 'Hello and welcome'} onChange={e => onChange('Hello and welcome')} /> Enthusiastic greeting </label> </> ); }
If you set a state variable to its current value, React will skip re-rendering your component even without memo
. You may still see your component function being called an extra time, but the result will be discarded.
Updating a memoized component using a context
Even when a component is memoized, it will still re-render when a context that itâs using changes. Memoization only has to do with props that are passed to the component from its parent.
import { createContext, memo, useContext, useEffect, useState } from 'react'; const ThemeContext = createContext(null); export default function MyApp() { const [theme, setTheme] = useState('dark'); function handleClick() { setTheme(theme === 'dark' ? 'light' : 'dark'); } return ( <ThemeContext.Provider value={theme}> <button onClick={handleClick}> Switch theme </button> <Greeting name="Taylor" /> </ThemeContext.Provider> ); } const Greeting = memo(function Greeting({ name }) { console.log("Greeting was rendered at", new Date().toLocaleTimeString()); const theme = useContext(ThemeContext); return ( <h3 className={theme}>Hello, {name}!</h3> ); });
To make your component re-render only when a part of some context changes, split your component in two. Read what you need from the context in the outer component, and pass it down to a memoized child as a prop.
Minimizing props changes
When you use memo
, your component re-renders whenever any prop is not shallowly equal to what it was previously. This means that React compares every prop in your component with the previous value of that prop using the Object.is
comparison. Note that Object.is(3, 3)
is true
, but Object.is({}, {})
is false
.
To get the most out of memo
, minimize the times that the props change. For example, if the prop is an object, prevent the parent component from re-creating that object every time by using useMemo
:
function Page() {
const [name, setName] = useState('Taylor');
const [age, setAge] = useState(42);
const person = useMemo(
() => ({ name, age }),
[name, age]
);
return <Profile person={person} />;
}
const Profile = memo(function Profile({ person }) {
// ...
});
A better way to minimize props changes is to make sure the component accepts the minimum necessary information in its props. For example, it could accept individual values instead of a whole object:
function Page() {
const [name, setName] = useState('Taylor');
const [age, setAge] = useState(42);
return <Profile name={name} age={age} />;
}
const Profile = memo(function Profile({ name, age }) {
// ...
});
Even individual values can sometimes be projected to ones that change less frequently. For example, here a component accepts a boolean indicating the presence of a value rather than the value itself:
function GroupsLanding({ person }) {
const hasGroups = person.groups !== null;
return <CallToAction hasGroups={hasGroups} />;
}
const CallToAction = memo(function CallToAction({ hasGroups }) {
// ...
});
When you need to pass a function to memoized component, either declare it outside your component so that it never changes, or useCallback
to cache its definition between re-renders.
Specifying a custom comparison function
In rare cases it may be infeasible to minimize the props changes of a memoized component. In that case, you can provide a custom comparison function, which React will use to compare the old and new props instead of using shallow equality. This function is passed as a second argument to memo
. It should return true
only if the new props would result in the same output as the old props; otherwise it should return false
.
const Chart = memo(function Chart({ dataPoints }) {
// ...
}, arePropsEqual);
function arePropsEqual(oldProps, newProps) {
return (
oldProps.dataPoints.length === newProps.dataPoints.length &&
oldProps.dataPoints.every((oldPoint, index) => {
const newPoint = newProps.dataPoints[index];
return oldPoint.x === newPoint.x && oldPoint.y === newPoint.y;
})
);
}
If you do this, use the Performance panel in your browser developer tools to make sure that your comparison function is actually faster than re-rendering the component. You might be surprised.
When you do performance measurements, make sure that React is running in the production mode.
Reference
memo(Component, arePropsEqual?)
Call memo
outside of any components to define a memoized version of a component. This memoized component will usually not be re-rendered when its component is re-rendered as long as its props have not changed. But React may still re-render it: memoization is only a performance optimization, not a guarantee.
import { memo } from 'react';
function SomeComponent(props) {
// ...
}
const MemoizedComponent = memo(SomeComponent);
Parameters
Component
: The component that you want to memoize. Thememo
does not modify this component, but returns a new, memoized component instead. Any valid React component, including functions andforwardRef
components, is accepted.optional
arePropsEqual
: A function that accepts two arguments: the componentâs previous props, and its new props. It should returntrue
if the old and new props are equal: that is, if the component will render the same output and behave in the same way with the new props as with the old. Otherwise it should returnfalse
.
Returns
memo
returns a new React component. It behaves the same as the component provided to memo
except that React will not always re-render it when its parent is being re-rendered unless its props have changed.
Troubleshooting
My component re-renders when a prop is an object, array, or function
React compares old and new props by shallow equality: that is, it considers whether each new prop is reference-equal to the old prop. If you create a new object or array each time the parent is re-rendered, even if the individual elements are each the same, React will still consider it to be changed. Similarly, if you create a new function when rendering the parent component, React will consider it to have changed even if the function has the same definition. Avoid this by simplifying props or memoizing props in the parent component.