Skip to content

Modern React and TypeScript Design Patterns Beyond the Gang of Four

Modern patterns from the JavaScript and TypeScript ecosystems - hooks, compound components, render props, and repositories that solve problems the GoF never faced.

Ayhan Sipahi Ayhan Sipahi

The Gang of Four documented patterns for C++ and Smalltalk in 1994, before asynchronous programming, component composition, and reactive data flow shaped how applications get written. JavaScript and TypeScript grew their own answers: React Hooks for sharing stateful logic, Compound Components for flexible APIs, the Repository pattern for data access, and ES modules as encapsulation. For TypeScript work on the front end or in Node, one default carries most of the weight: reach for a language or framework feature first, and add a pattern only when it removes a problem you can name.

That default follows from the constraints. First-class functions, closures, ES modules, async/await, and JSX make most classic indirection unnecessary. The patterns that survived in React and TypeScript codebases are the ones that solve problems the 1994 catalog never faced:

  • Sharing stateful logic without HOC wrapper hell
  • Building flexible component APIs without props explosion
  • Abstracting data access for testability
  • Encapsulating module-level state

Hooks Pattern: Stateful Logic Without Wrappers#

The Problem Hooks Solved#

Before hooks, sharing stateful logic in React required Higher-Order Components or Render Props. Both approaches created problems:

// HOC wrapper hell
export default withAuth(
  withTheme(
    withAnalytics(
      withErrorBoundary(
        Component
      )
    )
  )
);

// Render props callback hell
<DataFetcher url="/api/user">
  {(user, userLoading) => (
    <PermissionsChecker user={user}>
      {(permissions, permLoading) => (
        <ThemeProvider>
          {(theme) => (
            <Component
              user={user}
              permissions={permissions}
              theme={theme}
              loading={userLoading || permLoading}
            />
          )}
        </ThemeProvider>
      )}
    </PermissionsChecker>
  )}
</DataFetcher>

Debugging this is painful. React DevTools shows six levels of nesting before your actual component. Props collision becomes common when multiple HOCs add similarly-named props.

Custom Hooks: A New Pattern#

Hooks extract reusable logic into functions that share React’s state and lifecycle:

// Custom hook for data fetching
function useUser(userId: string) {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    let cancelled = false;
    // Clear the previous user's data as soon as the id changes
    setUser(null);
    setError(null);
    setLoading(true);

    async function fetchData() {
      try {
        const res = await fetch(`/api/users/${userId}`);
        if (!res.ok) {
          throw new Error(`GET /api/users/${userId} failed with ${res.status}`);
        }
        const data: User = await res.json();
        if (!cancelled) setUser(data);
      } catch (err) {
        if (!cancelled) setError(err instanceof Error ? err : new Error(String(err)));
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    fetchData();

    return () => {
      cancelled = true;
    };
  }, [userId]);

  // Note: Modern alternative using AbortController
  // const controller = new AbortController();
  // fetch(url, { signal: controller.signal })
  // return () => controller.abort();

  return { user, loading, error };
}

