Skip to main content
Practice Problems

What is React.memo and why is it needed

React.memo is a higher order function (HOC) in React that allows memoizing functional components.

It prevents unnecessary re-renders if props haven't changed.


How Does React.memo Work?

When you wrap component in React.memo, React compares current and previous props (by default — shallowly) and skips re-render if they remained the same.


Syntax

jsx
const MyComponent = React.memo((props) => { // component });

Example: without React.memo

jsx
const Button = ({ onClick }) => { console.log("🔁 Button rendered"); return <button onClick={onClick}>Click me</button>; }; function App() { const [count, setCount] = useState(0); return ( <> <Button onClick={() => console.log("clicked")} /> <button onClick={() => setCount(count + 1)}>+1</button> </> ); }

Even when clicking +1, Button will re-render because new onClick function is created at every render.

With React.memo + useCallback

jsx
const Button = React.memo(({ onClick }) => { console.log("✅ Button rendered"); return <button onClick={onClick}>Click me</button>; }); function App() { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("clicked"); }, []); return ( <> <Button onClick={handleClick} /> <button onClick={() => setCount(count + 1)}>+1</button> </> ); }

Now Button doesn't re-render if handleClick hasn't changed.

When to Use React.memo?

Useful if:

  • Component often receives same props
  • It's computationally heavy (e.g., contains nested lists, charts)
  • You want to avoid unnecessary re-renders

Not needed if:

  • Component is small and simple
  • Props are always different (e.g., function created anew every time without useCallback)
  • No performance issues

Custom Props Comparison

If you need to control comparison manually:

jsx
React.memo(Component, (prevProps, nextProps) => { return prevProps.value === nextProps.value; });

Conclusion:

React.memo helps optimize performance by avoiding unnecessary component re-renders if their props haven't changed. But it should be used thoughtfully and when needed.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems