Sub topic 3
Passing Callbacks Down So Children Can Request Changes
This chapter assumes you can write function components, use useState, destructure props, and attach an onChange or onClick handler. It builds on the idea that props flow one way, from parent to child. Here you will see how a child can still cause a change in the parent's data without breaking that rule.
The problem: props are read-only
Data in React moves down the tree. A parent passes props to a child, and the child reads them. The child must not change them. If a child assigns to a prop, React does not re-render, and the next render from the parent overwrites the change.
function Counter({ count }) {
// Wrong: this changes a local variable, not the parent's state.
// React is not told anything changed, so nothing re-renders.
function handleClick() {
count = count + 1;
}
return <button onClick={handleClick}>Count: {count}</button>;
}The child still needs a way to say "the user clicked, please update." The answer is to pass a function down as a prop. The parent owns the state and the function that changes it. The child calls the function when something happens.
A function is just another prop
In JavaScript, functions are values. You can store them in variables, pass them as arguments, and pass them as props. A prop that holds a function is usually called a callback. By convention, callback props are named onSomething, such as onChange, onSelect, or onDelete. The handler defined in the parent is often named handleSomething.
import { useState } from 'react';
function IncrementButton({ count, onIncrement }) {
return <button onClick={onIncrement}>Clicked {count} times</button>;
}
export default function App() {
const [count, setCount] = useState(0);
function handleIncrement() {
setCount(count + 1);
}
return <IncrementButton count={count} onIncrement={handleIncrement} />;
}Follow one click through this code:
- The user clicks the button inside
IncrementButton. - The
onClickhandler runs. It is theonIncrementfunction the parent passed in. - That function is
handleIncrement, defined inApp, so it callssetCountinApp's scope. - React re-renders
Appwith the new count. Apppasses the newcounttoIncrementButton, which shows it.
The child never changed anything. It reported an event, and the parent decided what to do.
Passing data back up through arguments
A callback can take arguments. This is how a child sends information to the parent, such as the text a user typed or the item they chose.
import { useState } from 'react';
function ColorPicker({ colors, onPick }) {
return (
<ul>
{colors.map(color => (
<li key={color}>
<button onClick={() => onPick(color)}>{color}</button>
</li>
))}
</ul>
);
}
export default function App() {
const [selected, setSelected] = useState('none');
return (
<>
<p>Selected: {selected}</p>
<ColorPicker
colors={['red', 'green', 'blue']}
onPick={setSelected}
/>
</>
);
}Two details matter here.
- The child wraps the call in an arrow function,
() => onPick(color), because each button must callonPickwith its own color. - The parent passes
setSelecteddirectly asonPick. A state setter is already a function that takes one value, so no wrapper is needed.
Passing a setter directly is fine when the child's argument is exactly the value you want to store. When the parent needs to transform the value or update several things at once, write a named handler instead.
function handlePick(color) {
setSelected(color.toUpperCase());
setPickCount(n => n + 1);
}Passing the setter or passing a handler
Both options work. They differ in how much the child can do to the parent's state.
| Approach | Example | What the child can do | Good when |
|---|---|---|---|
| Pass the setter | `onChange={setText}` | Set any value, including a function updater | The child's value maps directly to state |
| Pass a handler | `onChange={handleTextChange}` | Only what the handler allows | The parent validates, transforms, or updates several things |
A named handler also gives the parent one place to add rules later, such as trimming input or rejecting empty values. A child that receives the raw setter could bypass those rules. For small components the setter is fine. For shared components, prefer a handler that expresses intent, such as onAdd or onToggle, instead of exposing how state is stored.
Reading the event or the value
A DOM event handler receives an event object. A common design decision is whether the child passes the raw event up or extracts the value first.
function SearchBox({ query, onQueryChange }) {
return (
<input
value={query}
onChange={e => onQueryChange(e.target.value)}
/>
);
}Here the child unwraps e.target.value and calls onQueryChange with a plain string. The parent does not need to know the input is a DOM element. This keeps the callback's contract simple: onQueryChange(string). The same SearchBox could later be driven by a voice input without changing the parent. The examples in this tutorial use this style.
Common mistake: calling the function instead of passing it
The most frequent error with callbacks is writing parentheses where React expects a function reference.
import { useState } from 'react';
export default function Broken() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
// Wrong: handleClick() runs during render and returns undefined.
return <button onClick={handleClick()}>Add</button>;
}handleClick() is evaluated while React renders. It calls setCount, which schedules another render, which calls handleClick() again. React stops this with a "Too many re-renders" error. The fix is to pass the function itself, onClick={handleClick}, or wrap the call, onClick={() => handleClick()}.
Updating from the previous value
A callback closes over the values from the render in which it was created. If the handler can run several times before the next render, use the updater form of the setter so each call sees the latest state.
import { useState } from 'react';
function AddThree({ onAdd }) {
return <button onClick={onAdd}>Add 3</button>;
}
export default function App() {
const [total, setTotal] = useState(0);
function handleAdd() {
setTotal(t => t + 1);
setTotal(t => t + 1);
setTotal(t => t + 1);
}
return (
<>
<p>Total: {total}</p>
<AddThree onAdd={handleAdd} />
</>
);
}With setTotal(total + 1) written three times, the total would rise by 1 per click, because every call reads the same total from that render. With t => t + 1, React applies the three updates in order and the total rises by 3.
Naming and shape of callback props
Consistent naming makes component interfaces easy to read.
- Name the prop for the event from the child's point of view:
onSubmit,onSelect,onRemove. - Name the parent's function for what it does:
handleSubmit,handleSelect,handleRemove. - Pass the smallest useful data. Send an
idor a value, not a whole event or a whole state object, unless the parent needs it. - Treat the callback as part of the component's public interface. If you rename it, update every caller.
Props that are functions can also be optional. A child can guard the call, for example onClose?.(), so the parent may omit it. Required callbacks are clearer for components that cannot work without them. Use PropTypes or TypeScript to state which is which.
Why this matters for lifting state
This pattern is the second half of lifting state up. When two siblings need the same data, the parent owns the state and passes two things to each child: the current value as a prop, and a callback that asks for a change. The children stay simple. They display what they are given and report what the user did.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function App() {
const [text, setText] = useState('');
return (
<>
<Field label="First" value={text} onChange={setText} />
<Field label="Second" value={text} onChange={setText} />
</>
);
}Both fields call the same setText. Whichever one the user types in, the parent updates once and both receive the new value. The next chapters explain why this arrangement solves the sibling synchronization problem and how to decide where such state should live.
Edge cases to keep in mind
- Callbacks do not run on their own. A child calls the function only when its own event fires. Passing a callback does not subscribe the parent to anything else.
- New function each render. A handler defined inside a component is a new function on every render. This rarely matters. It only affects performance when a memoized child compares props, and you should measure before reaching for
useCallback. - Events do not bubble through props. A callback prop is an ordinary function call. It is not a DOM event, so
stopPropagationhas no effect on it. - Return values are usually ignored. React ignores what an event handler returns. If a child needs an answer from the parent, pass the answer back down as a prop on the next render instead of depending on a return value.
- Stale values in delayed callbacks. A callback used inside
setTimeoutsees the state from the render that created it. Use the updater form, or read the value from the arguments, when timing matters.
Exercise
A parent holds const [items, setItems] = useState(['milk']). It renders <AddForm onAdd={handleAdd} />. Write handleAdd so the child can call onAdd('eggs') and the list becomes ['milk', 'eggs']. Then explain why onClick={handleAdd('eggs')} inside the child would break the app.
Show answer
function handleAdd(item) { setItems(prev => [...prev, item]); }. It builds a new array and does not mutate the old one. onClick={handleAdd('eggs')} calls the function during render. It calls setItems, which triggers another render, which calls it again, so React reports too many re-renders. The child should write onClick={() => onAdd('eggs')} so the call happens only on click.
Exercise
A child receives onChange={setText} from the parent. The parent now needs to trim whitespace from every value before saving it. What should the parent change, and why does the child not need to change?
Show answer
The parent replaces setText with a handler such as function handleChange(value) { setText(value.trim()); } and passes onChange={handleChange}. The child still calls onChange(e.target.value) with a string, so its code is unchanged. The rule lives in the parent, which owns the state.