Skip to content
JL

Home

About

Blog

Contact

Shop

Portfolio

Privacy

TOS

Click to navigate

  1. Home
  2. Joshua R. Lehman's Blog
  3. Advanced TypeScript React Patterns

Table of contents

  • Share on X
  • Discuss on X

Related Articles

TypeScript with React Components and Props
TypeScript
12m
Nov 10, 2026

TypeScript with React Components and Props

Good React prop types express the component’s real states and relationships. Learn practical patterns for variants, native elements, children, events, polymorphism, and reusable component APIs.

#TypeScript#React+4
TypeScript React Hooks: State, Effects, and Refs
TypeScript
12m
Nov 17, 2026

TypeScript React Hooks: State, Effects, and Refs

Hooks are small APIs with large consequences. Learn patterns for inferrable state, explicit nullable values, effect cleanup, refs, reducers, and custom hooks that remain understandable as a feature grows.

#TypeScript#React+5
Advanced Utility Type Patterns in TypeScript
TypeScript
11m
Sep 22, 2026

Advanced Utility Type Patterns in TypeScript

Utility types become powerful when they express a deliberate policy. Learn how to filter keys by value type, build writable patch contracts, and keep advanced transformations understandable.

#TypeScript#Utility Types+4
Ask me anything! 💬

© Joshua R. Lehman

Full Stack Developer

Crafted with passion • Built with modern web technologies

2026 • All rights reserved

Contents

  • Patterns Are API Design Choices
  • Context Should Carry Stable Shared Meaning
  • Compound Components Express a Shared State Machine
  • Render Props Preserve a Useful Escape Hatch
  • HOCs Need a Precise Boundary
  • Key Takeaways
TypeScript

Advanced TypeScript React Patterns

November 24, 2026•7 min read
Joshua R. Lehman
Joshua R. Lehman
Centred React composition diagram connecting context, compound components, render props, and reusable typed interfaces
Advanced TypeScript React Patterns

Advanced React patterns are often introduced as techniques to memorize: Context, compound components, render props, higher-order components. That framing encourages teams to apply a pattern because it looks reusable rather than because it clarifies a real relationship in the interface.

The better question is architectural: what state is shared, who owns it, how much layout freedom does a caller need, and which guarantees should the component enforce? TypeScript makes those answers durable when the types reflect the public contract instead of obscuring it with clever machinery.

Patterns Are API Design Choices

A plain component with explicit props is the best default. Reach for a larger pattern only when ordinary props create repeated threading, awkward coordination between sibling parts, or a real need for caller-controlled rendering. Each pattern buys something and creates a new responsibility:

PatternIt is good atIts cost
ContextStable shared meaning across a subtreeHidden dependency and update scope
Compound componentsCoordinated parts with flexible layoutProvider/consumer contract and misuse handling
Render propsCaller-owned rendering with library-owned behaviourCallback API and render complexity
HOCsCross-cutting adaptation at component boundariesProp forwarding, refs, display names, wrapper depth

If a component only needs a value and callback from its parent, use props. If a component only needs local state, keep it local. Abstraction is valuable when it removes a repeated decision, not when it turns a simple tree into a miniature framework.

Context Should Carry Stable Shared Meaning

Context works well for dependencies that many descendants legitimately need: a theme, locale, authenticated session boundary, or a coordinated component’s internal state. Type the context as the actual contract, and use undefined as the default when consuming outside its provider is a programming error.

type TabsContextValue = {
  activeId: string;
  select(id: string): void;
};
 
const TabsContext = createContext<TabsContextValue | undefined>(undefined);
 
function useTabsContext() {
  const value = useContext(TabsContext);
  if (!value) throw new Error("Tabs components must be rendered inside <Tabs>");
  return value;
}

The custom hook gives consumers a helpful error rather than a non-null assertion and preserves a non-optional return type after the boundary. Do not put rapidly changing unrelated values in one global context merely to avoid props. A broad provider makes render behaviour harder to reason about and turns a local component dependency into invisible ambient state.

Context Is Not a Substitute for Component Boundaries

If a child needs a value only because a parent has not decided which component owns the behaviour, context will hide the uncertainty rather than resolve it. Keep data flow explicit until a stable shared boundary is clear.

Compound Components Express a Shared State Machine

Compound components make sense when several related child parts participate in one state machine while the caller controls their layout. Tabs, menus, dialogs, and select controls are common examples. The parent owns coordination; the children consume a narrow internal contract.

type TabsProps = { defaultActiveId: string; children: React.ReactNode };
 
export function Tabs({ defaultActiveId, children }: TabsProps) {
  const [activeId, setActiveId] = useState(defaultActiveId);
  return (
    <TabsContext.Provider value={{ activeId, select: setActiveId }}>
      {children}
    </TabsContext.Provider>
  );
}
 
function Tab({ id, children }: { id: string; children: React.ReactNode }) {
  const { activeId, select } = useTabsContext();
  return (
    <button
      aria-selected={activeId === id}
      onClick={() => select(id)}
      role="tab"
    >
      {children}
    </button>
  );
}

