Sub topic 7
Sending Events Upward with Callback Props
This chapter assumes you can write function components, pass props, and use useState for simple values. It also assumes you know basic JavaScript closures and arrow functions. Earlier chapters covered how data flows down from parent to child. This chapter covers the reverse: how a child tells its parent that something happened.
The problem: data flows down, events flow up
Props travel in one direction, from parent to child. A child cannot reach into its parent and change a variable. It also cannot change its own props, as the previous chapter explained.
Real interfaces need the opposite direction too. A button inside a child component is clicked, and the parent's counter must change. The standard solution is a callback prop: the parent passes a function as a prop, and the child calls it when something happens.
The child does not know what the function does. It only knows when to call it. The parent keeps ownership of the data and decides how it changes.
A minimal example
import { useState } from 'react';
function LikeButton({ onLike }) {
return <button onClick={onLike}>Like</button>;
}
export default function Post() {
const [likes, setLikes] = useState(0);
return (
<div>
<p>{likes} likes</p>
<LikeButton onLike={() => setLikes(likes + 1)} />
</div>
);
}Post owns the likes state. It passes LikeButton an arrow function named onLike. When the user clicks, React calls the onClick handler, which is the same function as onLike. That function runs inside Post's scope, so it can call setLikes. React then re-renders Post with the new value.
LikeButton has no state and no knowledge of what a "like" is. You could reuse it to bookmark a page or to upvote a comment.
Naming conventions
React code follows a common naming pattern:
- Name the prop
onSomething, such asonLike,onSelect, oronSubmit. The prefix says "this is called when something happens." - Name the function in the parent
handleSomething, such ashandleLike.
export default function Post() {
const [likes, setLikes] = useState(0);
function handleLike() {
setLikes(likes + 1);
}
return <LikeButton onLike={handleLike} />;
}The convention is not enforced by React. It makes the direction of data clear: on... names are events a child announces, and handle... names are what a parent does about them. Built-in elements use the same style: onClick, onChange, onSubmit.
Passing and calling: the most common mistake
There is a difference between passing a function and calling it.
// Correct: passes the function. React calls it on click.
<LikeButton onLike={handleLike} />
// Bug: calls handleLike during render and passes its return value (undefined).
<LikeButton onLike={handleLike()} />With the second form, handleLike runs every time Post renders. It calls setLikes, which schedules another render, which calls handleLike again. React stops this loop with a "Too many re-renders" error.
When the handler needs an argument, wrap the call in an arrow function so you pass a function instead of a result:
<LikeButton onLike={() => handleLike(post.id)} />Sending data up as arguments
A callback can receive values from the child. The child decides what information to report, and the parent decides what to do with it.
import { useState } from 'react';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
function handleSubmit(event) {
event.preventDefault();
onSearch(text.trim());
}
return (
<form onSubmit={handleSubmit}>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button type="submit">Search</button>
</form>
);
}
export default function App() {
const [query, setQuery] = useState('');
return (
<div>
<SearchBox onSearch={setQuery} />
<p>Searching for: {query || 'nothing yet'}</p>
</div>
);
}Two details matter here:
SearchBoxkeeps its owntextstate, since the parent does not need to know about every keystroke. Only the final query goes up.onSearch={setQuery}passes the state setter directly.SearchBoxcallsonSearch("react"), which is the same assetQuery("react"). This works whenever the callback's arguments match what you want to do.
Report a clean value rather than a raw browser event when you can. onSearch(text) is easier to use and test than onSearch(event), and it hides how the child collected the value.
Callbacks in lists
Lists are where callbacks usually need an identifier. The child either receives the id as a prop and includes it in the call, or the parent wraps the call.
import { useState } from 'react';
function TodoItem({ todo, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.text}
</label>
</li>
);
}
export default function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Write chapter', done: false },
{ id: 2, text: 'Run examples', done: false },
]);
function handleToggle(id) {
setTodos(todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t)));
}
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} onToggle={handleToggle} />
))}
</ul>
);
}handleToggle builds a new array with map and a new object for the changed item. It never modifies todo in place. The todo prop is read-only, and state updates must produce new values, or React may not notice the change.
Updating state from a callback: use the updater form
A callback captures the values from the render in which it was created. If you call a setter several times in one handler, each call sees the same old value:
function handleTripleLike() {
setLikes(likes + 1);
setLikes(likes + 1);
setLikes(likes + 1); // likes only goes up by 1
}When the new state depends on the previous state, pass an updater function:
function handleLike() {
setLikes((current) => current + 1);
}React queues updater functions and applies them in order, so three calls add three. Use this form for counters, toggles, and appends, especially when a child may call the callback more than once before the next render.
Optional callbacks
Not every parent cares about every event. Make a callback optional by guarding the call or by giving it a default:
function Dialog({ title, onClose }) {
return (
<div role="dialog">
<h2>{title}</h2>
<button onClick={() => onClose?.()}>Close</button>
</div>
);
}The optional call onClose?.() does nothing when the prop is missing. A default of onClose = () => {} also works. Either way, calling undefined() throws a TypeError and breaks the component, so decide on one approach per component.
Typing callback props
In TypeScript, write the function's full signature in the props type. This lets the compiler check both the parent's handler and the child's call.
type SearchBoxProps = {
onSearch: (query: string) => void;
onClear?: () => void;
};
function SearchBox({ onSearch, onClear }: SearchBoxProps) {
return (
<div>
<button onClick={() => onSearch('react')}>Search</button>
<button onClick={() => onClear?.()}>Clear</button>
</div>
);
}If a parent passes (id: number) => void to onSearch, the compiler reports the mismatch. Passing onSearch(42) inside the child is also an error. A callback type is a contract that both sides must follow.
Design guidance
- Lift state to the nearest shared parent. If two siblings must stay in sync, move the state into their parent. Each sibling gets the value as a prop and a callback to request changes.
- Keep callbacks narrow.
onToggle(id)describes an event. A child that receivessetTodoshas the power to replace the entire list, and parent and child become tightly coupled. - Describe events, not implementation. Prefer
onSelect(item)tosetSelectedItem. The parent can then change how it stores the selection without touching the child. - Do not store a callback result in props to read later. A callback returns control to the child immediately. If you need a value back, send it through state or a new prop on the next render.
- Watch re-renders. An inline arrow like
() => setLikes(likes + 1)is a new function on every render. This is harmless in most code. It matters only when the child is wrapped inmemo, because the new function breaks the shallow prop comparison. A later chapter covers that case.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| "Too many re-renders" error | Called the handler in JSX: `onClick={handle()}` | Pass the function: `onClick={handle}` |
| Counter increases by 1 after several calls | Reused a stale value in one handler | Use `setX((prev) => ...)` |
| `TypeError: onX is not a function` | Parent did not pass the prop | Pass it, or guard with `onX?.()` |
| UI does not update after a child's event | Parent mutated state in place | Create new arrays and objects |
| Handler receives an event instead of a value | Passed the callback directly to a DOM event | Wrap it: `onChange={(e) => onChange(e.target.value)}` |
Exercise
A ColorPicker child renders three buttons and should tell its parent which color was clicked. The parent stores the chosen color in state. Write the onPick callback call in the child for a button with the color "red", and name what the parent must pass for onPick if it should store the value directly.
Show answer
In the child, the button uses onClick={() => onPick('red')}. The arrow function delays the call until the click and passes the color as an argument. The parent can pass its state setter directly, for example <ColorPicker onPick={setColor} />, because setColor('red') stores the value. Writing onClick={onPick('red')} would be a bug, since it calls the function during render.
Exercise
A handler runs setCount(count + 1) twice in a row, but the count only rises by 1 per click. Why does this happen, and how do you fix it?
Show answer
Both calls read the same count value, which was captured when the component rendered, so both queue the same next value. Use the updater form, setCount((c) => c + 1), twice. React applies each updater to the latest queued state, so the count rises by 2.