React · Chapter 19 of 26

Context

By the end of this chapter you can give a value to every component below a point in the tree without passing it through each one: make a context with createContext and a default, provide a value with <MyContext value={...}>, read the nearest one with useContext, put state and a reducer behind it, and say which components render again when its value changes. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Effects and data
  • 4 tasks
  • React
  • In the all labs plan

The first 2 chapters of React are free. This one comes with the all labs plan.

Why you need this

Two things on Parda's pages are needed almost everywhere. The signed-in member: the header says Hi, Aditya, the booking form fills in his email, the tickets page lists his bookings. And the cart: the header shows Basket (3), the basket page lists the tickets, and a show card's Add button puts one in.

Chapter 10 taught the honest way to share: lift the state to the closest common parent and pass it down as props. For the member, that parent is App, and the booking form is five levels down: App, Layout, ShowPage, BookingPanel, ContactForm. Layout, ShowPage and BookingPanel never use the member; they take it as a prop only to hand it on. In Rukhsana's first draft, member={member} was written in every file between App and the form, and adding the member's phone to the form meant touching all of them. That is called prop drilling. It works, but it ties every component in the middle to data it does not care about, and a level that forgets to pass it on breaks the one at the bottom.

Context lets a component high up offer a value, and any component below it, however deep, read it directly. The ones in between are not involved.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    AccountMenu.jsx: the header's account menu

    AccountMenu takes no props. It reads the signed-in member from MemberContext, imported from MemberContext.js, where it is made with the default null (nobody signed in). When the context gives null, show a button Sign in. When it gives a member, like Aditya Bapat, show a paragraph Hi, Aditya (Hi, a comma and the first word of the member's name) and a link, an a element with href="#tickets", that says My tickets. Give the paragraph className="hello" for app.css.

    The Check shows AccountMenu outside any provider (it must say Sign in), inside a provider whose value is Aditya Bapat (Hi, Aditya and the link), then changes that value to null (Sign in again), and puts it inside Pranav Joshi's provider inside Aditya's: it must read the nearest one and say Hi, Pranav.

  2. Task 2

    CartContext.jsx: one cart for the whole page

    Write two exports in CartContext.jsx. First, export const CartContext, a context made with createContext, whose default (what a component reads outside any provider) is an object { cart: [], dispatch: () => {} }: an empty cart and a dispatch that does nothing.

    Second, export default function CartProvider({ children, initial = [] }): it keeps the cart with useReducer(cartReducer, initial), with cartReducer from cart.js, and shows its children inside a provider of CartContext whose value is { cart, dispatch }. Every component below CartProvider then reads the same cart and the same dispatch, and a dispatch from one of them changes what all of them show.

    The Check reads CartContext outside any provider (the default), then puts two readers inside CartProvider with initial holding 2 tickets for Ghar Wapsi Express: both must see it; one dispatches add for The Tiffin Thief and the other must see it, and a second add must make its qty 2. CartProvider with no initial must start with [].

  3. Task 3

    Basket.jsx: the basket and the header's count

    Both components read { cart, dispatch } from CartContext (from CartContext.jsx, Task 2's file) and take no props. Each cart item is { id, title, when, price, qty }.

    export function BasketCount() shows a paragraph Basket (3), the number of tickets: every item's qty added up (Basket (0) for an empty cart). Give it className="count".

    export default function Basket() shows a heading h2 Your basket. When the cart is empty, a paragraph Your basket is empty and no list. Otherwise a list, a ul (className="basket-items"), with one li per item in cart order, which shows the item's title, then its qty and price as 2 × ₹180, and a button Remove that calls dispatch({ type: 'remove', id }) with the item's id; and under the list a paragraph Total: ₹710, every item's price times its qty, added up.

    The Check gives them its own provider of CartContext with 2 tickets for Ghar Wapsi Express at ₹180 and 1 for The Tiffin Thief at ₹350 (Total: ₹710, Basket (3)), clicks The Tiffin Thief's Remove (dispatch must be called once with { type: 'remove', id: 'T0038' }), and also shows both outside any provider, with the default empty cart.

  4. Task 4 · interview question

    Interview: Layout.jsx, the header that never says hi

    Layout gets the signed-in member (or null) in its member prop and the page in children. It shows, in this order: a header with the h1 Parda, then AccountMenu, then BasketCount; a main with the children; and a footer that says Parda, Pune. Write to help@parda.example.. Every component inside Layout, the header's AccountMenu included, must read the member from MemberContext.

    The bug: Aditya is signed in, and the page knows it, but the header says Sign in. Fix it in Layout.jsx, so that the header says Hi, Aditya too, and says Sign in again when member changes to null. The Check renders Layout with its own AccountMenu and BasketCount and a child that reads the member.

    Rukhsana will ask: when a context's value changes, which components render again?

What you will learn

  • Prop drilling: a value passed through components that only hand it on.
  • createContext(default): a context object, and the value a component gets when no provider is above it.
  • Providing a value: in React 19, the context is its own provider, <TextSizeContext value="large">.
  • useContext: reads the value of the nearest provider above, or the default.
  • Context with state: a provider component holding state or a reducer, with its setter or dispatch in the value.
  • What renders again when a context's value changes, measured.
  • When not to use context: props first, and children before context.

More in Effects and data

Build "Context" yourself

Parda sells tickets for Pune's own cinemas and stages, and its booking page broke on opening night. You rebuild it in React. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of React are free. This one comes with the all labs plan.