1. Concept library
  2. Web Dev with React
  3. Module 8: Context and reducers

Concept

useContext

Context makes a value available to every component below a provider without passing it through each level. It suits things many components need: the current user, theme, locale.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what context provides and what it is for
  2. Create a provider and read its value with useContext
  3. Spot the object literal provider value that re-renders every consumer

In practice

A few lines that show useContext doing its job.

TSX
const ThemeContext = createContext<"light" | "dark">("light");

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

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

The common mistake

Watch for

Passing a new object literal as the provider value on every render, value={{ user, theme }}. Every consumer re-renders each time; memoise the value with useMemo.

What to know first

Your roadmap puts these before useContext, unless you already know them.

How it stays learned

Once a session shows you understand useContext, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on useContext.

Next in the moduleuseReducer →