Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.3 — Context Patterns and Pitfalls
React · Example 1 of 4

Three everyday contexts: theme, current user and locale

Each value comes straight from state, so it keeps the same identity until it really changes: no memoising needed. The script switches the locale once; Intl.NumberFormat groups Indian numbers in lakhs and crores.

Context fits values many distant components read and that change rarely, such as the theme, the signed-in user and the locale; every reader re-renders whenever the value changes, so keep the value stable with useMemo/useCallback, split values that change at different rates into separate contexts, and don't use context for fast-changing or server data.

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

This provider re-renders every reader whenever App renders: <CartContext value={{ items, add: (i) => setItems([...items, i]) }}>. Fix it with useCallback and useMemo.

02

Split an AuthContext that holds { user, login, logout } into a state context and an actions context, and write a LogoutButton that doesn't re-render when the user changes.

Explain it without notes

01

Which values are good candidates for context, and which aren't? Give examples of each.

02

Why does <Ctx value={{ user, logout }}> cause extra re-renders, and how do you fix it?

03

What does splitting a context mean and when is it worth it?

04

Does memo stop a component from re-rendering when a context it reads changes? Explain.

05

Why do state libraries with selectors render fewer components than context for the same state?

Three everyday contexts: theme, current user and locale

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

en-IN ₹12,34,567.00
en-US $1,234,567.00