Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 15.2 — When Context Isn't Enough
React · Example 2 of 3

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.

01

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.

02

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

01

Why does a context change re-render components that don't use the changed part?

02

How would you reduce re-renders from a large app context without adding a library?

03

Explain the external store pattern and how selectors avoid unnecessary renders.

04

When is context still the right tool?

Split contexts: fewer components disturbed

Preview

Press Run to see the page.

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