Sub topic 4
Passing Handlers Between Components
This chapter assumes you know JavaScript functions and arrow functions, basic JSX, how props work in React, and the basics of useState. It also assumes you can attach a handler such as onClick to a built-in element. Here the handler comes from a different component than the one that renders the element.
Why handlers travel as props
React data flows downward. A parent passes props to a child, and the child cannot change the parent's state directly. A child still needs a way to report that something happened, such as a click, a selection, or a changed value.
The solution is to pass a function as a prop. The parent defines what should happen. The child decides when to call the function. The parent owns the state and the logic, and the child stays a reusable piece of UI.
Naming: onX for props, handleX for functions
React projects follow a convention that makes the direction of data easy to read.
| Where | Pattern | Example |
|---|---|---|
| Prop name on your own component | `on` + event | `onSelect`, `onClose`, `onSearchChange` |
| Function defined in the parent | `handle` + event | `handleSelect`, `handleClose` |
| Built-in elements | fixed by React | `onClick`, `onChange`, `onSubmit` |
The prop name describes what happened from the child's point of view. The function name describes what the parent does about it. You then write onSelect={handleSelect}, which reads as "when a selection happens, run handleSelect."
React does not enforce these names. Props on your own components can have any name. The convention matters because it makes it obvious which props are callbacks.
A complete example
The List component below comes from the chapter plan. It does not know what selecting means. It only calls onSelect with the id of the clicked item.
import { useState } from 'react';
const ITEMS = [
{ id: 1, name: 'Apples' },
{ id: 2, name: 'Bananas' },
{ id: 3, name: 'Cherries' },
];
function List({ items, onSelect }) {
return (
<ul>
{items.map(item => (
<li key={item.id}>
<button onClick={() => onSelect(item.id)}>{item.name}</button>
</li>
))}
</ul>
);
}
export default function App() {
const [selectedId, setSelectedId] = useState(null);
function handleSelect(id) {
setSelectedId(id);
}
const selected = ITEMS.find(item => item.id === selectedId);
return (
<div>
<List items={ITEMS} onSelect={handleSelect} />
<p>Selected: {selected ? selected.name : 'nothing yet'}</p>
</div>
);
}The state lives in App, so App can render the selection anywhere. A second component that needs the selection can receive selectedId as a prop. This is the pattern often called lifting state up.
Deciding what the child sends back
When a child calls a handler, you choose what to pass. There are two common choices.
- Pass the event. The child calls
onChange(e). The parent has to know about DOM events, which couples the two components. - Pass the meaningful value. The child calls
onChange(e.target.value)oronSelect(item.id). The parent receives plain data.
The second choice is usually better for your own components. It lets the child change its internal markup later without breaking its callers.
import { useState } from 'react';
function SearchBox({ query, onQueryChange }) {
return (
<input
value={query}
onChange={e => onQueryChange(e.target.value)}
placeholder="Search"
/>
);
}
export default function Page() {
const [query, setQuery] = useState('');
return (
<div>
<SearchBox query={query} onQueryChange={setQuery} />
<p>You typed: {query}</p>
</div>
);
}Passing setQuery directly is valid here. The state setter is a function that accepts the new value, so no wrapper is needed. Use a handleX wrapper when the parent has to do more than set one piece of state, such as validate the value or update two states.
Forwarding handlers through wrapper components
A wrapper such as Button does nothing with an onClick prop unless it passes the prop to an element. React treats onClick on a custom component as an ordinary prop.
function Button({ onClick, children }) {
return (
<button className="btn" onClick={onClick}>
{children}
</button>
);
}If a wrapper should accept every standard button attribute, collect the remaining props and spread them onto the element.
function Button({ children, ...rest }) {
return (
<button className="btn" {...rest}>
{children}
</button>
);
}
export default function Demo() {
return (
<Button onClick={() => alert('Clicked')} disabled={false}>
Press
</Button>
);
}Spreading is convenient, but it hides which props the component supports. Name the important handlers explicitly when the component has a defined interface. Spread the rest for pass-through attributes such as disabled, aria-*, and type.
Optional handlers
A child that works with or without a callback should not crash when the prop is missing. Use a guard or optional call.
function Dismissible({ onDismiss, children }) {
return (
<div>
{children}
<button onClick={() => onDismiss?.()}>Dismiss</button>
</div>
);
}onDismiss?.() calls the function only if it is defined. Without the ?., a missing prop produces TypeError: onDismiss is not a function when the user clicks.
Common errors
Calling the handler instead of passing it
// Wrong: runs during render, and passes its return value
<List items={ITEMS} onSelect={handleSelect(1)} />
// Right: passes the function itself
<List items={ITEMS} onSelect={handleSelect} />handleSelect(1) runs while React renders. If it sets state, React re-renders and the call runs again, which can cause a "Too many re-renders" error. When you need an argument, wrap the call: onSelect={() => handleSelect(1)}.
A name mismatch between parent and child
If the parent writes onSelected={handleSelect} and the child reads onSelect, the child's prop is undefined. Nothing fails until the user clicks, and then you get "is not a function." When a click does nothing or throws, compare the prop name on both sides first.
Expecting a custom component to attach the handler
Writing <Card onClick={handleClick} /> does not make Card clickable. The Card component must receive onClick and pass it to an element it renders, as Button did above.
Handlers that depend on stale values
A handler captures the props and state from the render in which it was created. A child that stores a handler somewhere long-lived, such as an effect or a timer, can end up calling an old version. Effects that use a handler prop must list it in their dependency array. The Modal example in the plan does this with [onClose].
Unneeded re-renders from changing function identity
A new function is created every time a component renders. If you pass it to a child wrapped in React.memo, the child sees a new prop each time and re-renders anyway. useCallback keeps the same function between renders when its dependencies have not changed.
import { memo, useCallback, useState } from 'react';
const Row = memo(function Row({ id, onRemove }) {
console.log('render row', id);
return <button onClick={() => onRemove(id)}>Remove {id}</button>;
});
export default function Rows() {
const [ids, setIds] = useState([1, 2, 3]);
const [count, setCount] = useState(0);
const handleRemove = useCallback(id => {
setIds(current => current.filter(x => x !== id));
}, []);
return (
<div>
<button onClick={() => setCount(c => c + 1)}>Clicks: {count}</button>
{ids.map(id => (
<Row key={id} id={id} onRemove={handleRemove} />
))}
</div>
);
}Clicking the counter re-renders Rows, but the Row components skip rendering because handleRemove keeps the same identity. The handler uses the functional form current => ... so it does not need ids in its dependency list.
Summary of the pattern
- Keep state in the closest parent that every component needing it shares.
- Define a
handleXfunction there. - Pass it to the child as an
onXprop. - In the child, call the prop from the built-in element's own handler, passing plain values rather than raw events when you can.
- Check that wrapper components forward the prop to a real element.
Exercise
A Toggle component renders <button onClick={onToggle}>Toggle</button>. The parent renders <Toggle onToggle={handleToggle()} />, and the page throws "Too many re-renders" because handleToggle calls setOn(o => !o). What is wrong, and what is the fix?
Show answer
The parent calls handleToggle() during render instead of passing the function. The call sets state, which triggers another render, which calls it again, in a loop. Pass the function itself: <Toggle onToggle={handleToggle} />. If an argument is needed, use an arrow function: onToggle={() => handleToggle(arg)}.
Exercise
You write a Card component and use <Card onClick={() => setOpen(true)}>Details</Card>. Clicking the card does nothing, and no error appears. Card is defined as function Card({ children }) { return <div className="card">{children}</div>; }. Why, and how do you fix it?
Show answer
Card never reads the onClick prop, so the handler is not attached to any element. Destructure it and pass it on: function Card({ children, onClick }) { return <div className="card" onClick={onClick}>{children}</div>; }. Alternatively, collect the rest props with ...rest and spread them onto the div.