React patterns reference

Most React patterns decide who owns the state.

Composition, compound components, controlled inputs, hooks, and context are different answers to the same questions: which component owns this state, which one owns this markup, and how they talk to each other. This reference covers eight patterns for React 19 and the Next.js App Router, with the trap each one hides. For state that outgrows components, see Zustand store structure.

children · slot props

Composition with children and slots

A component that accepts children, or named slot props such as header and actions, lets its caller decide what goes inside without the component knowing about it. Composition is React’s default answer to reuse, and the first fix for prop drilling: the parent that has the data renders the child itself and passes it down as an element.

Use it for

  • Layout components — cards, dialogs, page shells — that frame content they do not own.
  • Avoiding prop drilling through components that only forward data they never read.

Watch for

  • A component that grows a prop for every variation (showIcon, iconPosition, iconSize…) is asking to take a slot instead.
  • Slots trade control for flexibility: the component can no longer guarantee what is inside it. Use them where callers genuinely differ.
function Card({ header, actions, children }: {
  header: ReactNode
  actions?: ReactNode
  children: ReactNode
}) {
  return (
    <section className="card">
      <header>
        {header}
        {actions}
      </header>
      {children}
    </section>
  )
}

<Card header={<h2>Invoices</h2>} actions={<ExportButton />}>
  <InvoiceTable rows={rows} />
</Card>

<Tabs> · <Tabs.Trigger> · <Tabs.Panel>

Compound components

A compound component is a set of components that work together and share state through context — Tabs with its list, triggers, and panels. The parent owns the state, and the caller arranges, wraps, and styles the parts freely. Most headless UI libraries, including Radix, Base UI, and React Aria, are built this way.

Use it for

  • Widgets with several coordinated parts: tabs, accordions, menus, selects, steppers.
  • Giving callers control over markup and order without a configuration object of props.

Watch for

  • The parts only work inside their parent. Throw a clear error when the context is missing, rather than rendering nothing.
  • A context value recreated on every render re-renders every part. Memoise it, or let the React Compiler do it.
type TabsState = { value: string; select(value: string): void }
const TabsContext = createContext<TabsState | null>(null)

function useTabs() {
  const tabs = use(TabsContext)
  if (!tabs) throw new Error("Tabs parts must be inside <Tabs>")
  return tabs
}

function Tabs({ defaultValue, children }: TabsProps) {
  const [value, select] = useState(defaultValue)
  return <TabsContext value={{ value, select }}>{children}</TabsContext>
}

function Trigger({ value, children }: TriggerProps) {
  const tabs = useTabs()
  return (
    <button
      role="tab"
      aria-selected={tabs.value === value}
      onClick={() => tabs.select(value)}
    >
      {children}
    </button>
  )
}

value · defaultValue

Controlled and uncontrolled components

A controlled component takes its current value from props and reports changes through a callback, so the parent is the single source of truth. An uncontrolled component keeps its own state and takes only an initial value. Reusable inputs often support both: value and onChange when the caller needs control, defaultValue when it does not.

Use it for

  • Controlled: values other parts of the UI read or constrain — live validation, dependent fields, formatting while typing.
  • Uncontrolled: simple forms read on submit through FormData, which is also how server actions receive them.

Watch for

  • Switching modes — value starting as undefined and later becoming a string — triggers React’s warning and changes behaviour. Start from an empty string.
  • Copying a prop into state with useState(props.value) creates a second source of truth that stops following the prop. Control it, or reset it with a key.
function useControllable<T>(
  value: T | undefined,
  defaultValue: T,
  onChange?: (next: T) => void
) {
  const [inner, setInner] = useState(defaultValue)
  const controlled = value !== undefined
  const current = controlled ? value : inner
  const set = (next: T) => {
    if (!controlled) setInner(next)
    onChange?.(next)
  }
  return [current, set] as const
}

useSomething()

Custom hooks

A custom hook is a function that calls other hooks, so stateful logic — a subscription, a debounced value, a media query — can be shared without sharing markup. Hooks replaced most higher-order components and the container and presentational split: the logic moves into a hook, and the component keeps the rendering.

Use it for

  • Logic needed by several components: useDebouncedValue, useMediaQuery, useOnlineStatus.
  • Giving a complicated component a readable top level by moving its effects and state into a named hook.

Watch for

  • Each call to a hook has its own state. Two components calling useCart() do not share a cart unless the hook reads a shared store or context.
  • A hook that wraps a single useState with no logic is indirection without a reason.
  • Effects that keep one piece of state in sync with another are usually derivations. Compute the value during render instead.
function useMediaQuery(query: string) {
  return useSyncExternalStore(
    (onChange) => {
      const list = window.matchMedia(query)
      list.addEventListener("change", onChange)
      return () => list.removeEventListener("change", onChange)
    },
    () => window.matchMedia(query).matches,
    () => false // the server snapshot
  )
}

const isWide = useMediaQuery("(min-width: 1024px)")

renderItem={(item) => …}

Render props

A render prop is a function prop the component calls to render part of its output, passing in state the caller needs — the row being rendered, whether an item is selected. Hooks replaced most render props, but the pattern still fits when the component owns iteration or layout and the caller owns the markup of each item.

