React's Context API & useReducer — Advanced State ManagementEntry 2 of 7
Creating and Providing Context
createContext() creates a context object; rendering it as a provider makes a value available to every component below it.
react.devcreateContext
Notes
createContext(defaultValue)creates the context. The default value is used only when a component reads the context without a matching provider above it. It also documents the value's shape.- Wrap a group of components in the provider and pass the shared data through its
valueprop. - In React 19, the context itself is the provider:
<CartContext value={...}>. The older<CartContext.Provider value={...}>still works and is common in courses and existing code.
What / Why / When
- What
A shared value scoped to a subtree.
- Why
Any component inside the provider can read the value without props.
- When
App-wide or section-wide data: cart, auth, theme, feature flags.
- Use case
Wrap the shop app in a cart provider so
ProductandCartshare the same cart.
Code compare
// store/cart-context.tsximport { createContext } from "react";export type CartItem = { id: string; name: string; price: number; quantity: number };export type CartContextValue = { items: CartItem[]; addItem: (product: Omit<CartItem, "quantity">) => void; updateItemQuantity: (id: string, amount: number) => void;};// The default value applies only when no provider is foundexport const CartContext = createContext<CartContextValue>({ items: [], addItem: () => {}, updateItemQuantity: () => {},});A service plays the role of the context. Where you provide it sets its scope, just like where you place a provider in React:
import { Injectable } from "@angular/core";// App-wide: one shared instance (like a provider around <App />)@Injectable({ providedIn: "root" })export class CartService {}Differences and gotchas
- Missing provider: React silently falls back to the default value. Angular throws
NullInjectorError(unless injected with{ optional: true }), which surfaces the bug immediately. - React context is tied to the component tree. Angular's hierarchical injector follows the same tree when you use component-level
providers.
Quick reference
| React | Angular |
|---|---|
createContext(default) | @Injectable() class |
<Ctx value={v}> around the app | providedIn: 'root' |
<Ctx value={v}> around a subtree | providers: [Service] on a component |