Split contexts: fewer components disturbed
UserName and Buttons no longer render on cart clicks. But CartCount still renders on More pens, although the number of lines didn't change: it reads the whole items array, and context can't select a part of it.
Every component that reads a context re-renders whenever the context value changes, even if it uses only one small part of it; splitting contexts helps, and an external store read through useSyncExternalStore with a selector fixes it properly.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Using the tiny createStore from this topic, build a counter store with +1 and +2 buttons and two components: Count shows the number, Parity shows "even" or "odd". Log renders and confirm that Parity skips its render when you click +2.
Rewrite an AppContext value { theme, setTheme, items, setItems } into two contexts so that components that only call setItems never re-render.
Explain it without notes
Why does a context change re-render components that don't use the changed part?
How would you reduce re-renders from a large app context without adding a library?
Explain the external store pattern and how selectors avoid unnecessary renders.
When is context still the right tool?
Preview
Console
Nothing logged yet.Expected console output
render UserName
render CartCount
render CartTotal
render Buttons
click Add pen
render CartCount
render CartTotal
click More pens
render CartCount
render CartTotal
renders for 2 clicks: 4