Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ Front-end work has changed a lot since the SPA-everything era: rendering moved b
- `useActionState` and `useFormStatus` for form result, error, and pending states
- Request-scoped memoization for fetch deduplication (the `React.cache()` pattern)
- Out-of-order streaming: boundaries flush by resolution time, not tree order
- Pure reducers and discriminated-union actions for client state transitions
- React Context with split state/dispatch providers
- External stores via `useSyncExternalStore` and selector subscriptions
- Re-render isolation: when context wins vs when a store wins
- App Router file conventions (`layout`, `page`, `loading`, `error`)
- Type-safe design tokens as a single origin for color, spacing, and type scale
- Core Web Vitals: LCP, CLS, and INP tracked against a budget
Expand All @@ -28,8 +32,8 @@ Front-end work has changed a lot since the SPA-everything era: rendering moved b
- Scaffold: Next.js 15 App Router, React 19, strict TypeScript, Vitest + Testing Library, GitHub Actions CI, and a design-token stylesheet. The home route lists the planned concepts using an accessible `ConceptCard` component.
- Design tokens: a typed token tree in `src/tokens` that generates the app's CSS custom properties. The root layout injects the generated `:root` rule at render time, so the token module is the runtime source and there is no second copy to drift. See the `/tokens` route.
- Server Components + streaming: the `/streaming` route is a Server Component whose three cards are each their own async Server Component behind a Suspense boundary. The shell flushes first, then each card streams in as its own fetch settles, fastest first. Data comes from a small simulated layer built on a request-scoped memoizing loader (the `React.cache()` pattern), so components that read the same key during one render share a single fetch and a rejection is cached the same way. Tests cover the loader dedup, out-of-order settle order, and the async components rendered to static markup. See the `/streaming` route.

- Server actions & optimistic UI: the `/data-patterns` route mutates a note list through a Server Action, so the browser never runs a fetch handler or a client API layer. `useActionState` holds the confirmed list plus the last error, `useOptimistic` overlays the in-flight note on top of it, and `useFormStatus` drives the pending button. The overlay is only a prediction, so React discards it when the action settles and a rejected write reverts on its own with no manual rollback. The mutation core (`applyAdd`) takes an injected store, which keeps validation, the fail path, and the store-throws path testable without the Next runtime. Tests cover trimming and length validation, the optimistic reducer folding pending dispatches newest-first, and confirmed state staying put on every failure mode. See the `/data-patterns` route.
- Client state patterns: the `/state-management` route runs one pure cart reducer in two hosts. Context + `useReducer` (split state/dispatch) re-renders every state consumer on any field change. An external store on `useSyncExternalStore` lets each leaf select a slice and skip the render when that slice is unchanged. Typing the note field is the repro: context bumps badge and total counters; the store leaves them alone.

## Stack

