Skip to main content

Web frameworks · Intermediate · 25 min

Share state across React components with context and useReducer

By Padding · Updated 19 Nov 2026
Node.js 26 · React 19.3 · Vite 8.3 · Vitest 5.1

You will turn a prop-drilled shopping basket into a reducer with named actions, share it through two React contexts and a useBasket hook, prove the add buttons stop re-rendering, and test the reducer as a plain function.

On this page

Lifting state up works until the closest common parent is a long way from the components that need the state. Then every component in between takes a prop it never reads, only to hand it on. React calls this prop drilling. It is not a bug, but it makes components harder to move, and it means a change near the top re-renders everything underneath.

In this tutorial you build a small online craft stall with a basket. You write it the drilled way first and watch the browser console to see what re-renders on each click. Then you change it in four moves:

  • a reducer: one pure function that takes the basket and a named action, such as itemAdded, and returns the next basket
  • two contexts: one carries the basket, the other carries dispatch, so components that only send actions never re-render when the basket changes
  • custom hooks: useBasket and useBasketDispatch hide the contexts and fail loudly when used outside the provider
  • plain tests: the reducer is an ordinary function, so Vitest tests it without a browser

You finish with a clear sense of when context and a reducer are enough, and when a state library is worth adding.

The project uses the Vite React and TypeScript template from build a React 19 app with Vite, and builds on managing component state with useState.

Step 1 · Create the project and start Vite

Create a project in a throwaway folder and install its dependencies:

Bash
cd ~
npm create vite@9 basket-demo -- --template react-ts --no-interactive
cd basket-demo
npm install

Start the dev server. It keeps running, so open a second terminal in ~/basket-demo for the commands that follow:

Bash
npm run dev

Check it worked

The dev server prints Local: http://localhost:5173/. Open it and you see the Vite and React starter page. Open the browser's developer tools on the Console tab as well; you will use it in the next step.

Bash
curl -s http://localhost:5173/ | grep -o '<div id="root"></div>'

Step 2 · Build the basket the prop-drilled way

Start with the products and two small helpers. Prices are stored in kobo, the smallest unit of the naira, so totals are whole numbers and never pick up floating-point errors. Intl.NumberFormat turns them into a price with the right symbol and separators. The same approach works for cents, pesewas or any other currency.

Bash
mkdir -p src/components src/basket
cat > src/products.ts <<'TS'
export type Product = {
  id: string
  name: string
  priceKobo: number
}

export type BasketLine = {
  productId: string
  quantity: number
}

export const products: Product[] = [
  { id: 'tote', name: 'Ankara tote bag', priceKobo: 1_500_000 },
  { id: 'shea', name: 'Shea butter, 250 g', priceKobo: 450_000 },
  { id: 'basket', name: 'Woven market basket', priceKobo: 1_200_000 },
  { id: 'candle', name: 'Beeswax candle', priceKobo: 300_000 },
]

const naira = new Intl.NumberFormat('en-NG', { style: 'currency', currency: 'NGN' })

export function formatPrice(kobo: number): string {
  return naira.format(kobo / 100)
}

export function findProduct(id: string): Product {
  const product = products.find((p) => p.id === id)
  if (!product) throw new Error(`Unknown product: ${id}`)
  return product
}
TS
cat > src/debug.ts <<'TS'
// Logs each render while you develop. Vite sets import.meta.env.DEV to false in a build.
export function logRender(name: string): void {
  if (import.meta.env.DEV) console.log(`render ${name}`)
}
TS

Now the components. App owns the basket in useState. The header shows a count, the shop lists products with an add button on each, and a basket panel shows the lines and a total. Look at onAdd in Shop.tsx: it goes from Shop to ProductList to ProductCard to AddToBasketButton, and only the last of those four uses it.

Bash
cat > src/components/Header.tsx <<'TSX'
import { logRender } from '../debug'

