Preventing unnecessary re-renders in React helps improve performance and ensures components only update when needed.
Here are the most effective strategies ๐
๐น 1. Use React.memo for Functional Components
React.memo prevents re-rendering if the props haven’t changed.
import React from "react";
const UserCard = React.memo(({ name, age }) => {
console.log("Rendered:", name);
return <p>{name} - {age}</p>;
});
โ
When to use:
If a child component receives the same props repeatedly, wrap it in React.memo().
๐น 2. Use useCallback for Functions
In React, functions are recreated on every render.useCallback memoizes them, preventing child re-renders caused by prop changes.
const Parent = () => {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(prev => prev + 1);
}, []);
return <Child onClick={increment} />;
};
โ
Without useCallback, the Child component would re-render every time.
๐น 3. Use useMemo for Expensive Calculations
useMemo memoizes computed values so they aren’t recalculated on every render.
const total = useMemo(() => {
return items.reduce((acc, item) => acc + item.price, 0);
}, [items]);
โ
Only recalculates total when items changes.
๐น 4. Avoid Inline Functions and Objects in JSX
Inline functions and objects create new references each render.
โ Bad:
<Child style={{ color: "red" }} onClick={() => setCount(count + 1)} />
โ Good:
const style = { color: "red" };
const handleClick = useCallback(() => setCount(c => c + 1), []);
<Child style={style} onClick={handleClick} />;
๐น 5. Proper State Management
- Keep local state as close as possible to where it’s needed.
- Avoid putting everything in a global store (Redux/Zustand).
- Break down large components into smaller, isolated ones.
๐น 6. Use key Properly in Lists
If keys are unstable (like using indexes), React re-renders unnecessarily.
Use unique IDs instead.
{users.map(user => <UserCard key={user.id} {...user} />)}
๐น 7. Use PureComponent or shouldComponentUpdate (Class Components)
For class-based components, these lifecycle methods prevent re-renders when props/state haven’t changed.
class Profile extends React.PureComponent {
render() {
return <div>{this.props.name}</div>;
}
}
โ Summary
| Technique | Purpose |
|---|---|
React.memo() |
Memoize functional components |
useCallback() |
Prevent function re-creation |
useMemo() |
Cache computed values |
| Proper keys | Avoid re-renders in lists |
| Localized state | Prevent parent → child cascade updates |
In short:
Use memoization (
React.memo,useCallback,useMemo), stable props, and minimal state to keep React rendering efficient.