Memoization in React is an optimization technique used to avoid unnecessary re-computations or re-renders by caching the result of expensive operations and reusing it when the same inputs occur again.
In interviews, you can explain it like this:
What is Memoization in React?
Memoization is a performance optimization technique where React remembers (caches) the output of a function or component and returns the cached result instead of recalculating it, if the inputs haven’t changed.
Why is it used?
React re-renders components frequently. Without optimization, this can lead to:
-
Recalculating expensive logic again and again
-
Re-rendering child components unnecessarily
-
Performance issues in large applications
Memoization helps to:
-
Reduce unnecessary renders
-
Improve performance
-
Avoid redundant calculations
Types of Memoization in React
1. React.memo() (Component Memoization)
Used for functional components.
It prevents re-rendering if props are unchanged.
const Child = React.memo(function Child({ name }) {
console.log("Child rendered");
return <div>{name}</div>;
});
Child will only re-render if name changes.
2. useMemo() (Value Memoization)
Used to cache expensive calculations.
const result = useMemo(() => {
return heavyComputation(data);
}, [data]);
The computation runs only when data changes.
3. useCallback() (Function Memoization)
Used to memoize functions so they don’t get recreated on every render.
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Useful when passing callbacks to memoized child components.
Real Interview Example
Imagine a list filtering function:
const filteredUsers = useMemo(() => {
return users.filter(user => user.active);
}, [users]);
Without useMemo, filtering runs on every render.
With useMemo, it runs only when users changes.
Key Interview Points
-
Memoization improves performance by caching results
-
Helps prevent unnecessary re-renders and recalculations
-
Common tools:
-
React.memo -
useMemo -
useCallback
-
-
Should be used only when needed, because overuse can add overhead
One-line Answer
Memoization in React is a performance optimization technique that caches computed values or components to avoid unnecessary recalculations or re-renders when the inputs remain unchanged.