function BasketBadge({ itemCount }: { itemCount: number }) {
  logRender('BasketBadge')
  return (
    <p className="badge" role="status">
      Basket: {itemCount} {itemCount === 1 ? 'item' : 'items'}
    </p>
  )
}

export function Header({ itemCount }: { itemCount: number }) {
  logRender('Header')
  return (
    <header className="header">
      <h1>Corner craft stall</h1>
      <BasketBadge itemCount={itemCount} />
    </header>
  )
}
TSX
cat > src/components/Shop.tsx <<'TSX'
import { products, formatPrice, type Product } from '../products'
import { logRender } from '../debug'

type AddProps = { onAdd: (productId: string) => void }

function AddToBasketButton({ product, onAdd }: AddProps & { product: Product }) {
  logRender('AddToBasketButton')
  return (
    <button type="button" onClick={() => onAdd(product.id)}>
      Add to basket<span className="visually-hidden">: {product.name}</span>
    </button>
  )
}

function ProductCard({ product, onAdd }: AddProps & { product: Product }) {
  logRender('ProductCard')
  return (
    <li className="card">
      <span className="name">{product.name}</span>
      <span className="price">{formatPrice(product.priceKobo)}</span>
      <AddToBasketButton product={product} onAdd={onAdd} />
    </li>
  )
}

function ProductList({ onAdd }: AddProps) {
  logRender('ProductList')
  return (
    <ul className="products">
      {products.map((product) => (
        <ProductCard key={product.id} product={product} onAdd={onAdd} />
      ))}
    </ul>
  )
}

export function Shop({ onAdd }: AddProps) {
  logRender('Shop')
  return (
    <section aria-labelledby="shop-heading">
      <h2 id="shop-heading">Products</h2>
      <ProductList onAdd={onAdd} />
    </section>
  )
}
TSX
cat > src/components/BasketPanel.tsx <<'TSX'
import { findProduct, formatPrice, type BasketLine } from '../products'
import { logRender } from '../debug'

type Props = {
  lines: BasketLine[]
  onAdd: (productId: string) => void
  onRemoveOne: (productId: string) => void
  onEmpty: () => void
}

export function BasketPanel({ lines, onAdd, onRemoveOne, onEmpty }: Props) {
  logRender('BasketPanel')
  const total = lines.reduce(
    (sum, line) => sum + findProduct(line.productId).priceKobo * line.quantity,
    0,
  )
  return (
    <section aria-labelledby="basket-heading" className="basket">
      <h2 id="basket-heading">Basket</h2>
      {lines.length === 0 ? (
        <p>Your basket is empty.</p>
      ) : (
        <>
          <ul className="lines">
            {lines.map((line) => {
              const product = findProduct(line.productId)
              return (
                <li key={line.productId}>
                  <span className="name">{product.name}</span>
                  <button type="button" aria-label={`Remove one ${product.name}`} onClick={() => onRemoveOne(line.productId)}>
                    −
                  </button>
                  <span className="qty">{line.quantity}</span>
                  <button type="button" aria-label={`Add one more ${product.name}`} onClick={() => onAdd(line.productId)}>
                    +
                  </button>
                </li>
              )
            })}
          </ul>
          <p className="total">
            Total: <strong>{formatPrice(total)}</strong>
          </p>
          <button type="button" onClick={onEmpty}>
            Empty basket
          </button>
        </>
      )}
    </section>
  )
}
TSX
cat > src/App.tsx <<'TSX'
import { useState } from 'react'
import type { BasketLine } from './products'
import { Header } from './components/Header'
import { Shop } from './components/Shop'
import { BasketPanel } from './components/BasketPanel'
import './App.css'