// Usage
function Profile({ userId }: { userId: string }) {
  const { user, loading, error } = useUser(userId);
  const { theme } = useTheme();
  const { permissions } = usePermissions(user?.id);

  if (loading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;
  if (!user) return null;

  return (
    <div className={theme}>
      <UserCard user={user} permissions={permissions} />
    </div>
  );
}

The difference is substantial. No wrapper nesting, clear data flow, and excellent TypeScript inference. Each hook’s return type flows through automatically.

Three details in useUser carry most of the correctness. The three setters at the top of the effect clear the previous result, so the old user disappears as soon as the effect runs instead of staying on screen with loading set to false until the next response. React still renders once with the old user before the effect runs. To skip even that render, give the component key={userId} so React remounts it with fresh state. The res.ok check turns a 404 or 500 into an error; without it, the error body would land in user. The cancelled flag drops responses that arrive after userId has moved on.

A hand-written hook like this is fine for showing the pattern. For production data fetching, React’s useEffect documentation recommends the framework’s built-in data fetching when there is one, and otherwise a client-side cache such as TanStack Query or SWR, which add caching and request deduplication on top of the same idea.

Composing Complex Logic#

Hooks compose naturally. Here’s a realistic example from working with form state management:

function useForm<T extends Record<string, unknown>>(initialValues: T) {
  const [values, setValues] = useState<T>(initialValues);
  const [errors, setErrors] = useState<Partial<Record<keyof T, string>>>({});
  const [touched, setTouched] = useState<Partial<Record<keyof T, boolean>>>({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Functional updates keep this callback stable: no dependency on errors
  const handleChange = useCallback(<K extends keyof T>(field: K, value: T[K]) => {
    setValues(prev => ({ ...prev, [field]: value }));
    // Clear the field's error when the user edits it
    setErrors(prev => {
      if (!(field in prev)) return prev;
      const next = { ...prev };
      delete next[field];
      return next;
    });
  }, []);

  const handleBlur = useCallback((field: keyof T) => {
    setTouched(prev => ({ ...prev, [field]: true }));
  }, []);

  const setError = useCallback((field: keyof T, error: string) => {
    setErrors(prev => ({ ...prev, [field]: error }));
  }, []);

  const reset = useCallback(() => {
    setValues(initialValues);
    setErrors({});
    setTouched({});
    setIsSubmitting(false);
  }, [initialValues]);

  return {
    values,
    errors,
    touched,
    isSubmitting,
    setIsSubmitting,
    handleChange,
    handleBlur,
    setError,
    setErrors,
    reset
  };
}

// Compose with validation hook (Zod 4)
function useValidatedForm<T extends Record<string, unknown>>(
  initialValues: T,
  validationSchema: z.ZodType<T>
) {
  const form = useForm(initialValues);
  // Depend on the pieces validate reads, not on the whole form object,
  // which is a new object on every render
  const { values, setErrors } = form;

  const validate = useCallback(async () => {
    const result = await validationSchema.safeParseAsync(values);
    if (result.success) {
      setErrors({});
      return true;
    }
    // Replace all errors so fields that are now valid lose their old message
    const next: Partial<Record<keyof T, string>> = {};
    for (const issue of result.error.issues) {
      const field = issue.path[0] as keyof T | undefined;
      if (field !== undefined && next[field] === undefined) {
        next[field] = issue.message;
      }
    }
    setErrors(next);
    return false;
  }, [values, setErrors, validationSchema]);

  return { ...form, validate };
}

// Usage
function RegistrationForm() {
  const form = useValidatedForm(
    { email: '', password: '' },
    registrationSchema
  );

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();

    if (!await form.validate()) return;

    form.setIsSubmitting(true);
    try {
      await registerUser(form.values);
    } finally {
      form.setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={form.values.email}
        onChange={(e) => form.handleChange('email', e.target.value)}
        onBlur={() => form.handleBlur('email')}
      />
      {form.touched.email && form.errors.email && (
        <span className="error">{form.errors.email}</span>
      )}
      {/* ... */}
    </form>
  );
}

This pattern works because hooks compose through function composition. Each hook returns values that other hooks can consume. No inheritance hierarchies, no wrapper components.

Composition has one trap: the object a hook returns is new on every render. Listing form as a dependency would recreate validate on every render, so useValidatedForm depends on values and the stable setErrors setter instead. The validation reads error.issues, the Zod 4 name; the .errors alias from Zod 3 is gone. Each failed run replaces the whole error map, so a field the user has fixed loses its old message.

Rules and Constraints#

React’s Rules of Hooks are two rules, and the rules-of-hooks check in eslint-plugin-react-hooks enforces both:

  1. Only call hooks at the top level: No hooks in conditionals, loops, or nested functions
  2. Only call hooks from React functions: Functional components or other hooks

A separate lint rule in the same plugin, exhaustive-deps, checks that the dependency arrays of useEffect, useCallback and useMemo list every value the callback reads. Missing a dependency does not break React’s hook bookkeeping. It produces a stale closure: the callback keeps using values from an older render. Treat both as errors, since the first corrupts state and the second hides logic bugs.

React Compiler 1.0 (October 2025) memoizes components and hooks at build time. For new code, the React team recommends relying on the compiler and keeping useMemo and useCallback as escape hatches for precise control, such as a value used as an effect dependency. For existing code, they recommend leaving manual memoization in place or testing carefully before removing it. The dependency discipline above still matters wherever a hand-written useCallback remains.

The two Rules of Hooks enable React to preserve hook state across re-renders. The implementation relies on call order:

// React internally maintains an array of hook values
// First render:
const [name, setName] = useState('');  // hooks[0]
const [age, setAge] = useState(0);  // hooks[1]
const [email, setEmail] = useState('');  // hooks[2]

// Second render - same order required:
const [name, setName] = useState('');  // hooks[0] - same position
const [age, setAge] = useState(0);  // hooks[1] - same position
const [email, setEmail] = useState('');  // hooks[2] - same position

// Breaking the rules causes state corruption:
if (showAge) {
  const [age, setAge] = useState(0);  // Conditional hook - order changes!
}

The rules feel restrictive initially but enable powerful composition patterns.

Compound Components: Flexible APIs Through Context#

The Problem: Props Explosion#

Building reusable components often leads to props explosion. Consider a Select component:

// Props explosion - hard to extend
interface SelectProps {
  options: Array<{ value: string; label: string; disabled?: boolean }>;
  value: string | null;
  onChange: (value: string) => void;
  placeholder?: string;
  disabled?: boolean;
  searchable?: boolean;
  clearable?: boolean;
  renderOption?: (option: Option) => ReactNode;
  renderValue?: (value: string) => ReactNode;
  filterOptions?: (options: Option[], search: string) => Option[];
  onOpen?: () => void;
  onClose?: () => void;
  // ... 20 more props
}

<Select
  options={options}
  value={selected}
  onChange={setSelected}
  searchable
  clearable
  renderOption={(opt) => <CustomOption {...opt} />}
/>

Every new feature adds props. The component API becomes unwieldy.

Compound Components Pattern#

Compound components distribute props across multiple components that share implicit state:

// Context holds shared state
interface SelectContextValue {
  value: string | null;
  onChange: (value: string) => void;
  isOpen: boolean;
  setIsOpen: (open: boolean) => void;
}

const SelectContext = createContext<SelectContextValue | null>(null);

function useSelectContext() {
  const context = useContext(SelectContext);
  if (!context) {
    throw new Error('Select.* components must be used within <Select>');
  }
  return context;
}

// Root component manages state
interface SelectProps {
  value: string | null;
  onChange: (value: string) => void;
  children: ReactNode;
}

function Select({ value, onChange, children }: SelectProps) {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <SelectContext.Provider value={{ value, onChange, isOpen, setIsOpen }}>
      <div className="select-container">
        {children}
      </div>
    </SelectContext.Provider>
  );
}

// Sub-components access context
function SelectTrigger({ children }: { children: ReactNode }) {
  const { isOpen, setIsOpen, value } = useSelectContext();

  return (
    <button
      className="select-trigger"
      onClick={() => setIsOpen(!isOpen)}
    >
      {children || value || 'Select...'}
    </button>
  );
}

function SelectOptions({ children }: { children: ReactNode }) {
  const { isOpen } = useSelectContext();

  if (!isOpen) return null;

  return (
    <div className="select-options">
      {children}
    </div>
  );
}

interface SelectOptionProps {
  value: string;
  children: ReactNode;
}

function SelectOption({ value, children }: SelectOptionProps) {
  const { value: selectedValue, onChange, setIsOpen } = useSelectContext();

  return (
    <div
      className={selectedValue === value ? 'selected' : ''}
      onClick={() => {
        onChange(value);
        setIsOpen(false);
      }}
    >
      {children}
    </div>
  );
}

// Namespace sub-components
Select.Trigger = SelectTrigger;
Select.Options = SelectOptions;
Select.Option = SelectOption;

// Flexible usage
<Select value={selected} onChange={setSelected}>
  <Select.Trigger>
    <span>Choose a framework</span>
  </Select.Trigger>
  <Select.Options>
    <Select.Option value="react">React</Select.Option>
    <Select.Option value="vue">Vue</Select.Option>
    <Select.Option value="svelte">Svelte</Select.Option>
  </Select.Options>
</Select>

// Or customize rendering
<Select value={selected} onChange={setSelected}>
  <Select.Trigger>
    {selected ? (
      <div className="custom-display">
        <Icon name={selected} />
        <span>{selected}</span>
      </div>
    ) : (
      <span>Pick one</span>
    )}
  </Select.Trigger>
  <Select.Options>
    {frameworks.map(fw => (
      <Select.Option key={fw.id} value={fw.id}>
        <div className="custom-option">
          <Icon name={fw.icon} />
          <div>
            <div className="name">{fw.name}</div>
            <div className="description">{fw.description}</div>
          </div>
        </div>
      </Select.Option>
    ))}
  </Select.Options>
</Select>

The compound pattern provides flexibility without props explosion. Consumers control rendering while the library manages state and behavior.

Real-World Examples#

This pattern appears throughout the React ecosystem:

Radix UI uses compound components extensively:

<Tabs.Root value={tab} onValueChange={setTab}>
  <Tabs.List>
    <Tabs.Trigger value="account">Account</Tabs.Trigger>
    <Tabs.Trigger value="password">Password</Tabs.Trigger>
  </Tabs.List>
  <Tabs.Content value="account">
    <AccountSettings />
  </Tabs.Content>
  <Tabs.Content value="password">
    <PasswordSettings />
  </Tabs.Content>
</Tabs.Root>

Headless UI follows the same pattern for accessible components:

<Disclosure>
  <Disclosure.Button>
    What is your refund policy?
  </Disclosure.Button>
  <Disclosure.Panel>
    Refunds are available within 30 days.
  </Disclosure.Panel>
</Disclosure>

The pattern works well for component libraries where flexibility matters more than simplicity.

Repository Pattern: Abstracting Data Access#

The Problem: Scattered Data Logic#

Without abstraction, data access scatters throughout the application:

// UserService.ts
async function getUser(id: string) {
  return prisma.user.findUnique({ where: { id } });
}

// OrderService.ts
async function getOrders(userId: string) {
  return prisma.order.findMany({ where: { userId } });
}

// ProductService.ts
async function getProducts() {
  return prisma.product.findMany();
}

This approach has problems:

  1. Switching ORMs requires changes throughout codebase
  2. Testing requires mocking Prisma directly
  3. No clear separation between business logic and data access
  4. Hard to implement caching or logging uniformly

Repository Pattern Implementation#

Repository pattern centralizes data access behind interfaces:

// User carries the password hash; PublicUser is what leaves the service
type PublicUser = Omit<User, 'password'>;

class EmailAlreadyRegisteredError extends Error {
  constructor(email: string) {
    super(`Email already registered: ${email}`);
    this.name = 'EmailAlreadyRegisteredError';
  }
}

// Define interface (abstraction)
// Contract: save() throws EmailAlreadyRegisteredError for a duplicate email,
// and findAll() returns the newest users first
interface UserRepository {
  findById(id: string): Promise<User | null>;
  findByEmail(email: string): Promise<User | null>;
  findAll(options?: FindOptions): Promise<User[]>;
  save(user: User): Promise<User>;
  delete(id: string): Promise<void>;
}

// Prisma implementation
class PrismaUserRepository implements UserRepository {
  constructor(private prisma: PrismaClient) {}

  async findById(id: string): Promise<User | null> {
    return this.prisma.user.findUnique({ where: { id } });
  }

  async findByEmail(email: string): Promise<User | null> {
    return this.prisma.user.findUnique({ where: { email } });
  }

  async findAll(options?: FindOptions): Promise<User[]> {
    return this.prisma.user.findMany({
      skip: options?.offset,
      take: options?.limit,
      orderBy: { createdAt: 'desc' }
    });
  }

  async save(user: User): Promise<User> {
    try {
      return await this.prisma.user.upsert({
        where: { id: user.id },
        create: user,
        update: user
      });
    } catch (e) {
      // P2002: unique constraint failed (here, the @unique email column)
      if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') {
        throw new EmailAlreadyRegisteredError(user.email);
      }
      throw e;
    }
  }

  async delete(id: string): Promise<void> {
    await this.prisma.user.delete({ where: { id } });
  }
}

// In-memory implementation for testing
class InMemoryUserRepository implements UserRepository {
  private users = new Map<string, User>();

  // Return copies so a test cannot mutate stored state through a result
  async findById(id: string): Promise<User | null> {
    const user = this.users.get(id);
    return user ? structuredClone(user) : null;
  }

  async findByEmail(email: string): Promise<User | null> {
    const user = [...this.users.values()].find(u => u.email === email);
    return user ? structuredClone(user) : null;
  }

  async findAll(options?: FindOptions): Promise<User[]> {
    const offset = options?.offset ?? 0;
    const end = options?.limit === undefined ? undefined : offset + options.limit;
    return [...this.users.values()]
      .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
      .slice(offset, end)
      .map(u => structuredClone(u));
  }

  async save(user: User): Promise<User> {
    // Mirror the database's unique index on email
    const taken = [...this.users.values()]
      .some(u => u.email === user.email && u.id !== user.id);
    if (taken) {
      throw new EmailAlreadyRegisteredError(user.email);
    }
    this.users.set(user.id, structuredClone(user));
    return structuredClone(user);
  }

  async delete(id: string): Promise<void> {
    this.users.delete(id);
  }
}

function toPublicUser({ password: _password, ...rest }: User): PublicUser {
  return rest;
}

// Business logic depends on interface, not implementation
class UserService {
  constructor(private userRepository: UserRepository) {}

  async registerUser(email: string, password: string): Promise<PublicUser> {
    // No findByEmail pre-check: two concurrent requests would both pass it.
    // The unique constraint behind save() is the check that holds.
    const user = await this.userRepository.save({
      id: uuid(),
      email,
      password: await hashPassword(password),
      createdAt: new Date()
    });
    return toPublicUser(user);
  }

  async getUser(id: string): Promise<PublicUser> {
    const user = await this.userRepository.findById(id);
    if (!user) {
      throw new Error('User not found');
    }
    return toPublicUser(user);
  }
}

// Production - use Prisma
const userRepository = new PrismaUserRepository(prisma);
const userService = new UserService(userRepository);

// Testing - use in-memory
const testRepository = new InMemoryUserRepository();
const testService = new UserService(testRepository);

A fake only buys testability while it behaves like production. Prisma ORM 7 reports a duplicate value on a @unique column as a PrismaClientKnownRequestError with code P2002. The Prisma repository translates that into EmailAlreadyRegisteredError, and the in-memory fake throws the same error on its own. Without that, a test of duplicate registration passes against the fake and fails in production. Sorting by createdAt and returning copies close two more gaps: the order of findAll results, and tests that mutate a returned object and silently change the stored one.

Keeping the Fake Honest With a Contract Test#

The reliable way to keep both implementations aligned is to run one test suite against each of them. The suite encodes the interface’s contract once:

function makeUser(overrides: Partial<User> = {}): User {
  return {
    id: uuid(),
    email: `${uuid()}@example.com`,
    password: 'hash',
    createdAt: new Date(),
    ...overrides
  };
}

function userRepositoryContract(
  name: string,
  makeRepository: () => Promise<UserRepository>
) {
  describe(name, () => {
    it('rejects a second user with the same email', async () => {
      const repo = await makeRepository();
      await repo.save(makeUser({ email: 'a@example.com' }));
      await expect(repo.save(makeUser({ email: 'a@example.com' })))
        .rejects.toBeInstanceOf(EmailAlreadyRegisteredError);
    });

    it('returns users newest first', async () => {
      const repo = await makeRepository();
      const older = await repo.save(makeUser({ createdAt: new Date('2024-01-01') }));
      const newer = await repo.save(makeUser({ createdAt: new Date('2024-02-01') }));
      const ids = (await repo.findAll()).map(u => u.id);
      expect(ids).toEqual([newer.id, older.id]);
    });
  });
}

userRepositoryContract('InMemoryUserRepository', async () => new InMemoryUserRepository());
// testPrismaClient() is a project helper that returns a client on a test database with the users table emptied
userRepositoryContract('PrismaUserRepository', async () => new PrismaUserRepository(await testPrismaClient()));

The Prisma run is slower and needs a real database, so it can live in a separate CI job. When it fails and the in-memory run passes, the fake has drifted, and every unit test built on it is suspect until the fake is fixed.

Benefits and Trade-offs#

Benefits:

  1. Testability: Swap implementations without mocking ORM internals
  2. Flexibility: Switch from Prisma to TypeORM by implementing interface
  3. Centralized logic: Query patterns, caching, logging in one place
  4. Clear boundaries: Business logic doesn’t know about database details

Trade-offs:

  1. More code: Each entity needs repository interface and implementation
  2. Learning curve: Team must understand repository pattern
  3. Abstraction cost: Can’t access ORM-specific features easily
  4. Over-engineering risk: Simple CRUD apps might not need this

Working with teams on data-heavy applications taught me the repository pattern pays off when:

  • Multiple data sources (Postgres + Redis + S3)
  • Complex querying logic that shouldn’t live in services
  • High test coverage requirements
  • Potential ORM migration in the future

For simple applications with straightforward data access, direct ORM usage is often cleaner.

Provider Pattern: Context-Based Dependency Injection#

The Classic Problem: Prop Drilling#

Passing props through multiple component layers gets tedious:

function App() {
  const theme = useTheme();
  const user = useUser();
  const config = useConfig();

  return (
    <Dashboard theme={theme} user={user} config={config} />
  );
}

function Dashboard({ theme, user, config }: DashboardProps) {
  return (
    <Layout theme={theme}>
      <Sidebar user={user} config={config} />
    </Layout>
  );
}

function Sidebar({ user, config }: SidebarProps) {
  return (
    <Navigation user={user} config={config} />
  );
}

function Navigation({ user, config }: NavigationProps) {
  // Finally use the props
  return <div>{user.name} - {config.appName}</div>;
}

Three intermediate components don’t use theme, user, or config - they just pass them down. This creates coupling and makes refactoring painful.

Provider Pattern with Context#

React Context provides values deep in the component tree without prop drilling:

// Create context with type
interface ThemeContextValue {
  theme: 'light' | 'dark';
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextValue | null>(null);

// Custom hook for consuming context
function useTheme() {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within ThemeProvider');
  }
  return context;
}

// Provider component
function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<'light' | 'dark'>('light');

  const toggleTheme = useCallback(() => {
    setTheme(prev => prev === 'light' ? 'dark' : 'light');
  }, []);

  const value = useMemo(
    () => ({ theme, toggleTheme }),
    [theme, toggleTheme]
  );

  return (
    <ThemeContext.Provider value={value}>
      {children}
    </ThemeContext.Provider>
  );
}

