Sub topic 11
Step 5: Add inverse data flow with callback props
This chapter assumes you can write function components, pass props, and call useState. You should also know the earlier steps of this tutorial: the component hierarchy, the static version, the minimal state (filterText and inStockOnly), and the decision that FilterableProductTable owns that state.
At the end of Step 4 the state lives in the right place, but nothing can change it. The inputs sit in SearchBar, and the state sits in its parent. This chapter connects the two.
The problem: state is above, events are below
The user types into an input inside SearchBar. The state that the input should change lives in FilterableProductTable. Props only travel down, so SearchBar cannot reach up and call setFilterText by itself.
The fix is to pass the setter down as a prop. The child calls it when something happens. The parent still owns the state, and the data change still starts in the parent's code. React docs call this pattern inverse data flow.
Step 1: Start with the parent state
The parent already holds the two pieces of state from Step 4. Here it is again, passing values and setters to both children.
import { useState } from 'react';
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFilterText}
onInStockOnlyChange={setInStockOnly}
/>
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStockOnly}
/>
</div>
);
}Two props on SearchBar are values (filterText, inStockOnly). Two are callbacks (onFilterTextChange, onInStockOnlyChange). A callback prop is a function that a parent gives to a child so the child can notify the parent.
setFilterText and setInStockOnly are passed directly. This works because each setter accepts a single new value, and that is exactly what SearchBar will call it with. You could also wrap them, for example onFilterTextChange={(text) => setFilterText(text)}, but the wrapper adds nothing here.
Step 2: Call the callbacks from the child
SearchBar receives the callbacks and calls them from its event handlers.
function SearchBar({
filterText,
inStockOnly,
onFilterTextChange,
onInStockOnlyChange
}) {
return (
<form>
<input
type="text"
value={filterText}
placeholder="Search..."
onChange={(e) => onFilterTextChange(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(e) => onInStockOnlyChange(e.target.checked)}
/>{' '}
Only show products in stock
</label>
</form>
);
}SearchBar has no state of its own. It displays what it is given and reports what the user did. This keeps it easy to test: render it with fixed props and check that a typed character calls the callback with the right value.
Step 3: Follow one keystroke
Suppose the user types a into an empty search box. This is the sequence:
- The browser fires a change event on the text input.
- React calls the
onChangehandler:onFilterTextChange(e.target.value). Heree.target.valueis"a". onFilterTextChangeissetFilterText, so React schedules a state update inFilterableProductTablewith the value"a".- React re-renders
FilterableProductTablewithfilterTextequal to"a". - The new value goes down to
SearchBar, which renders the input withvalue="a". - The new value also goes down to
ProductTable, which filters the rows during render.
Everything the user sees comes from the new state. The input does not keep its own copy of the text.
Controlled inputs
The value and checked props on the inputs are what make them controlled. A controlled input is a form element whose displayed value is set by React from props or state, not by the browser's own internal value.
In a controlled input, the value prop tells React what text to show. The onChange handler is how the user's typing gets back to your state. Without it, the input would be stuck, because React would keep resetting it to the same value.
| Element | Display prop | Value inside the event | Handler |
|---|---|---|---|
| Text input | `value` | `e.target.value` | `onChange` |
| Checkbox | `checked` | `e.target.checked` | `onChange` |
Note the difference for checkboxes. A checkbox uses checked and e.target.checked, which is a boolean. Using value on a checkbox is a common mistake and does not control whether it is ticked.
How the table reacts
ProductTable receives filterText and inStockOnly as props and computes the visible rows on each render. It does not store the filtered list.
function ProductTable({ products, filterText, inStockOnly }) {
const rows = [];
let lastCategory = null;
products.forEach((product) => {
if (!product.name.toLowerCase().includes(filterText.toLowerCase())) {
return;
}
if (inStockOnly && !product.stocked) {
return;
}
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}
/>
);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}Because the rows are derived from the props, the table can never show a list that disagrees with the search box. There is one source of truth, and both children read from it.
A detail worth noticing: the category heading is only pushed when the first matching product of a category is reached. If a search removes every product in Vegetables, the Vegetables heading disappears too, because the check for lastCategory happens after the filters.
Callback naming conventions
The names in this example follow a common convention.
- Props that receive a function are named
onSomething, such asonFilterTextChange. The name describes the event, not what the parent will do. - Handlers defined in a component are named
handleSomething, such ashandleFilterChange.
Naming the prop after the event keeps SearchBar independent of the parent. SearchBar says "the filter text changed". It does not say "set the filter text". The parent decides what that means. Later you could make the parent also save the text to the URL, and SearchBar would not need to change.
Common errors
Calling the function instead of passing it
// Wrong: runs during render and sets state in a loop
<input onChange={onFilterTextChange(e.target.value)} />
// Right: passes a function that runs on the event
<input onChange={(e) => onFilterTextChange(e.target.value)} />The first version calls the callback while rendering. e is not even defined there, so it fails. If you write onChange={onFilterTextChange()} with no argument, the call happens during render, sets state, triggers another render, and React reports too many re-renders.
Passing the event instead of the value
If you write onChange={onFilterTextChange} in SearchBar, the parent's setter receives the whole event object. The state becomes an object, and filterText.toLowerCase() throws an error. Either pass e.target.value as shown, or design the callback to receive the event and unpack it in the parent. Pick one convention and keep it consistent.
Copying props into child state
function SearchBar({ filterText }) {
// Wrong: this copy only uses the initial prop value
const [text, setText] = useState(filterText);
// ...
}useState uses its argument only on the first render. After that, changes to the filterText prop are ignored, and you have two sources of truth. Use the prop directly.
Missing the checkbox prop
Using value={inStockOnly} on a checkbox, or reading e.target.value in its handler, leaves the checkbox out of sync. Use checked and e.target.checked.
Alternatives and trade-offs
Passing callbacks works well when the state owner is one or two levels above the component that fires events. Here FilterableProductTable is the direct parent of SearchBar, so the cost is small.
Trade-offs to keep in mind:
- Prop drilling. If
SearchBarwere five levels deep, every component in between would have to forward the callbacks. At that point consider moving the controls closer to the state, or using context. - Re-rendering. Each keystroke re-renders
FilterableProductTableand its children. For six products this is negligible. For thousands of rows you would measure first, then consider memoization or virtualized lists. - Granularity of callbacks. Two callbacks per control is simple. If the form grows to many fields, one
onChangethat receives a field name and value, or a single filters object in state, can be tidier.
Putting it together
Here is a complete file you can run in a Vite or Create React App project. Replace App.jsx with it.
import { useState } from 'react';
const PRODUCTS = [
{ category: 'Fruits', price: '$1', stocked: true, name: 'Apple' },
{ category: 'Fruits', price: '$1', stocked: true, name: 'Dragonfruit' },
{ category: 'Fruits', price: '$2', stocked: false, name: 'Passionfruit' },
{ category: 'Vegetables', price: '$2', stocked: true, name: 'Spinach' },
{ category: 'Vegetables', price: '$4', stocked: false, name: 'Pumpkin' },
{ category: 'Vegetables', price: '$1', stocked: true, name: 'Peas' }
];
function ProductCategoryRow({ category }) {
return (
<tr>
<th colSpan="2">{category}</th>
</tr>
);
}
function ProductRow({ product }) {
const name = product.stocked ? (
product.name
) : (
<span style={{ color: 'red' }}>{product.name}</span>
);
return (
<tr>
<td>{name}</td>
<td>{product.price}</td>
</tr>
);
}
function ProductTable({ products, filterText, inStockOnly }) {
const rows = [];
let lastCategory = null;
products.forEach((product) => {
if (!product.name.toLowerCase().includes(filterText.toLowerCase())) {
return;
}
if (inStockOnly && !product.stocked) {
return;
}
if (product.category !== lastCategory) {
rows.push(
<ProductCategoryRow
category={product.category}
key={product.category}
/>
);
}
rows.push(<ProductRow product={product} key={product.name} />);
lastCategory = product.category;
});
return (
<table>
<thead>
<tr>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
function SearchBar({
filterText,
inStockOnly,
onFilterTextChange,
onInStockOnlyChange
}) {
return (
<form>
<input
type="text"
value={filterText}
placeholder="Search..."
onChange={(e) => onFilterTextChange(e.target.value)}
/>
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(e) => onInStockOnlyChange(e.target.checked)}
/>{' '}
Only show products in stock
</label>
</form>
);
}
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<div>
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFilterText}
onInStockOnlyChange={setInStockOnly}
/>
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStockOnly}
/>
</div>
);
}
export default function App() {
return <FilterableProductTable products={PRODUCTS} />;
}Try these checks once it runs:
- Type
ap. Only Apple and Snapple-style matches remain: here, Apple and Dragonfruit do not both match, so expect Apple only (plus nothing else containingap). Passionfruit does not containapeither. - Clear the box and tick the checkbox. Passionfruit and Pumpkin disappear.
- Type
pwith the checkbox ticked. Apple, Spinach, and Peas remain, under their category headings.
Exercise
Your teammate changes SearchBar so the text input reads onChange={onFilterTextChange}, with no arrow function. Typing then crashes the page with "filterText.toLowerCase is not a function". Explain what happens and give the fix.
Show answer
Without the arrow function, React calls onFilterTextChange (which is setFilterText) with the whole change event object. State then holds an event object, not a string. On the next render the table calls filterText.toLowerCase(), which fails because an event has no such method. The fix is onChange={(e) => onFilterTextChange(e.target.value)}, so the setter receives the string.
Exercise
SearchBar needs a "Clear" button that empties the search box. Which component should hold the new logic, which props does SearchBar need, and does this add any state?
Show answer
No new state is needed. The button's onClick handler in SearchBar calls the existing callback with an empty string: onClick={() => onFilterTextChange('')}. SearchBar already has that prop, and FilterableProductTable still owns filterText. The controlled input then shows an empty value on the next render.