export default function App() {
  const [lines, setLines] = useState<BasketLine[]>([])

  function addItem(productId: string) {
    setLines((previous) => {
      const existing = previous.find((line) => line.productId === productId)
      if (!existing) return [...previous, { productId, quantity: 1 }]
      return previous.map((line) =>
        line.productId === productId ? { ...line, quantity: line.quantity + 1 } : line,
      )
    })
  }

  function removeOne(productId: string) {
    setLines((previous) =>
      previous
        .map((line) =>
          line.productId === productId ? { ...line, quantity: line.quantity - 1 } : line,
        )
        .filter((line) => line.quantity > 0),
    )
  }

  const itemCount = lines.reduce((sum, line) => sum + line.quantity, 0)

  return (
    <div className="stall">
      <Header itemCount={itemCount} />
      <main className="layout">
        <Shop onAdd={addItem} />
        <BasketPanel lines={lines} onAdd={addItem} onRemoveOne={removeOne} onEmpty={() => setLines([])} />
      </main>
    </div>
  )
}
TSX
cat > src/App.css <<'CSS'
.stall {
  max-width: 56rem;
  margin: 0 auto;
  padding: 1rem;
  text-align: left;
}

.header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 0.5rem;
}

.layout {
  display: grid;
  gap: 2rem;
}

@media (min-width: 48rem) {
  .layout {
    grid-template-columns: 3fr 2fr;
  }
}

.products,
.lines {
  list-style: none;
  padding: 0;
}

.card,
.lines li {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 0.5rem 0.75rem;
  padding: 0.5rem 0;
  border-bottom: 1px solid #d9dce1;
}

.card .name,
.lines .name {
  flex: 1;
  font-weight: 600;
}

.qty {
  min-width: 2ch;
  text-align: center;
}

.visually-hidden {
  position: absolute;
  width: 1px;
  height: 1px;
  margin: -1px;
  padding: 0;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
  border: 0;
}
CSS

Each add button shows "Add to basket" and carries the product name in a visually-hidden span, so a screen reader announces something like "Add to basket: Ankara tote bag". The accessible name starts with the visible words, which lets a speech-input user say "click Add to basket" and still reach the button (WCAG 2.2 success criterion 2.5.3, Label in Name). An aria-label such as "Add Ankara tote bag to basket" would replace the visible text and break that match. The − and + buttons in the basket show only a symbol, so their aria-label supplies the whole name.

Check it worked

Run the type checker. It prints nothing when the code compiles:

Bash
npx tsc -b

The page shows four products with prices such as ₦15,000.00, a badge reading "Basket: 0 items" and an empty basket. Clear the console, then select "Add to basket" on the tote bag. The badge changes to "Basket: 1 item", and the console fills with lines such as render Shop, render ProductList, four render ProductCard and four render AddToBasketButton. Every product re-rendered, although no product changed. Each line may appear twice, because the template wraps the app in StrictMode, which renders every component twice in development to expose impure code.

Step 3 · Move the basket logic into a reducer

The rules for changing the basket are spread across App: one function adds, another removes, and the empty button has its own inline update. A reducer collects all of them in one place. It is a function with the shape (state, action) => nextState. The component no longer says how the basket changes, only what happened, by dispatching an action such as { type: 'itemAdded', productId: 'tote' }.

Name actions after the event, not the code it triggers: itemAdded reads well in a log, and the reducer decides what an added item means.

Bash
cat > src/basket/reducer.ts <<'TS'
import { findProduct, type BasketLine } from '../products'

export type BasketState = {
  lines: BasketLine[]
}

export type BasketAction =
  | { type: 'itemAdded'; productId: string }
  | { type: 'itemDecreased'; productId: string }
  | { type: 'itemRemoved'; productId: string }
  | { type: 'basketCleared' }

export const initialBasket: BasketState = { lines: [] }

function hasLine(state: BasketState, productId: string): boolean {
  return state.lines.some((line) => line.productId === productId)
}

