React's Context API & useReducer — Advanced State ManagementEntry 3 of 7
Consuming Context
Reading the nearest provider's value from inside a component.
Notes
useContext(CartContext)returns the value of the closest provider above the component.- React 19 adds
use(CartContext), which does the same but may be called conditionally (it's the one exception to the Rules of Hooks). <CartContext.Consumer>is an older alternative: it wraps JSX and takes a function that receives the context value. It's rarely used now; prefer the hook.- Re-renders: when the provider's value changes, every component consuming that context re-executes.
What / Why / When
- What
Reading shared data inside a component.
- Why
The component gets the data directly, with no intermediate props.
- When
Any component inside the provider needs the shared value or its functions.
- Use case
Cartreads the items and computes the total.
Code compare
import { useContext } from "react";import { CartContext } from "../store/cart-context";export function Cart() { const cartCtx = useContext(CartContext); // React 19 alternative: const cartCtx = use(CartContext); const totalPrice = cartCtx.items.reduce((sum, item) => sum + item.price * item.quantity, 0); return <p>Total: ${totalPrice.toFixed(2)}</p>;}// Legacy: the Consumer component<CartContext.Consumer> {(cartCtx) => <p>{cartCtx.items.length} items in cart</p>}</CartContext.Consumer>import { Component, inject } from "@angular/core";import { CurrencyPipe } from "@angular/common";import { CartService } from "./cart.service";@Component({ selector: "app-cart", imports: [CurrencyPipe], template: `<p>Total: {{ cart.totalPrice() | currency }}</p>`,})export class CartComponent { protected cart = inject(CartService);}Differences and gotchas
- React re-executes every consumer when the context value changes, even if the consumer uses only part of it. Split unrelated data into separate contexts to limit re-renders. Angular updates only bindings that read the changed signal.
- Derived values (like the total price) are computed in each consumer in React, or in the provider. In Angular, put them in the service as
computed()so every consumer shares one calculation.
Quick reference
| React | Angular |
|---|---|
useContext(Ctx) / use(Ctx) | inject(Service) |
<Ctx.Consumer>{(v) => ...}</Ctx.Consumer> | — |
| Derived value in consumer | computed() in the service |