liveBook · Manning

createContext

As explained in React Hooks in Action: With Suspense and Concurrent Mode

createContext is a React API function that creates a context object for sharing a value with descendant components.

createContext creates a context object for sharing a value with descendant components. Keep the context in its own file so the provider and consumers can import the same object. section 8.1.4

Sharing the current user

A bookings app can create UserContext, then place user state in its Provider. Components such as BookingDetails read that value with useContext instead of receiving the user through every intermediate component. The provider can wrap the whole application or only the routes that need the value. section 8.1.4

Listing 8.3 Creating and exporting a context object for our user value
import {createContext} from "react";

const UserContext = createContext();

export default UserContext;

The minimal creation step imports createContext, creates UserContext, and exports it for providers and consumers. section 8.1.4

How React Hooks in Action: With Suspense and Concurrent Mode covers it

How deep it goes
Defines context creation and Provider placement, while deferring deeper implementation internals.
Examples
Uses UserContext, App, UserPicker, BookingDetails, and a current-user edit-button scenario.
What it assumes
Assumes React components and hooks, while demonstrating the relationship between useState, Provider, and useContext.
What you can do after
Build shared React state by creating a context, providing its value, and reading it in descendants.
How it connects
Connects React Context API with Provider components, useContext, useState, and props.

Also explained in

Compare how 2 books explain createContext →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Hooks in Action: With Suspense and Concurrent Mode. The section links point to the parts of the book it draws on.