What is React.memo in React: Simple Explanation and Usage
React.memo is a higher-order component that wraps a functional component to prevent unnecessary re-renders by memoizing its output. It only re-renders the component if its props change, improving performance in React apps.How It Works
Imagine you have a friend who only wants to hear new information and ignores repeated stories. React.memo works similarly by remembering the last props a component received. If the new props are the same as before, React skips re-rendering that component to save time and resources.
This is useful because React normally re-renders components whenever their parent renders, even if the props didn’t change. React.memo compares the previous and new props using a shallow comparison (checks if the values are the same). If nothing changed, it reuses the last rendered output.
Think of it like a shortcut that avoids repeating work when the input stays the same, making your app faster and smoother.
Example
This example shows a simple counter with a child component wrapped in React.memo. The child only re-renders when its props change.
import React, { useState } from 'react'; const Child = React.memo(({ count }) => { console.log('Child rendered'); return <div>Count: {count}</div>; }); export default function App() { const [count, setCount] = useState(0); const [other, setOther] = useState(false); return ( <div> <Child count={count} /> <button onClick={() => setCount(count + 1)}>Increment Count</button> <button onClick={() => setOther(!other)}>Toggle Other State</button> </div> ); }
When to Use
Use React.memo when you have functional components that receive props but don’t need to update unless those props change. It helps avoid slowdowns in apps with many components or expensive rendering.
Common cases include:
- Pure components that render the same output for the same props.
- Components that receive large data objects or functions as props.
- Lists or tables where only some items change.
However, avoid overusing it on simple components because the prop comparison itself has a small cost. Use it when you notice performance issues or unnecessary re-renders.
Key Points
React.memomemoizes functional components to skip re-renders when props are unchanged.- It uses shallow comparison of props by default.
- You can provide a custom comparison function for complex props.
- It improves performance by reducing unnecessary rendering.
- Not always needed; use when re-renders cause slowdowns.
Key Takeaways
React.memo prevents re-rendering of functional components when props don’t change.