Sub topic 11
Step 5: Add inverse data flow with callback props
This chapter assumes you know how to write function components, pass props, and call useState. It also assumes you have finished Step 4, where filterText and inStockOnly were placed in FilterableProductTable, the closest common parent of SearchBar and ProductTable.
The problem: state flows down, but changes start low
Data moves from parent to child through props. State now lives in FilterableProductTable, and SearchBar shows it. The user types in an input that belongs to SearchBar, so the change starts in a child, and the state that must change lives in the parent.
A child cannot set a parent's state directly. The parent has to hand the child a function that does it. This is called inverse data flow. Data still travels down as props, and requests to change it travel up through callbacks.
The parent passes setters as callback props
The parent already has the setter functions from useState. It passes them to SearchBar under names that describe the event.
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>
);
}onFilterTextChange and onInStockOnlyChange are ordinary props whose values are functions. The on prefix is a common convention for props that report an event. setFilterText and setInStockOnly are the real state setters, so calling them updates state in the parent.
The child calls the callback
SearchBar does not own any state. It reads the current values from props, and when the user edits an input, it calls the matching callback with the new value.
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>
);
}For the text box, the value is e.target.value. For the checkbox, it is e.target.checked. Mixing these up is a common error: a checkbox's value is a fixed string, not its on/off state.
What happens on each keystroke
- The user types a character into the text input.
- React calls the
onChangehandler with the event object. - The handler calls
onFilterTextChange(e.target.value), which issetFilterTextin the parent. - React re-renders
FilterableProductTablewith the newfilterText. - The new value flows down again to both
SearchBarandProductTable. ProductTablefilters its rows during render, and the input displays the new text.
The input shows the typed text only after the parent's state has changed and the new value has come back as a prop. That is why this kind of input is called a controlled component.
Common errors
- Calling the callback during render. Writing
onChange={onFilterTextChange(e.target.value)}runs the function immediately and passes its result to React. Wrap it in an arrow function, as above. - Passing
valuewithoutonChange. React then treats the input as read-only. Typing does nothing, and React logs a warning. - Copying props into local state in
SearchBar. A second copy offilterTextcan fall out of sync with the parent. Keep one source of truth. - Reading the wrong event property. Use
e.target.checkedfor checkboxes.
Check your understanding
Exercise
In the code above, SearchBar has no useState call, yet typing in its text input changes what ProductTable shows. Describe the path the new text takes, from the keystroke to the filtered rows.
Show answer
The onChange handler calls onFilterTextChange(e.target.value). That prop is setFilterText from FilterableProductTable, so the parent's filterText state updates. The parent re-renders and passes the new filterText down as a prop to both SearchBar, which shows it in the input, and ProductTable, which skips rows whose names do not include the text.
Exercise
A teammate writes <input type="text" value={filterText} /> in SearchBar and leaves out onChange. What happens when you type, and how do you fix it?
Show answer
The input appears frozen. Its value is fixed by the filterText prop, and nothing updates that state, so React also warns about a value without onChange. Add onChange={(e) => onFilterTextChange(e.target.value)} so typing calls the parent's setter.