// Usage - no prop drilling
function App() {
  return (
    <ThemeProvider>
      <Dashboard />
    </ThemeProvider>
  );
}

function Dashboard() {
  return (
    <Layout>
      <Sidebar />
    </Layout>
  );
}

function Sidebar() {
  return <Navigation />;
}

function Navigation() {
  const { theme, toggleTheme } = useTheme();

  return (
    <div className={theme}>
      <button onClick={toggleTheme}>
        Toggle theme
      </button>
    </div>
  );
}

Components at any depth access theme without intermediate components knowing about it.

Combining Multiple Providers#

Real applications have multiple contexts:

function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <ConfigProvider>
          <I18nProvider>
            <Router />
          </I18nProvider>
        </ConfigProvider>
      </AuthProvider>
    </ThemeProvider>
  );
}

This nesting works but gets verbose. A common pattern combines providers:

interface AppProvidersProps {
  children: ReactNode;
}

const providers = [
  ThemeProvider,
  AuthProvider,
  ConfigProvider,
  I18nProvider
];

function AppProviders({ children }: AppProvidersProps) {
  return providers.reduceRight(
    (acc, Provider) => <Provider>{acc}</Provider>,
    children
  );
}

// Cleaner usage
function App() {
  return (
    <AppProviders>
      <Router />
    </AppProviders>
  );
}