Use it for

  • Virtualised lists and tables: the component decides which rows exist, the caller renders a row.
  • Headless components that expose per-item state, such as renderItem(item, { selected }).

Watch for

  • Nested render props build the pyramid hooks were introduced to flatten. If the caller only needs the state, offer a hook.
  • An inline render function is a new function on every render, so memoised children re-render. Usually harmless; measure before optimising.
<VirtualList
  items={messages}
  rowHeight={56}
  renderItem={(message, { index }) => (
    <MessageRow
      key={message.id}
      message={message}
      striped={index % 2 === 1}
    />
  )}
/>

useState · key

Colocating and lifting state

State belongs in the lowest component that needs it. When two siblings need the same state, lift it to their closest common parent and pass it down; when only one component reads it, move it back down. Colocated state re-renders less, is deleted along with its component, and is easier to follow.

Use it for

  • Placing a new piece of state: start next to the component that uses it, and lift it only when a second component needs it.
  • Resetting a component’s state by changing its key. A new key mounts a fresh instance, as with key={user.id} on a profile form.

Watch for

  • A global store for everything by default makes every component depend on everything. Most state is either local or server data.
  • Copying server data into client state means two copies to keep in sync. Read it from the data layer — server components or a query cache — instead.
  • Derived values stored in state drift from their source. If it can be computed from props and state during render, compute it.
function Checkout() {
  // Lifted: both children read the same coupon
  const [coupon, setCoupon] = useState<string | null>(null)
  return (
    <>
      <CouponField onApply={setCoupon} />
      <OrderSummary coupon={coupon} />
    </>
  )
}

// A fresh form per user, with no effect copying props into state
<ProfileForm key={user.id} user={user} />

createContext · use()

Context for dependency injection

Context makes a value available to every component below a provider without passing it through each level. It suits values that change rarely and are needed widely — the session, theme, locale, an API client — and that tests or stories may want to replace. It is a way to pass values down, not a state manager.

Use it for

  • App-wide, slow-changing values: session, theme, feature flags, translations.
  • Injecting dependencies such as an API client, so tests and stories can provide a fake.
  • State scoped to one subtree, such as a compound component or a multi-step form.

Watch for

  • Every consumer re-renders when the value changes. Fast-changing state in one large context re-renders the whole tree; split the context or use a store with selectors.
  • A provider at the app root for state one page uses makes everything depend on it. Put the provider where its subtree starts.
  • In the App Router a provider must be a client component. Render it in a layout around children, and those children can still be server components.
const ApiContext = createContext<ApiClient>(realApi)

export function useApi() {
  return use(ApiContext)
}

// The app uses the default. A test or story passes a fake:
<ApiContext value={fakeApi}>
  <InvoicePage />
</ApiContext>

"use client"

Server and client components

In the Next.js App Router, components are server components by default: they run on the server, can read the database directly, and send no JavaScript of their own. A "use client" directive marks where interactivity starts, and that file and everything it imports ship to the browser. The pattern is to keep that boundary low, with interactive leaves inside server-rendered pages.

Use it for

  • Data access and secrets in server components; state, effects, and event handlers in client components.
  • Passing server components into a client component as children, so a client shell such as a collapsible panel can wrap server-rendered content.

Watch for

  • "use client" at the top of a page makes the whole subtree client code, including libraries that only formatted data.
  • Props that cross the boundary must be serialisable: no functions other than server actions, and no class instances.
  • A client component cannot import a server component. It can only receive one as children or another prop.
  • Add import "server-only" to modules that hold secrets, so importing one into client code fails the build instead of shipping it.
// app/invoices/page.tsx: a server component, ships no JS of its own
export default async function InvoicesPage() {
  const invoices = await db.invoices.list()
  return (
    <Collapsible title="Invoices">
      <InvoiceTable rows={invoices} />
    </Collapsible>
  )
}

// collapsible.tsx: a client component that owns the open state
"use client"
export function Collapsible({ title, children }: CollapsibleProps) {
  const [open, setOpen] = useState(true)
  // …renders a toggle button, and children when open
}

Start from the problem

A component has a prop for every variation
Composition with children and slots
Props pass through components that never read them
Composition with children and slots
A widget’s parts share state but must stay rearrangeable
Compound components
An input must work with and without a parent’s state
Controlled and uncontrolled components
The same effect and state code appears in several components
Custom hooks
A list owns which rows render; the caller owns each row
Render props
A form keeps showing the previous record’s values
Colocating and lifting state
Tests need to swap the API client a component uses
Context for dependency injection
A page ships a large bundle for content that never changes
Server and client components

Keep going

Plan the structure before writing the components.

Nodlume is a system-design workspace for React applications. Pages, components, stores, data models, and API routes are planned in one place and exported as a scaffold.

Start planning free

With your permission, Affonso uses a 30-day cookie to remember which affiliate referred you. Google Analytics measures site usage. Google Ads measures our advertising. Microsoft Clarity records masked session replays. You can use Nodlume with or without these cookies.