Sub topic 4
Passing handlers between components
This chapter assumes you know JavaScript arrow functions, basic JSX, how props work, and the basics of useState. You have already attached a handler to a DOM element. Now you will pass handlers from one component to another.
Why pass handlers as props
Data flows down in React: a parent passes props to a child. Handlers let information flow back up. The parent owns the logic (often the state), and the child only knows that "something happened."
A child component such as SaveButton should not decide what saving means. The parent decides, and the child calls the function it was given.
Naming: onX and handleX
React code follows a convention that makes the direction of a handler clear.
| Where | Pattern | Example |
|---|---|---|
| Prop name on a component | `onX` | `onSelect`, `onClose` |
| Function that implements it | `handleX` | `handleSelect`, `handleClose` |
The onX name describes the event from the child's point of view. The handleX name describes the work from the parent's point of view. A parent writes onSelect={handleSelect}.
A worked example
The List component renders buttons. It does not know what selecting an item does. It calls onSelect with the item's id.
function List({ items, onSelect }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>
<button onClick={() => onSelect(item.id)}>{item.name}</button>
</li>
))}
</ul>
);
}The inline arrow function is needed here. Each button must call onSelect with its own id, so the handler needs an argument. Writing onClick={onSelect(item.id)} would call onSelect during render and pass its return value to onClick.
The parent supplies the behavior and keeps the state:
import { useState } from 'react';
function App() {
const [selectedId, setSelectedId] = useState(null);
const items = [
{ id: 1, name: 'Apples' },
{ id: 2, name: 'Pears' },
];
function handleSelect(id) {
setSelectedId(id);
}
return (
<div>
<List items={items} onSelect={handleSelect} />
<p>Selected: {selectedId ?? 'nothing'}</p>
</div>
);
}Passing a reference, not a call
Most mistakes in this area come from one confusion: passing a function versus calling it.
| Code | What happens |
|---|---|
| `onClick={handleClick}` | Passes the function. React calls it on click. |
| `onClick={() => handleClick(id)}` | Passes a new function that calls `handleClick` with `id` on click. |
| `onClick={handleClick(id)}` | Calls `handleClick` during render. Passes its result. Usually a bug. |
Common errors
- Calling during render.
onClick={handleClick()}runs the handler on every render. If the handler sets state, this can cause an infinite render loop. - Mismatched names. If the parent passes
onSelectbut the child readsonSelected, the value isundefined. Clicking then throws "onSelected is not a function". - Forgetting that props are optional. If a handler may be absent, guard the call with
onClose?.(). - Naming the DOM attribute wrong. On built-in elements such as
<button>, the prop must be the exact React event name (onClick). On your own components, the name is whatever you choose, so keep toonX.
Passing the event along
A child can forward the event object if the parent needs it. Most of the time, pass only the data the parent needs, such as an id or a value. That keeps the parent independent of the DOM.
function SearchBox({ onSearch }) {
return (
<input
onChange={e => onSearch(e.target.value)}
placeholder="Search"
/>
);
}The parent receives a plain string, so it can be tested and reused without a DOM event.
Exercise
A parent renders <List items={items} onSelect={handleSelect(5)} />. The page freezes with a "Too many re-renders" error, and handleSelect calls setSelectedId. What is wrong, and how do you fix it?
Show answer
handleSelect(5) is called during render instead of being passed as a function. It sets state, which triggers another render, which calls it again. Pass a function instead: onSelect={handleSelect} if List supplies the id, or onSelect={() => handleSelect(5)} to fix the argument.
Exercise
In List, why does each button use () => onSelect(item.id) instead of onSelect?
Show answer
onClick would call onSelect with the click event, not the item's id. The arrow function wraps the call so onSelect receives item.id.