Performance Considerations#

Context re-renders all consumers when value changes. Optimize with memoization:

function ExpensiveProvider({ children }: { children: ReactNode }) {
  const [state, setState] = useState(initialState);

  // Without memoization - new object every render
  // All consumers re-render even if state unchanged
  const badValue = { state, setState };

  // With memoization - only changes when dependencies change
  const goodValue = useMemo(
    () => ({ state, setState }),
    [state]  // Only recreate when state changes
  );

  return (
    <ExpensiveContext.Provider value={goodValue}>
      {children}
    </ExpensiveContext.Provider>
  );
}

For frequently updating values, split contexts:

// Separate fast-changing and slow-changing values
// null is a real state (logged out), so the types say so
const UserContext = createContext<User | null>(null);
const UserActionsContext = createContext<UserActions | null>(null);

function useUserActions() {
  const actions = useContext(UserActionsContext);
  if (!actions) {
    throw new Error('useUserActions must be used within UserProvider');
  }
  return actions;
}

function UserProvider({ children }: { children: ReactNode }) {
  const [user, setUser] = useState<User | null>(null);

  // Actions rarely change
  const actions = useMemo<UserActions>(
    () => ({
      updateProfile: (data: ProfileData) => {
        setUser(prev => (prev ? { ...prev, ...data } : prev));
      },
      logout: () => setUser(null)
    }),
    []
  );

  return (
    <UserContext.Provider value={user}>
      <UserActionsContext.Provider value={actions}>
        {children}
      </UserActionsContext.Provider>
    </UserContext.Provider>
  );
}

