React re-renders a component whenever its state, props, or context change.
To avoid unnecessary re-renders and improve performance, use the following tools and techniques:
✅ 1. Use React.memo() for Component Memoization
Wrap your functional component with React.memo() so it only re-renders when its props change.
const Child = React.memo(function Child({ value }) {
console.log("Child rendered");
return <div>{value}</div>;
});
✔ Prevents re-render when parent re-renders
✔ Shallow compares props automatically
✅ 2. Use useCallback() for Functions
React re-renders child components when you pass new function references.useCallback() memoizes the function so the reference stays the same.
const handleClick = useCallback(() => {
console.log("clicked");
}, []);
✔ Prevents child components from re-rendering due to recreated functions
✅ 3. Use useMemo() for Expensive Computations
Memoize heavy calculations so they don’t recompute on every render.
const sortedItems = useMemo(() => items.sort(), [items]);
✔ Saves time on repeated renders
✅ 4. Avoid Anonymous Functions in JSX
❌ Avoid:
<Child onClick={() => doSomething()} />
✔ Instead:
const handleClick = useCallback(doSomething, []);
<Child onClick={handleClick} />
✅ 5. Avoid Inline Objects in Props
❌ This causes new object reference every render:
<Child style={{ color: "red" }} />
✔ Fix:
const style = useMemo(() => ({ color: "red" }), []);
<Child style={style} />
✅ 6. Split Large Components (Component-level Optimization)
Break huge components into smaller memoized ones.
const Header = React.memo(HeaderComponent);
✔ Only re-renders the part that changes
✅ 7. Use key properly in lists
Wrong keys → more unnecessary re-renders.
{items.map(item => <Item key={item.id} />)}
✔ Stable keys = stable DOM = fewer renders
⭐ Bonus: React 18 Automatic Batching
React 18 batches multiple state updates → fewer re-renders automatically.
🎯 Short Interview Answer
You can prevent unnecessary re-renders by using
React.memo()to memoize components,useCallback()to memoize functions, anduseMemo()for expensive calculations.
Also avoid inline functions/objects in JSX and ensure proper key usage in lists.
Together, these techniques keep components from re-rendering when their inputs haven't actually changed.