Sibling re-render
- React course
- Intermediate
- Lesson 26/80
- 4 min
Learn how useCallback prevents needless renders of child components.
Sibling re-render
In React, when a component's state changes, all child components re-render. This can cause performance issues. The useCallback + React.memo pair solves this.
Example: App has count and text states. ExpensiveList takes only text as a prop. Even if count changes, ExpensiveList re-renders needlessly.
The fix: wrap ExpensiveList with React.memo, keep the function prop stable with useCallback. So it only renders when the prop truly changes.
Prop equality
React.memo by default does a shallow compare across all props. Objects and functions are compared by reference; primitives by value.
So functions or objects created fresh on every render cause React.memo'd components to re-render. useCallback and useMemo prevent these new references.
Sometimes shallow comparison isn't enough; a custom comparator is needed. We'll cover that in the next group.
Practice App stable handler
Complete the skeleton. Write an App component. Define count with useState(0). Define handleAdd with useCallback(() => setCount(c => c + 1), []). Show <button onClick={ '{ handleAdd }' }>Add</button> and <p>{ '{ count }' }</p>. Export it.
Starter code
import { useState, useCallback } from "react";
// Write the App component hereSample solution
import { useState, useCallback } from "react";
function App() {
const [count, setCount] = useState(0);
const handleAdd = useCallback(() => setCount((c) => c + 1), []);
return (
<div>
<p>{count}</p>
<button onClick={handleAdd}>Add</button>
</div>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is useCallback most useful?
- In a stateless component
- Inside useEffect
- When passing a prop to a React.memo child Correct answer
- In CSS animation
Explanation: When passing prop to a React.memo child.
2 React.memo role
React.memo prevents re-render when ____ are equal.
React.memo prevents re-render when prop'lar are equal.
Explanation: React.memo prevents when props equal.
3 Match the stable reference steps
| Term | Meaning |
|---|---|
useCallback |
function stable |
React.memo |
child skip |
shallow |
shallow |
prop |
compare |