Sub topic 7
Sending events upward with callback props
Props flow down from parent to child. Callback props let a child tell its parent that something happened. This chapter assumes you know function components, basic props, destructuring, and useState.
The working model
A callback prop is a function that the parent defines and passes to the child as a prop. The child calls it when an event occurs, such as a click. The function runs in the parent's scope, so it can update the parent's state.
The child never touches the parent's data. It only asks for a change. The parent decides what to do.
A first example
The parent owns likes. The child receives onLike and attaches it to a button.
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>
);
}Each click calls onLike, which calls setLikes. React re-renders Post with the new count.
Sending data back to the parent
The child can pass arguments to the callback. This is how a child reports a value, such as what the user typed.
import { useState } from 'react';
function SearchBox({ onSearch }) {
const [text, setText] = useState('');
function handleSubmit(event) {
event.preventDefault();
onSearch(text);
}
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}</p>
</div>
);
}Naming conventions
- Name the prop
onSomething, such asonLike,onSearch, oronDelete. The prop describes the event from the child's point of view. - Name the parent's handler
handleSomething, such ashandleLike. It describes what the parent does in response.
<LikeButton onLike={handleLike} />Common errors
Calling the function instead of passing it
This is the most frequent mistake. Parentheses call the function during render.
// Wrong: runs during render, then passes its result (undefined)
<button onClick={handleLike()}>Like</button>
// Right: passes the function itself
<button onClick={handleLike}>Like</button>
// Right: wraps a call that needs an argument
<button onClick={() => handleDelete(id)}>Delete</button>Calling setLikes during render also triggers another render, which causes an infinite loop and a "Too many re-renders" error.
Forgetting to pass the callback
If the parent omits onLike, then onLike is undefined, and clicking throws a TypeError. Make it optional with a guard when that is a valid use.
function LikeButton({ onLike }) {
return <button onClick={() => onLike?.()}>Like</button>;
}Updating from stale state
setLikes(likes + 1) uses the likes value from the current render. If you call it twice in one handler, both calls see the same value. Use the updater form when the new value depends on the old one.
<LikeButton onLike={() => setLikes((n) => n + 1)} />Letting the child own the data
If the child keeps its own copy of the count, the parent cannot read it. Keep the data in the parent, and let the child report events.
Summary of the pattern
| Role | Responsibility |
|---|---|
| Parent | Owns state, defines the callback, passes it as a prop |
| Child | Calls the callback with any needed arguments |
| React | Re-renders the parent, then the child, with new props |
Exercise
A parent renders <DeleteButton onDelete={handleDelete(item.id)} />. The item is deleted as soon as the page loads, and clicking does nothing. What is wrong, and how do you fix it?
Show answer
handleDelete(item.id) is called during render, and its return value (probably undefined) is passed as onDelete. Pass a function instead: onDelete={() => handleDelete(item.id)}. The arrow function runs only when the child calls onDelete.
Exercise
Write a Counter child component that shows a "+1" button and takes an onIncrement prop. In the parent, store the count in state and show it. Which component owns the count?
Show answer
The parent owns the count. Example: function Counter({ onIncrement }) { return <button onClick={onIncrement}>+1</button>; } export default function App() { const [count, setCount] = useState(0); return ( <div> <p>{count}</p> <Counter onIncrement={() => setCount((n) => n + 1)} /> </div> ); }