export function basketReducer(state: BasketState, action: BasketAction): BasketState {
  switch (action.type) {
    case 'itemAdded': {
      if (!hasLine(state, action.productId)) {
        return { lines: [...state.lines, { productId: action.productId, quantity: 1 }] }
      }
      return {
        lines: state.lines.map((line) =>
          line.productId === action.productId ? { ...line, quantity: line.quantity + 1 } : line,
        ),
      }
    }
    case 'itemDecreased': {
      if (!hasLine(state, action.productId)) return state
      return {
        lines: state.lines
          .map((line) =>
            line.productId === action.productId ? { ...line, quantity: line.quantity - 1 } : line,
          )
          .filter((line) => line.quantity > 0),
      }
    }
    case 'itemRemoved': {
      if (!hasLine(state, action.productId)) return state
      return { lines: state.lines.filter((line) => line.productId !== action.productId) }
    }
    case 'basketCleared':
      return initialBasket
    default: {
      const unhandled: never = action
      throw new Error(`Unknown basket action: ${JSON.stringify(unhandled)}`)
    }
  }
}

export function countItems(state: BasketState): number {
  return state.lines.reduce((sum, line) => sum + line.quantity, 0)
}

export function basketTotal(state: BasketState): number {
  return state.lines.reduce(
    (sum, line) => sum + findProduct(line.productId).priceKobo * line.quantity,
    0,
  )
}
TS
cat > src/App.tsx <<'TSX'
import { useReducer } from 'react'
import { basketReducer, countItems, initialBasket } from './basket/reducer'
import { Header } from './components/Header'
import { Shop } from './components/Shop'
import { BasketPanel } from './components/BasketPanel'
import './App.css'

export default function App() {
  const [basket, dispatch] = useReducer(basketReducer, initialBasket)

  const addItem = (productId: string) => dispatch({ type: 'itemAdded', productId })
  const removeOne = (productId: string) => dispatch({ type: 'itemDecreased', productId })

  return (
    <div className="stall">
      <Header itemCount={countItems(basket)} />
      <main className="layout">
        <Shop onAdd={addItem} />
        <BasketPanel
          lines={basket.lines}
          onAdd={addItem}
          onRemoveOne={removeOne}
          onEmpty={() => dispatch({ type: 'basketCleared' })}
        />
      </main>
    </div>
  )
}
TSX

A few details matter here:

  • The reducer must be pure. It never changes state in place, never reads the clock or the network, and returns the same result for the same input. React may call it more than once, and Strict Mode does so on purpose in development.
  • When nothing changes, such as decreasing a product that is not in the basket, the reducer returns the same state object. React compares the old and new state with Object.is and skips the re-render when they are identical.
  • The never line in default makes TypeScript fail the build if you add an action type to BasketAction and forget to handle it.
  • itemRemoved is not used by any button yet. It is there because "remove this line" is a real basket event, and you test it in a later step.

Check it worked

Bash
npx tsc -b

The page behaves exactly as before: add, +, − and "Empty basket" all work, and the console still shows every product re-rendering on each click. The logic has moved, but the props are still drilled. To see the safety net, add | { type: 'couponApplied'; code: string } to BasketAction and run npx tsc -b again: TypeScript reports that the type is not assignable to never. Remove the line afterwards.

Step 4 · Create two contexts and a provider

Context lets a component read a value from any parent that provides it, without the components in between passing it on. You create two contexts rather than one:

  • BasketStateContext carries the basket. Its value changes on every action.
  • BasketDispatchContext carries dispatch. React gives dispatch a stable identity, so this value never changes.

A component that reads a context re-renders whenever that context's value changes. If the basket and dispatch shared one context, every add button would re-render on every action, even though a button only ever sends actions. With two contexts, the buttons read only the one that never changes.

The hooks live in the same file as the contexts, so the rest of the app never touches the contexts directly:

Bash
cat > src/basket/context.ts <<'TS'
import { createContext, useContext, type Dispatch } from 'react'
import { basketTotal, countItems, type BasketAction, type BasketState } from './reducer'

export const BasketStateContext = createContext<BasketState | null>(null)
export const BasketDispatchContext = createContext<Dispatch<BasketAction> | null>(null)

