-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Add client state patterns for context vs store #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> | ||
| ) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| 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 | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.