Stable handler
- React course
- Intermediate
- Lesson 35/80
- 5 min
Write a stable selection handler with useCallback.
Stable handler
This lesson writes the StatsRow component. Each row has a click handler. Stabilized with useCallback; no new function is born on every render.
A stable handler keeps the same reference when passed as a prop to a child. A React.memo'd child thus avoids needless renders.
The handler usually takes a parameter like (id) => { ... }. Stabilized with useCallback((id) => console.log(id), []) without dependencies.
Handler parameter
The row click handler must know which row was clicked. Two paths: take id as parameter, or create an inline function inside the row.
The second path births a new function on every render; it breaks memo. The first path is preferred: const handleClick = useCallback((id) => { ... }, []). Inside the row, call onClick={() => handleClick(row.id)}.
Inline functions also regenerate every render but are acceptable here; because memo is on the row component, not inside it. The whole approach must be balanced.
Practice Write StatsRow
Complete the skeleton. Write an App component. Define ids with useState([1,2,3]). Define handleClick with useCallback((id) => console.log(id), []). Inside <ul>, render ids.map(id => <li key={ '{ id }' } onClick={ '{ () => handleClick(id) }' }>{ '{ id }' }</li>). Export it.
Starter code
import { useState, useCallback } from "react";
// Write the App component hereSample solution
import { useState, useCallback } from "react";
function App() {
const [ids] = useState([1, 2, 3]);
const handleClick = useCallback((id) => console.log(id), []);
return (
<ul>
{ids.map((id) => (
<li key={id} onClick={() => handleClick(id)}>{id}</li>
))}
</ul>
);
}
export default App;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a stable handler prevent?
- CSS changes
- useEffect
- useState
- Child's needless render Correct answer
Explanation: Prevents needless child render.
2 useCallback dep
A handler with no deps is stabilized with ____.
A handler with no deps is stabilized with useCallback ve [].
Explanation: The answer: useCallback and [].
3 Match the stable handler steps
| Term | Meaning |
|---|---|
useCallback |
stabilizes |
[] |
no deps |
id |
parameter |
handleClick(row.id) |
call |