Sub topic 2
Why data flows down from parent to child
Assume you know basic JavaScript arrays and objects, HTML elements, JSX, and function components. This chapter uses those ideas to explain how React keeps a UI predictable.
Data flows down from parent to child
A parent component owns data and passes it to a child through props. Props are read-only values that describe how a child should render. The child should not change them directly.
function ProductTable({ products, filterText }) {
const visibleProducts = products.filter((product) =>
product.name.toLowerCase().includes(filterText.toLowerCase())
);
return <ProductRows products={visibleProducts} />;
}
function ProductRows({ products }) {
return products.map((product) => (
<div key={product.name}>{product.name}</div>
));
}ProductTable passes visibleProducts down to ProductRows. The child receives the result and renders it. This one-way flow makes it easier to find where a value came from and which component controls it.
State versus props
State is data a component remembers between renders and can update after user interaction. Props come from a parent and are inputs to the component.
For this table:
- The product list can be a prop because another component supplies it.
- The search text is state because the user changes it.
- The stock-only choice is state because the user changes it.
- The visible rows are not state because they can be calculated.
Find the minimal complete state
Store only values that can change independently and cannot be calculated from other values. The parent can own the two independent controls:
import { useState } from 'react';
function FilterableProductTable({ products }) {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<ProductTable
products={products}
filterText={filterText}
inStockOnly={inStockOnly}
/>
);
}Do not store visibleProducts. It is a duplicate representation of the products and filters. Duplicated state can become stale when one value changes without the other.
Compute filtered rows during render
Filtering during render keeps the result synchronized automatically:
const visibleProducts = products.filter((product) => {
const matchesText = product.name
.toLowerCase()
.includes(filterText.toLowerCase());
return matchesText && (!inStockOnly || product.stocked);
});Each render uses the current inputs, so the table cannot display an old filtered list.
Exercise
Should visibleProducts be stored in state when it depends only on products, filterText, and inStockOnly?
Show answer
No. Calculate it during rendering from those current values.