// Components consuming only actions don't re-render when user changes
function LogoutButton() {
  const { logout } = useUserActions();
  // Doesn't re-render when user profile updates
  return <button onClick={logout}>Logout</button>;
}

Module Pattern: ES Modules as Design Pattern#

Pre-ES6: IIFE and Revealing Module#

Before ES modules, JavaScript used IIFEs for encapsulation:

// Old IIFE pattern
const logger = (function() {
  // Private variables
  let logLevel = 'info';
  const levels = ['debug', 'info', 'warn', 'error'];

  // Private function
  function shouldLog(level: string): boolean {
    return levels.indexOf(level) >= levels.indexOf(logLevel);
  }

  // Public API
  return {
    setLogLevel(level: string) {
      logLevel = level;
    },
    log(level: string, message: string) {
      if (shouldLog(level)) {
        console.log(`[${level}] ${message}`);
      }
    }
  };
})();

logger.log('info', 'Application started');
// Can't access logLevel or shouldLog directly

This worked but required boilerplate and lacked static analysis.

Modern: ES Modules#

ES modules provide natural encapsulation:

// logger.ts - private by default
let logLevel: 'debug' | 'info' | 'warn' | 'error' = 'info';
const levels = ['debug', 'info', 'warn', 'error'] as const;

// Private function (not exported)
function shouldLog(level: typeof logLevel): boolean {
  return levels.indexOf(level) >= levels.indexOf(logLevel);
}

