React · Lesson 35 of 120
Where State Lives
The closest common parent.
Once you know your state, put it in the closest component that's above everything that uses it. Not higher, and not lower.
- Who uses it?
- Closest parent above them
- Not higher
One checkbox, three users
The in stock state is used by the filter, the list, and the summary. So it lives in App, their closest common parent. App works out the shown products, and passes them down. We tick in stock only. Run it.
App.jsxjsx
import { useState } from "react";
const PRODUCTS = [{ name: "Trail 500", stock: 12 }, { name: "City 200", stock: 0 }, { name: "Volt 7", stock: 4 }];
function Filter({ on, setOn }) {
return <label><input id="s" type="checkbox" checked={on} onChange={e => setOn(e.target.checked)} /> In stock only</label>;
}
function List({ items }) {
return <ul>{items.map(p => <li key={p.name}>{p.name} ({p.stock} left)</li>)}</ul>;
}
export default function App() {
const [inStock, setInStock] = useState(false);
const shown = inStock ? PRODUCTS.filter(p => p.stock > 0) : PRODUCTS;
return (
<div>
<Filter on={inStock} setOn={setInStock} />
<List items={shown} />
<p className="box">Showing {shown.length} of {PRODUCTS.length}</p>
</div>
);
}Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#s"}]Summary
Put state in the closest common parent of everything that uses it. Next, derived values.
Key takeaways- Who uses it
- Closest parent
- Pass it down
Next up: Derived Values — compute, don't store