Boss lesson · Unit 02
Where state lives
A filterable list end to end: lift state to the common parent, keep one source of truth, derive the rest.
What you practise
- Lifting state to the common parent, one source of truth, deriving instead of storing
- A filterable list
Try a question from this lesson
Pick one
Typing in Search must narrow what List shows, and props only flow down. Which component should own the query?
Shop
├─ Search the text box
└─ List shows the matching itemsCorrect answer
Shop: the closest parent of both
Why
A sibling cannot pass props sideways. Put the state in the closest common parent and it can flow down to both: Search shows it, List filters by it. Two copies would need syncing, and would drift apart.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Lifting state up
When two components must agree on a value, move the state to their closest common parent. The parent passes the value down to whoever shows it, and passes a function down to whoever changes it. Each piece of state has one owner, a single source of truth. Everyone else receives it as props.
Concept
Derive, do not store
Rendering runs your function from top to bottom after every state change, so a plain const computed from state is always fresh. It cannot go out of sync, because it is never stored. Keep in state only the minimum that cannot be computed: here, the query.
const [q, setQ] = useState('');
// not state: recomputed on every render
const shown = items.filter(s =>
s.includes(q),
);
const n = shown.length;10 more exercises in the app
- 4× multiple choice
- 1× fill the blanks
- 2× type the answer
- 2× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.