The public API should still make accessibility and ownership visible. A tab is not merely a styled button: it needs a corresponding tab panel, keyboard interaction, stable IDs, and selected state. TypeScript can guarantee the id exists; tests and semantic HTML verify the relationship actually works.

Avoid pretending TypeScript can perfectly enforce that callers arrange children in a specific JSX shape. If exact structure is required, use an explicit data model or validate children at runtime. Flexible composition and strict structural guarantees pull in opposite directions.

Render Props Preserve a Useful Escape Hatch

Render props remain valuable when a reusable hook or component owns behaviour while the caller needs complete control over markup. A headless listbox, virtualized row, or permission gate may expose a function instead of choosing the final elements itself.

type PermissionGateProps = {
  permission: string;
  children: (result: {
    allowed: boolean;
    requestAccess(): void;
  }) => React.ReactNode;
};
 
function PermissionGate({ permission, children }: PermissionGateProps) {
  const result = usePermission(permission);
  return <>{children(result)}</>;
}

The callback type documents what the library owns and what the caller decides. Keep the object small and domain-oriented. Exposing every internal event, ref, and transient flag turns a helpful escape hatch into a dependency on implementation details. In many modern cases a custom hook is the simpler render-prop alternative; use a component when it supplies a meaningful boundary or lifecycle.

HOCs Need a Precise Boundary

A higher-order component takes a component and returns an adapted component. They remain practical for integration layers, legacy code, instrumentation, or injecting a narrow cross-cutting dependency. The key is to subtract injected props from the wrapper’s public contract.

type WithFeatureFlagProps = { enabled: boolean };
 
function withFeatureFlag<Props extends WithFeatureFlagProps>(
  Component: React.ComponentType<Props>
) {
  return function FeatureFlagged(
    props: Omit<Props, keyof WithFeatureFlagProps>
  ) {
    const enabled = useFeatureFlag();
    return <Component {...(props as Props)} enabled={enabled} />;
  };
}

This pattern needs care around refs, static properties, display names, prop collisions, and the assertion required for generic prop reconstruction. That friction is information: for new code, a custom hook or explicit wrapper component is often clearer. Choose an HOC when the adaptation itself is the reusable API, not merely to avoid writing a small component.

Keep state ownership visible

The unifying design question across these patterns is ownership. A Tabs component should own which tab is active; a caller should own the labels, panel content, and surrounding layout. A permission hook should own how a policy is queried; a caller should own what its allowed and denied UI says. When ownership is muddled, types grow increasingly elaborate because they are attempting to encode a decision nobody made.

Write the ownership sentence before introducing the abstraction: “This provider owns selection state and its children render it.” “This hook owns subscription lifecycle and exposes the current value.” “This wrapper supplies analytics metadata and otherwise preserves the component’s contract.” If that sentence describes two unrelated owners, split the component.

Testing the composed contract

TypeScript protects the caller during development, but runtime tests must prove the composition works: tabs identify their panels, a missing provider produces a useful development failure, a render prop receives the promised values, and an adapted component forwards semantic props and refs as intended. Test the public interaction rather than the provider’s implementation details. A component API is successful when a caller can use it without understanding its internals.

A practical selection guide

Choose plain props when one parent already owns state and children simply render it. Choose context when several coordinated descendants need stable shared state and prop threading would obscure the relationship. Choose a compound component when callers need layout freedom across those coordinated descendants. Choose a custom hook or render prop when behaviour should be reusable while markup remains entirely caller-owned. Choose an HOC only when adapting component boundaries is itself the stable abstraction.

This sequence avoids a common trap: starting with the most flexible pattern and trying to constrain it later. Start with the smallest honest public contract. Generalize only after repeated consumers demonstrate which variation is real.

Migration without a component rewrite

You do not need to replace every existing prop API with a compound component or context provider. Introduce an internal hook first, keep the existing public props, and use the hook to consolidate duplicated behaviour. If multiple consumers later need layout freedom, expose a small compound-component layer that calls the same internal machinery. Existing callers keep working while the new abstraction earns its place.

Likewise, remove advanced patterns when their reason disappears. A context created to avoid three levels of prop threading can become unnecessary after a layout change. A render prop that exposes one boolean may become a clearer hook. Good component design is reversible: types should let the team change internal ownership without forcing every caller to learn the migration at once.

Key Takeaways

  • Start with plain props and local state; advanced patterns should solve a specific ownership or composition problem.
  • Use context for stable shared meaning and expose it through a guarded custom hook.
  • Use compound components for genuinely coordinated parts, while preserving semantic and accessibility contracts.
  • Use render props or hooks when behaviour is reusable but markup must remain caller-owned.
  • Use HOCs sparingly and type their injected props as a deliberate public-boundary transformation.

Next, we return to Next.js Route Handlers: when a server-side HTTP boundary is the right tool for webhooks, integrations, downloads, and clients outside the React tree.