// Public API (exported)
export function setLogLevel(level: typeof logLevel) {
  logLevel = level;
}

export function log(level: typeof logLevel, message: string) {
  if (shouldLog(level)) {
    console.log(`[${level}] ${message}`);
  }
}

// Other files
import { log, setLogLevel } from './logger';
log('info', 'Application started');
// Can't access logLevel or shouldLog

Benefits over IIFE:

  1. Static analysis: TypeScript and bundlers understand imports
  2. Tree shaking: Unused exports eliminated at build time
  3. Better tooling: Auto-imports, go-to-definition work correctly
  4. Type safety: TypeScript enforces module boundaries
  5. No boilerplate: No wrapping function needed

Module-Scoped Singletons#

ES modules naturally implement singleton pattern:

// database.ts
class DatabaseConnection {
  private connected = false;

  connect() {
    if (!this.connected) {
      console.log('Connecting to database...');
      this.connected = true;
    }
  }

  query(sql: string) {
    if (!this.connected) {
      throw new Error('Not connected');
    }
    // Execute query
  }
}

// Export single instance
export const db = new DatabaseConnection();

// Other files always get the same instance
import { db } from './database';
db.connect();
db.query('SELECT * FROM users');

Module caching ensures db is the same instance everywhere. This is cleaner than classic singleton pattern with private constructor and static getInstance method.

Module Initialization#

Modules execute once when first imported. Use this for initialization:

// config.ts
interface Config {
  apiUrl: string;
  apiKey: string;
  timeout: number;
}

let config: Config | null = null;

function loadConfig(): Config {
  // Load from environment or file
  return {
    apiUrl: process.env.API_URL || 'http://localhost:3000',
    apiKey: process.env.API_KEY || '',
    timeout: 30000
  };
}

// Initialize on module load
config = loadConfig();

export function getConfig(): Config {
  if (!config) {
    throw new Error('Config not initialized');
  }
  return config;
}

export function reloadConfig(): void {
  config = loadConfig();
}

// First import triggers initialization
import { getConfig } from './config';
const config = getConfig();  // Already loaded

Container/Presenter: Separation Reconsidered#

