React useMemo Hook
memo is a React higher-order component (HOC) used to optimize performance by skipping the re-rendering of a component if its props have not changed
The React useMemo Hook returns a memoized value.
Think of memoization as caching a value so that it does not need to be recalculated.
The useMemo Hook only runs when one of its dependencies update.
This can improve performance.
The useMemo and useCallback Hooks are similar:
useMemo returns a memoized value.
Without useMemo
The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly running.
Basic Syntax & Example
import { memo } from 'react';
const EmployeeCard = memo(({ name, role }) => {
console.log("EmployeeCard rendered");
return (
<div className="card">
<h3>{name}</h3>
<p>{role}</p>
</div>
);
});
export default EmployeeCard;
When Should You Use It?
Do not wrap every component in memo.
The comparison logic itself carries an overhead penalty, which can make your app slower if misused.
Only consider using memo when:
The component is pure (it always renders the same output given the same props).
The component renders frequently.
The component usually receives the exact same props over and over.
Top comments (0)