export function useBasket() {
  const state = useContext(BasketStateContext)
  if (state === null) throw new Error('useBasket must be used inside <BasketProvider>')
  return {
    lines: state.lines,
    itemCount: countItems(state),
    totalKobo: basketTotal(state),
  }
}

export function useBasketDispatch(): Dispatch<BasketAction> {
  const dispatch = useContext(BasketDispatchContext)
  if (dispatch === null) throw new Error('useBasketDispatch must be used inside <BasketProvider>')
  return dispatch
}
TS
cat > src/basket/BasketProvider.tsx <<'TSX'
import { useReducer, type ReactNode } from 'react'
import { basketReducer, initialBasket } from './reducer'
import { BasketDispatchContext, BasketStateContext } from './context'

export function BasketProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(basketReducer, initialBasket)
  return (
    <BasketDispatchContext value={dispatch}>
      <BasketStateContext value={state}>{children}</BasketStateContext>
    </BasketDispatchContext>
  )
}
TSX

Three choices are worth knowing:

  • The default value is null, not an empty basket. A component rendered outside the provider then throws a message that names the problem, instead of quietly showing an empty basket that never changes.
  • React 19 lets you render a context itself as the provider, <BasketStateContext value={...}>. Older code writes <BasketStateContext.Provider value={...}>, which still works.
  • BasketProvider takes children instead of rendering the app itself. When its state changes, React re-renders BasketProvider, but the children elements were created by its parent, which did not re-render. So React only revisits the components that read a context whose value changed.

Check it worked

Bash
npx tsc -b

The type checker prints nothing. Nothing on the page has changed yet, because no component uses the provider. You connect it in the next step.

Step 5 · Connect the components and remove the drilled props

Wrap the app in BasketProvider and let each component take what it needs from the hooks. App no longer holds any state. Shop, ProductList and ProductCard lose their onAdd prop, and Header loses itemCount.

Bash
cat > src/App.tsx <<'TSX'
import { BasketProvider } from './basket/BasketProvider'
import { Header } from './components/Header'
import { Shop } from './components/Shop'
import { BasketPanel } from './components/BasketPanel'
import './App.css'

export default function App() {
  return (
    <BasketProvider>
      <div className="stall">
        <Header />
        <main className="layout">
          <Shop />
          <BasketPanel />
        </main>
      </div>
    </BasketProvider>
  )
}
TSX
cat > src/components/Header.tsx <<'TSX'
import { useBasket } from '../basket/context'
import { logRender } from '../debug'

function BasketBadge() {
  logRender('BasketBadge')
  const { itemCount } = useBasket()
  return (
    <p className="badge" role="status">
      Basket: {itemCount} {itemCount === 1 ? 'item' : 'items'}
    </p>
  )
}

export function Header() {
  logRender('Header')
  return (
    <header className="header">
      <h1>Corner craft stall</h1>
      <BasketBadge />
    </header>
  )
}
TSX
cat > src/components/Shop.tsx <<'TSX'
import { products, formatPrice, type Product } from '../products'
import { useBasketDispatch } from '../basket/context'
import { logRender } from '../debug'

function AddToBasketButton({ product }: { product: Product }) {
  logRender('AddToBasketButton')
  const dispatch = useBasketDispatch()
  return (
    <button type="button" onClick={() => dispatch({ type: 'itemAdded', productId: product.id })}>
      Add to basket<span className="visually-hidden">: {product.name}</span>
    </button>
  )
}

function ProductCard({ product }: { product: Product }) {
  logRender('ProductCard')
  return (
    <li className="card">
      <span className="name">{product.name}</span>
      <span className="price">{formatPrice(product.priceKobo)}</span>
      <AddToBasketButton product={product} />
    </li>
  )
}

function ProductList() {
  logRender('ProductList')
  return (
    <ul className="products">
      {products.map((product) => (
        <ProductCard key={product.id} product={product} />
      ))}
    </ul>
  )
}