Expand Down Expand Up @@ -85,6 +89,14 @@ async function onSubmit(formData: FormData) {
// fail or a thrown store -> confirmed list unchanged, error set
```

The same cart reducer can sit in Context or in an external store. Selectors decide who re-renders:

```tsx
const store = createReducerStore(cartReducer, EMPTY_CART)
const count = useStoreSelector(store, selectItemCount)
store.dispatch({ type: 'setNote', note: 'gift' }) // count subscriber stays quiet
```

Styles reference tokens through a typed helper, so a bad name fails to compile:

```tsx
Expand All @@ -99,5 +111,7 @@ import { token } from '@/tokens'
```
app/ App Router routes, layout, and global tokens
src/components/ shared, tested UI primitives
src/state/ pure cart reducer, context provider, external store
src/tokens/ typed design tokens and CSS variable generation
test/ Vitest specs and setup
```
6 changes: 6 additions & 0 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ const CONCEPTS: readonly Concept[] = [
status: 'done',
href: '/data-patterns'
},
{
title: 'Client state: context vs store',
description: 'Same pure reducer, two hosts: React Context re-renders every consumer; a store selects slices.',
status: 'done',
href: '/state-management'
},
{
title: 'Design tokens',
description: 'A typed token system that stays the single origin for color, spacing, and type scale.',
Expand Down
155 changes: 155 additions & 0 deletions app/state-management/demo.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
'use client'
import { useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react'
import {
EMPTY_CART,
cartReducer,
selectItemCount,
selectNote,
selectTotal,
type CartAction,
type CartItem,
type CartState
} from '@/state/cart'
import { CartProvider, useCartDispatch, useCartState } from '@/state/cart-context'
import { createReducerStore, useStoreSelector, type ReducerStore } from '@/state/create-store'
import { token } from '@/tokens'
const CATALOG: readonly Omit<CartItem, 'qty'>[] = [
{ id: 'mug', name: 'Mug', price: 12 },
{ id: 'sticker', name: 'Sticker', price: 3 }
]
const card: CSSProperties = {
padding: token('space', '4'),
border: '1px solid var(--color-border)',
borderRadius: token('radius', 'md'),
background: 'var(--color-surface)',
display: 'grid',
gap: token('space', '3')
}
const field: CSSProperties = {
padding: token('space', '2'),
borderRadius: token('radius', 'md'),
border: '1px solid var(--color-border)',
background: 'var(--color-bg)',
color: 'var(--color-text)'
}
function Renders({ id }: { id: string }) {
const n = useRef(0)
n.current += 1
return (
<span data-testid={`renders-${id}`} style={{ fontSize: token('fontSize', 'sm'), color: token('color', 'muted'), fontFamily: 'var(--font-mono)' }}>
renders: {n.current}
</span>
)
}
function Panel({ title, children }: { title: string; children: ReactNode }) {
return (
<section aria-label={title} style={card}>
<h2 style={{ margin: 0, fontSize: token('fontSize', 'lg') }}>{title}</h2>
{children}
</section>
)
}
function AddButtons({ onAdd }: { onAdd: (item: Omit<CartItem, 'qty'>) => void }) {
return (
<div style={{ display: 'flex', gap: token('space', '2') }}>
{CATALOG.map((item) => (
<button key={item.id} type="button" onClick={() => onAdd(item)}>
Add {item.name}
</button>
))}
</div>
)
}
function Line({ label, value, id, testId }: { label: string; value: string | number; id: string; testId: string }) {
return (
<p style={{ margin: 0 }}>
{label}: <strong data-testid={testId}>{value}</strong> <Renders id={id} />
</p>
)
}
// Context leaves each call useCartState, so any field change re-renders all of them.
function CtxBadge() {
const { items } = useCartState()
return <Line label="Items" value={items.reduce((s, i) => s + i.qty, 0)} id="ctx-badge" testId="ctx-count" />
}
function CtxTotal() {
const { items } = useCartState()
return <Line label="Total" value={`$${items.reduce((s, i) => s + i.price * i.qty, 0)}`} id="ctx-total" testId="ctx-total" />
}
function CtxNote() {
const { note } = useCartState()
const dispatch = useCartDispatch()
return (
<label style={{ display: 'grid', gap: token('space', '2'), fontSize: token('fontSize', 'sm') }}>
<span>
Note <Renders id="ctx-note" />
</span>
<input data-testid="ctx-note-input" value={note} onChange={(e) => dispatch({ type: 'setNote', note: e.target.value })} style={field} />
</label>
)
}
function ContextPanel() {
const dispatch = useCartDispatch()
return (
<Panel title="Reducer + Context">
<AddButtons onAdd={(item) => dispatch({ type: 'add', item })} />
<CtxBadge />
<CtxTotal />
<CtxNote />
<button type="button" onClick={() => dispatch({ type: 'clear' })}>
Clear
</button>
</Panel>
)
}
// Store leaves each select one slice, so setNote leaves badge and total alone.
type CartStore = ReducerStore<CartState, CartAction>
function StoreBadge({ store }: { store: CartStore }) {
const count = useStoreSelector(store, selectItemCount)
return <Line label="Items" value={count} id="store-badge" testId="store-count" />
}
function StoreTotal({ store }: { store: CartStore }) {
const total = useStoreSelector(store, selectTotal)
return <Line label="Total" value={`$${total}`} id="store-total" testId="store-total" />
}
function StoreNote({ store }: { store: CartStore }) {
const note = useStoreSelector(store, selectNote)
return (
<label style={{ display: 'grid', gap: token('space', '2'), fontSize: token('fontSize', 'sm') }}>
<span>
Note <Renders id="store-note" />
</span>
<input data-testid="store-note-input" value={note} onChange={(e) => store.dispatch({ type: 'setNote', note: e.target.value })} style={field} />
</label>
)
}
function StorePanel({ store }: { store: CartStore }) {
return (
<Panel title="External store + selectors">
<AddButtons onAdd={(item) => store.dispatch({ type: 'add', item })} />
<StoreBadge store={store} />
<StoreTotal store={store} />
<StoreNote store={store} />
<button type="button" onClick={() => store.dispatch({ type: 'clear' })}>
Clear
</button>
</Panel>
)
}
export function StateDemo() {
const [resetKey, setResetKey] = useState(0)
const store = useMemo(() => createReducerStore(cartReducer, EMPTY_CART), [resetKey])
return (
<div style={{ display: 'grid', gap: token('space', '6'), marginTop: token('space', '8') }}>
<div style={{ display: 'grid', gap: token('space', '4'), gridTemplateColumns: 'repeat(auto-fit, minmax(16rem, 1fr))' }}>
<CartProvider key={resetKey}>
<ContextPanel />
</CartProvider>
<StorePanel store={store} />
</div>
<button type="button" onClick={() => setResetKey((k) => k + 1)}>
Reset both demos
</button>
</div>
)
}
27 changes: 27 additions & 0 deletions app/state-management/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { token } from '@/tokens'
import { StateDemo } from './demo'
export const metadata = {
title: 'Client state: reducer + context vs a store - Modern Frontend Lab'
}
export default function StateManagementPage() {
return (
<main style={{ maxWidth: '52rem', margin: '0 auto', padding: `${token('space', '8')} ${token('space', '4')}` }}>
<h1>Client state: reducer + context vs a store</h1>
<p style={{ color: token('color', 'muted'), marginTop: 0 }}>
Both panels share the same pure cart reducer. Context is on the left; an external store with
<code> useSyncExternalStore</code> selectors is on the right. Type in the note field and watch the render counters:
context re-renders every state consumer; the store only re-renders components whose selected value changed.
</p>
<StateDemo />
<section aria-label="Notes" style={{ marginTop: token('space', '8'), color: token('color', 'muted') }}>
<h2 style={{ fontSize: token('fontSize', 'lg'), color: 'var(--color-text)' }}>When each wins</h2>
<p>
Context fits tree-scoped UI that updates infrequently or where most consumers need most of the state. Split
state and dispatch contexts so pure dispatchers stay quiet. An external store wins when many leaves each need a
thin slice, updates are high-frequency, or non-React code shares the state. Selectors must return stable values;
a fresh object every call throws away the re-render savings.
</p>
</section>
</main>
)
}
31 changes: 31 additions & 0 deletions src/state/cart-context.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use client'
import { createContext, useContext, useReducer, type Dispatch, type ReactNode } from 'react'
import { cartReducer, EMPTY_CART, type CartAction, type CartState } from './cart'
// Split state and dispatch so components that only dispatch do not re-render
// when state changes. Dispatch identity is stable under useReducer.
const CartStateContext = createContext<CartState | null>(null)
Comment thread
ThomasHartDev marked this conversation as resolved.
const CartDispatchContext = createContext<Dispatch<CartAction> | null>(null)
export function CartProvider({
children,
initial = EMPTY_CART
}: {
children: ReactNode
initial?: CartState
}) {
const [state, dispatch] = useReducer(cartReducer, initial)
return (
<CartDispatchContext.Provider value={dispatch}>
<CartStateContext.Provider value={state}>{children}</CartStateContext.Provider>
</CartDispatchContext.Provider>
)
}
export function useCartState(): CartState {
const state = useContext(CartStateContext)
if (state === null) throw new Error('useCartState must be used inside CartProvider')
return state
}
export function useCartDispatch(): Dispatch<CartAction> {
const dispatch = useContext(CartDispatchContext)
if (dispatch === null) throw new Error('useCartDispatch must be used inside CartProvider')
return dispatch
}
68 changes: 68 additions & 0 deletions src/state/cart.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
export interface CartItem {
id: string
name: string
price: number
qty: number
}
export interface CartState {
items: readonly CartItem[]
// Changes often and is unrelated to the badge/total; useful for showing re-render cost.
note: string
}
export type CartAction =
| { type: 'add'; item: Omit<CartItem, 'qty'>; qty?: number }
| { type: 'remove'; id: string }
| { type: 'setQty'; id: string; qty: number }
| { type: 'setNote'; note: string }
| { type: 'clear' }
export const EMPTY_CART: CartState = { items: [], note: '' }
export function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case 'add': {
const qty = action.qty ?? 1
if (qty <= 0) return state
const existing = state.items.find((i) => i.id === action.item.id)
if (existing) {
return {
...state,
items: state.items.map((i) => (i.id === action.item.id ? { ...i, qty: i.qty + qty } : i))
}
}
return { ...state, items: [...state.items, { ...action.item, qty }] }
}
case 'remove': {
if (!state.items.some((i) => i.id === action.id)) return state
return { ...state, items: state.items.filter((i) => i.id !== action.id) }
}
case 'setQty': {
if (action.qty < 0) return state
const target = state.items.find((i) => i.id === action.id)
if (!target) return state
if (action.qty === 0) return { ...state, items: state.items.filter((i) => i.id !== action.id) }
if (target.qty === action.qty) return state
return {
...state,
items: state.items.map((i) => (i.id === action.id ? { ...i, qty: action.qty } : i))
}
}
case 'setNote':
if (state.note === action.note) return state
return { ...state, note: action.note }
case 'clear':
if (state.items.length === 0 && state.note === '') return state
return EMPTY_CART
default: {
const _exhaustive: never = action
return _exhaustive
}
}
}
export function selectItemCount(state: CartState): number {
return state.items.reduce((sum, i) => sum + i.qty, 0)
}
export function selectTotal(state: CartState): number {
return state.items.reduce((sum, i) => sum + i.price * i.qty, 0)
}
export function selectNote(state: CartState): string {
return state.note
}
Loading
Loading