Typorithm · medium

Context

react-contextreactcontextproviderusecontext
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Context

0%

Patterns

Context shares a value down the tree without prop drilling. createContext sets a default; a <ThemeContext.Provider value=...> overrides it for its subtree; useContext reads the nearest provider's value; every consumer re-renders when the value changes.

Context lets a value travel from an ancestor to deeply nested descendants without threading it through every intermediate component as a prop. createContext defines the channel and supplies a default used when no provider is present above a consumer.

A <ThemeContext.Provider value={...}> wraps a subtree and supplies the current value to every consumer inside it, overriding the default. Nesting providers is allowed; a consumer always reads the nearest one above it.

useContext(ThemeContext) reads the active value inside a component. When the provider's value changes, every consumer re-renders — so keep the value stable (memoize objects) to avoid needless re-renders.

01

createContext sets the default value.

02

A Provider overrides the default for its subtree.

03

useContext reads the nearest provider's value.

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

function Toolbar() {
  const theme = useContext(ThemeContext);
  return <div className={theme}>Toolbar</div>;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Create context

createContext makes a context object and sets its default value, used when no provider is found above.

const ThemeContext = createContext("light");

2. Imports

createContext defines the context; useContext reads it inside a component.

import { createContext, useContext } from "react";

3. Read context

useContext returns the value of the nearest matching provider above, or the default.

const theme = useContext(ThemeContext);

4. Use the value

The consumed value flows straight into JSX, with no props passed down the tree.

return <div className={theme}>Toolbar</div>;

5. Consumer

Any component in the subtree can consume the context without receiving it as a prop.

function Toolbar() {

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Context: Lesson & Practice · Typorithm | ApplyDjinn