export function Shop() {
  logRender('Shop')
  return (
    <section aria-labelledby="shop-heading">
      <h2 id="shop-heading">Products</h2>
      <ProductList />
    </section>
  )
}
TSX
cat > src/components/BasketPanel.tsx <<'TSX'
import { findProduct, formatPrice } from '../products'
import { useBasket, useBasketDispatch } from '../basket/context'
import { logRender } from '../debug'

export function BasketPanel() {
  logRender('BasketPanel')
  const { lines, totalKobo } = useBasket()
  const dispatch = useBasketDispatch()
  return (
    <section aria-labelledby="basket-heading" className="basket">
      <h2 id="basket-heading">Basket</h2>
      {lines.length === 0 ? (
        <p>Your basket is empty.</p>
      ) : (
        <>
          <ul className="lines">
            {lines.map((line) => {
              const product = findProduct(line.productId)
              return (
                <li key={line.productId}>
                  <span className="name">{product.name}</span>
                  <button
                    type="button"
                    aria-label={`Remove one ${product.name}`}
                    onClick={() => dispatch({ type: 'itemDecreased', productId: line.productId })}
                  >
                    −
                  </button>
                  <span className="qty">{line.quantity}</span>
                  <button
                    type="button"
                    aria-label={`Add one more ${product.name}`}
                    onClick={() => dispatch({ type: 'itemAdded', productId: line.productId })}
                  >
                    +
                  </button>
                </li>
              )
            })}
          </ul>
          <p className="total">
            Total: <strong>{formatPrice(totalKobo)}</strong>
          </p>
          <button type="button" onClick={() => dispatch({ type: 'basketCleared' })}>
            Empty basket
          </button>
        </>
      )}
    </section>
  )
}
TSX

Compare ProductCard with its earlier version: it takes only the product. You could now move AddToBasketButton anywhere inside the provider, such as a product detail page, without touching any component in between.

Check it worked

Bash
npx tsc -b

Reload the page, clear the console, and select "Add to basket" on the tote bag. The console now shows only render BasketBadge and render BasketPanel (twice each in development). No Shop, ProductList, ProductCard or AddToBasketButton line appears. Add two candles, then select − next to one of them: the badge reads "Basket: 2 items" and the total is ₦18,000.00. "Empty basket" brings back "Your basket is empty."

If you have React Developer Tools installed, the Profiler tab shows the same thing as a chart of which components rendered for each click.

Step 6 · Test the reducer as a plain function

All the rules for the basket now live in one function that takes data and returns data. It needs no browser, no rendering and no mocks to test. Install Vitest and add a test script:

Bash
npm install --save-dev vitest@5.1.1
npm pkg set scripts.test="vitest run"

Write the reducer tests. The run helper replays a list of actions with Array.prototype.reduce, which is where the name "reducer" comes from: React folds each dispatched action into the state the same way.

Bash
cat > src/basket/reducer.test.ts <<'TS'
import { describe, expect, it } from 'vitest'
import {
  basketReducer,
  basketTotal,
  countItems,
  initialBasket,
  type BasketAction,
  type BasketState,
} from './reducer'

function run(...actions: BasketAction[]): BasketState {
  return actions.reduce(basketReducer, initialBasket)
}

const add = (productId: string): BasketAction => ({ type: 'itemAdded', productId })

