React memo
is a higher-order component (HOC) used to optimize functional components by preventing unnecessary re-renders. It’s especially useful when your component re-renders with the same props, saving performance.
1. What is React.memo
?
React.memo
is a wrapper around functional components that tells React to only re-render the component if its props change.
2. Basic Syntax
import React from 'react'; const MyComponent = React.memo((props) => { console.log('Rendered:', props.name); return <div>Hello, {props.name}!</div>; }); export default MyComponent;
Key Point: If props.name
doesn’t change, the component won’t re-render.
3. When to Use React.memo
Use it when:
- The component is pure (output depends only on props).
- Re-renders are costly or the component tree is deep.
4. Example Without React.memo
import React, { useState } from 'react'; const Child = (props) => { console.log('Child rendered!'); return <p>Child: {props.value}</p>; }; const Parent = () => { const [count, setCount] = useState(0); return ( <div> <button onClick={() => setCount(count + 1)}>Increment</button> <Child value="Hello" /> </div> ); }; export default Parent;
Issue: The Child
component renders every time you click the button, even though props.value
never changes.
5. Optimizing with React.memo
import React, { useState } from 'react'; const Child = React.memo((props) => { console.log('Child rendered!'); return <p>Child: {props.value}</p>; }); const Parent = () => { const [count, setCount] = useState(0); return ( <div> <button onClick={() => setCount(count + 1)}>Increment</button> <Child value="Hello" /> </div> ); }; export default Parent;
Result: Now, the Child
component doesn’t re-render unless props.value
changes.
6. Using React.memo
with a custom comparison
By default, React.memo
does a shallow comparison of props. If you need deeper checks, pass a custom comparison function.
const Child = React.memo( (props) => { console.log('Child rendered!'); return <p>Child: {props.data.text}</p>; }, (prevProps, nextProps) => { return prevProps.data.text === nextProps.data.text; // Custom comparison } );
Things to Remember
- Avoid overusing
React.memo
. It adds complexity. - Not useful if props always change.
- Pair with React DevTools to check re-render behavior.