Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 9.2 — Context: Passing Data Deeply
React · Example 1 of 3

Headings that know their level (read, then provide level + 1)

No heading receives a level prop. Each Section reads the level from the nearest Section above it and provides one more. Move a Heading into a deeper Section and it becomes smaller by itself.

Context lets a component make a value available to everything below it without passing props: create it with createContext(defaultValue), provide it with <MyContext value={...}> (React 19) or <MyContext.Provider value={...}> (older code), and read it with useContext(MyContext), which returns the value from the nearest provider above.

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

Create a UserContext, provide { name: "Asha" } from App, and show Hi, Asha in a Navbar two levels down without passing props.

02

Make a SizeContext with default "medium". Render three <Box> components: one outside any provider, one inside <SizeContext value="small">, and one inside a nested <SizeContext value="large">. Each box shows its size.

Explain it without notes

01

What are the three steps to use context? Show the code.

02

What's the difference between <ThemeContext value> and <ThemeContext.Provider value>?

03

When does useContext return the default value passed to createContext?

04

How do nested providers work? Give a real use for overriding a context.

Headings that know their level (read, then provide level + 1)

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

h1: React course
h2: Phase 9
h3: Topic 9.2: Context
h3: Topic 9.3: Pitfalls