describe('basketReducer', () => {
  it('adds a line, then increases its quantity', () => {
    const state = run(add('tote'), add('tote'), add('shea'))
    expect(state.lines).toEqual([
      { productId: 'tote', quantity: 2 },
      { productId: 'shea', quantity: 1 },
    ])
    expect(countItems(state)).toBe(3)
    expect(basketTotal(state)).toBe(2 * 1_500_000 + 450_000)
  })

  it('drops a line when its quantity reaches zero', () => {
    const state = run(add('candle'), { type: 'itemDecreased', productId: 'candle' })
    expect(state.lines).toEqual([])
  })

  it('removes a whole line whatever its quantity', () => {
    const state = run(add('tote'), add('tote'), add('shea'), { type: 'itemRemoved', productId: 'tote' })
    expect(state.lines).toEqual([{ productId: 'shea', quantity: 1 }])
  })

  it('returns the same object when nothing changes', () => {
    const state = run(add('tote'))
    expect(basketReducer(state, { type: 'itemDecreased', productId: 'candle' })).toBe(state)
  })

  it('empties the basket', () => {
    expect(run(add('tote'), add('shea'), { type: 'basketCleared' })).toEqual(initialBasket)
  })

  it('never changes the state it is given', () => {
    const before = run(add('tote'))
    Object.freeze(before)
    Object.freeze(before.lines)
    before.lines.forEach((line) => Object.freeze(line))
    const after = basketReducer(before, add('tote'))
    expect(before.lines[0].quantity).toBe(1)
    expect(after.lines[0].quantity).toBe(2)
  })
})
TS

The last test freezes the old state. Writing to a frozen object throws in a module, so if the reducer ever changed line.quantity in place, the test would fail with a clear error instead of passing by luck.

The hooks deserve one test too: used outside the provider, they must throw the helpful message. renderToString from react-dom/server renders a component to HTML in Node.js, so this test also needs no browser:

Bash
cat > src/basket/context.test.tsx <<'TSX'
import { describe, expect, it } from 'vitest'
import { renderToString } from 'react-dom/server'
import { BasketProvider } from './BasketProvider'
import { useBasket } from './context'

function ItemCount() {
  const { itemCount } = useBasket()
  return <p>{itemCount}</p>
}

describe('useBasket', () => {
  it('reads the basket inside the provider', () => {
    const html = renderToString(
      <BasketProvider>
        <ItemCount />
      </BasketProvider>,
    )
    expect(html).toBe('<p>0</p>')
  })

  it('throws a helpful error outside the provider', () => {
    expect(() => renderToString(<ItemCount />)).toThrow('inside <BasketProvider>')
  })
})
TSX
npm test

Check it worked

Vitest ends with a summary along the lines of Test Files 2 passed (2) and Tests 8 passed (8). To watch a test catch a real mistake, change { ...line, quantity: line.quantity + 1 } in the itemAdded case to line and run npm test: the first test fails and shows the expected and received quantities. Put it back afterwards.

Step 7 · Decide when context and a reducer are enough, then build

Context with a reducer is part of React itself: no extra dependency and nothing new for the next developer to learn. It fits well when:

  • updates come from people clicking and typing, a few times a second at most
  • the shared state is small, and most of the components that read it need most of it
  • one part of the tree owns the state, such as a basket, a signed-in user or a theme

It starts to strain when:

  • many components each need a small slice of a large object. Every component that reads a context re-renders when any part of its value changes. You can split contexts further, but beyond three or four it gets awkward. Libraries such as Zustand or Redux let a component subscribe through a selector and re-render only when its slice changes.
  • updates arrive fast, from a WebSocket, a timer or a drag, and reach many readers
  • you need the state outside React components, or want time-travel debugging and middleware

Server data is a separate case. A product list fetched from an API is a cache of someone else's data, with loading, errors and refetching. A tool such as TanStack Query handles that better than any reducer you would write.

One more consideration for your users: a basket held in the browser costs no network request per click, which matters on prepaid mobile data and patchy connections. It also disappears on reload. If that matters, save it to localStorage and read it back with useReducer's third argument, an initialiser function; remember user settings with localStorage covers the storage part.

Stop the dev server with Ctrl+C in its terminal.

Build the production version. The build type-checks every file in src, including the tests, then bundles the app:

Bash
npm run build
ls dist

Check it worked

The build ends with built in and a time, and dist contains index.html and an assets folder. Look at your own app and count the components that would read your shared state, and how often it changes. If that is a handful of components and changes at the speed of clicks, context and a reducer are enough. If it is dozens of components reading small slices, or updates many times a second, that is the point where a store library earns its place.

When you have finished, remove the project:

Bash
cd ~
rm -rf ~/basket-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.