The Classic Pattern#

Container/Presenter (also called Smart/Dumb or Stateful/Stateless) separates data fetching from presentation:

// Presenter - pure presentation
interface UserCardProps {
  user: User;
  onFollow: () => void;
  onMessage: () => void;
}

function UserCard({ user, onFollow, onMessage }: UserCardProps) {
  return (
    <div className="user-card">
      <img src={user.avatar} alt={user.name} />
      <h3>{user.name}</h3>
      <p>{user.bio}</p>
      <div className="actions">
        <button onClick={onFollow}>Follow</button>
        <button onClick={onMessage}>Message</button>
      </div>
    </div>
  );
}

// Container - data and logic
interface UserCardContainerProps {
  userId: string;
}

function UserCardContainer({ userId }: UserCardContainerProps) {
  const { user, loading, error } = useUser(userId);
  const { followUser } = useFollowUser();
  const { startConversation } = useMessaging();

  if (loading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;
  if (!user) return null;

  return (
    <UserCard
      user={user}
      onFollow={() => followUser(userId)}
      onMessage={() => startConversation(userId)}
    />
  );
}

Benefits of separation:

  1. Testability: UserCard easy to test with mock props
  2. Reusability: UserCard works with any user object
  3. Storybook: Show UserCard in all states without data fetching

Modern Alternative: Co-location#

Hooks enable co-locating data and presentation without sacrifice:

function UserCard({ userId }: { userId: string }) {
  const { user, loading, error } = useUser(userId);
  const { followUser } = useFollowUser();
  const { startConversation } = useMessaging();

  if (loading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;
  if (!user) return null;

  return (
    <div className="user-card">
      <img src={user.avatar} alt={user.name} />
      <h3>{user.name}</h3>
      <p>{user.bio}</p>
      <div className="actions">
        <button onClick={() => followUser(userId)}>Follow</button>
        <button onClick={() => startConversation(userId)}>Message</button>
      </div>
    </div>
  );
}

Testing remains straightforward by mocking hooks:

// Mock hooks for testing
jest.mock('./hooks/useUser', () => ({
  useUser: () => ({
    user: mockUser,
    loading: false,
    error: null
  })
}));

// Test UserCard directly
render(<UserCard userId="123" />);
expect(screen.getByText(mockUser.name)).toBeInTheDocument();

Storybook works by mocking hooks at story level:

// UserCard.stories.tsx
export const Default: Story = {
  decorators: [
    (Story) => {
      // Mock hooks for Storybook
      jest.spyOn(require('./hooks/useUser'), 'useUser')
        .mockReturnValue({
          user: mockUser,
          loading: false,
          error: null
        });

      return <Story />;
    }
  ]
};

When Container/Presenter Still Makes Sense#

Strict separation remains valuable when:

  1. Presentation components shared across apps: Design system components
  2. Server-side rendering: Different data fetching patterns per platform
  3. Complex prop interfaces: Clear contract between data and display
  4. Team boundaries: Different teams own data vs UI

For most application code, co-location with hooks provides better developer experience without losing testability.

Render Props: Advanced Control Pattern#

When Hooks Aren’t Enough#

Hooks work for most scenarios but fail when consumers need rendering control:

// Hook approach - consumer can't control loading UI
function useData<T>(url: string) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch(url)
      .then(r => r.json())
      .then(setData)
      .finally(() => setLoading(false));
  }, [url]);

  if (loading) return <DefaultSpinner />;  // Fixed loading UI
  return data;  // Consumer can't customize
}

Render Props Pattern#

Pass rendering control to consumers:

interface DataFetcherProps<T> {
  url: string;
  children: (state: {
    data: T | null;
    loading: boolean;
    error: Error | null;
    refetch: () => void;
  }) => ReactNode;
}

