React.memo:
- React.memo is a performance optimization tool in React that prevents a functional component from re-rendering if its props have not changed.
How It works:
- When a parent component attempts to update, React.memo performs a shallow comparison (Object.is) on the component's previous props and its new props:
- If props are identical: React skips re-rendering the component entirely, saving processing power.
- If props have changed: React proceeds with the re-render to reflect the new data.
Syntax Example:
import { memo } from 'react';
const MyComponent = memo(({ title, description }) => {
console.log("Component rendered!");
return (
<div>
<h3>{title}</h3>
<p>{description}</p>
</div>
);
});
export default MyComponent;
When Should You Use It?
- You should not wrap every single component in memo because the comparison logic itself has a minor performance cost.
It is best used when:
The component is pure: It always renders the same output given the exact same props.
The component re-renders frequently: It is forced to re-render constantly because its parent component updates often.
The component is heavy: It contains a large UI tree or carries out expensive UI layout processes.
Difference between React.memo vs useMemo:
useMemo:
- useMemo is a React Hook that caches (memoizes) the result of a calculation between re-renders.
- By using the official React useMemo Hook, you optimize performance by ensuring that expensive, resource-heavy calculations only run when their specific inputs change, rather than on every single render.
How It Works (The Syntax):
useMemo accepts two arguments:
- a calculation function
- an array of dependencies.
import React, { useMemo } from 'react';
const memoizedValue = useMemo(() => {
// 1. Perform expensive calculation here
return someExpensiveCalculation(a, b);
}, [a, b]); // 2. Only re-run if 'a' or 'b' changes
First Argument: A function that takes no arguments and returns the value you want to cache.
Second Argument: A dependency array containing all reactive values (props, state, or variables) used inside the function.
Use Cases:
- Skipping expensive recalculations
- Skipping re-rendering of child components
- Memoizing a dependency for another Hook


Top comments (0)