function DataFetcher<T>({ url, children }: DataFetcherProps<T>) {
  const [data, setData] = useState<T | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const fetchData = useCallback(() => {
    setLoading(true);
    setError(null);

    fetch(url)
      .then(r => {
        if (!r.ok) throw new Error(`GET ${url} failed with ${r.status}`);
        return r.json();
      })
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, [url]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return <>{children({ data, loading, error, refetch: fetchData })}</>;
}

// Flexible usage - consumer controls everything
<DataFetcher<User> url="/api/user">
  {({ data, loading, error, refetch }) => (
    <div>
      {loading && <CustomSpinner message="Loading user..." />}
      {error && (
        <div className="error">
          <p>{error.message}</p>
          <button onClick={refetch}>Retry</button>
        </div>
      )}
      {data && (
        <div>
          <h1>{data.name}</h1>
          <button onClick={refetch}>Refresh</button>
        </div>
      )}
    </div>
  )}
</DataFetcher>

// Different consumer, different rendering
<DataFetcher<Product[]> url="/api/products">
  {({ data, loading }) => (
    loading ? <SkeletonGrid /> : <ProductGrid products={data!} />
  )}
</DataFetcher>

Render Props vs Hooks#

Use hooks when:

  • Consumers just need data
  • Rendering is consistent across uses
  • Logic composition matters more than rendering control

Use render props when:

  • Consumers need full rendering control
  • Loading/error states vary significantly
  • Component manages complex UI state (modals, dropdowns)

Real example from React Router:

// Render prop gives access to router state
<Route path="/users/:id">
  {({ match }) => (
    match ? (
      <UserProfile userId={match.params.id} />
    ) : (
      <UserList />
    )
  )}
</Route>

React Router v6 switched to hooks (useParams, useNavigate) for most use cases, but render props remain for advanced scenarios.

Series Wrap-Up: Patterns Past and Present#

We’ve covered four posts exploring design patterns from 1994 to 2025:

Post 1: Creational Patterns showed how ES modules, object spread, and TypeScript’s type system replaced most creational patterns. Singleton became module exports, prototype became spread operators, factory became discriminated unions. Builder pattern remains valuable for complex configurations.

Post 2: Structural Patterns examined how React’s composition model absorbed structural patterns. HOCs carried the Decorator idea into components and custom hooks took over most HOC use cases, facade simplified complex APIs, composite naturally maps to component trees, adapter isolated external dependencies.

Post 3: Behavioral Patterns explored observer’s evolution into reactive programming. RxJS, Redux, and hooks represent modern observer implementations with better error handling and cancellation. Strategy became functions, command powers undo/redo, state machines prevent invalid states.

Post 4: Modern Patterns cataloged patterns that emerged from JavaScript/TypeScript ecosystems. Hooks solved wrapper hell, compound components provided flexible APIs, repository abstracted data access, modules became natural singletons.

What Changed and Why#

The Gang of Four wrote their 1994 examples in C++ and Smalltalk, and the two languages did not share the same limits. C++ had no closures until lambdas arrived in C++11, so behavior had to travel inside objects, and polymorphism ran through class hierarchies. Smalltalk already had closures: a block is a function value, and passing one to do: replaces an iterator class with a single line.

Peter Norvig’s 1996 talk “Design Patterns in Dynamic Languages” measured that gap. His study of the book found that “16 of 23 patterns have qualitatively simpler implementation in Lisp or Dylan than in C++ for at least some uses of each pattern”. He traced the difference to first-class types, first-class functions, macros, method combination, multimethods and modules. Much of the catalog works around C++ constraints that languages with closures and first-class types do not share.

Modern JavaScript and TypeScript bring those features to everyday front-end and Node work:

  • First-class functions and closures
  • Sophisticated type inference
  • ES modules with tree shaking
  • Async/await and Promises
  • Component composition (React/Vue/Svelte)
  • Reactive programming primitives

Different constraints produce different patterns; the problems stayed, the implementations changed.

Pattern Selection Framework#

Before reaching for a pattern:

  1. Name the problem: If it doesn’t fit in one sentence, the pattern is decoration.
  2. Check the language: Discriminated unions often remove the need for a factory, and ES modules cover most creational patterns.
  3. Check the framework: Hooks cover stateful logic sharing, and composition covers most structural work.
  4. Weigh the indirection: It earns its place by buying testability or a clearer boundary.
  5. Check the team: A pattern nobody else reads fluently turns into maintenance cost.

Looking Forward#

Patterns will continue evolving as languages and frameworks change:

React Server Components introduce new patterns for server/client composition. The boundary between server and client code creates new abstraction challenges. With React 19 (December 2024), RSC became stable and production-ready, bringing server-first patterns to mainstream development.

Signals and fine-grained reactivity (SolidJS, Vue 3, Preact Signals) track which values each piece of UI reads and update only what depends on a changed value, a different model from React’s component re-rendering. They narrow the scope of a render and can coexist with a virtual DOM. Vue 3 still renders through its compiler-informed virtual DOM. In Preact, a component that reads signal.value re-renders as usual, while a signal passed straight into JSX text updates in place without diffing.

Type-level programming in TypeScript enables encoding constraints at compile time that previously required runtime patterns.

Edge computing and distributed systems introduce patterns for dealing with network boundaries, caching, and eventual consistency.

When the Default Holds#

Reaching for a language or framework feature first works for application code, where the framework already owns state, composition, and data flow. Two cases override it. Library and design-system code needs an explicit contract, so compound components and render props earn their indirection even when a hook would be shorter. Long-lived domain code with several data sources needs the repository boundary in place before the second source arrives.

Patterns are a vocabulary for discussing design, not a prescription for implementing it. A useful next step is auditing one module you own: for every abstraction in it, name the problem that abstraction removes. Anything you cannot name is a candidate for deletion.

References#

Modern Perspective on Classic Design Patterns

Part 4 of 4

A comprehensive series examining how classic Gang of Four design patterns have evolved in modern TypeScript, React, and functional programming contexts. Learn when classic patterns still apply, when they've been superseded, and how to recognize underlying principles in modern codebases.

Related posts