Course contentsShow
← React
Lesson 1061 of 2,39627. Composition: Render PropsFree lesson

Real-World Examples: Data Providers and Toggles

Examining common use cases like mouse position trackers, toggle components, and data fetchers.

Real-World Examples: Data Providers and Toggles

You'll learn: How render props solve common real-world problems like fetching data and managing toggle state across your application.

The Core Idea

Render props shine in practical scenarios where you need to share stateful logic but give consumers full control over rendering. Two of the most common patterns are data providers (components that fetch and manage data) and toggles (components that manage open/closed state).

Data Provider Pattern

Imagine a <DataFetcher> component that handles loading, errors, and success states internally, but lets you decide what to render:

<DataFetcher url="/api/users">
  {({ data, loading, error }) => {
    if (loading) return <Spinner />;
    if (error) return <ErrorMessage error={error} />;
    return <UserList users={data} />;
  }}
</DataFetcher>

The component owns the logic (fetching, state management), but you control the presentation. Different parts of your app can use the same fetcher with completely different UIs.

Toggle Pattern

A <Toggle> component manages boolean state (like a dropdown or modal) and shares it via render props:

<Toggle>
  {({ on, toggle }) => (
    <div>
      <button onClick={toggle}>
        {on ? 'Hide' : 'Show'} Details
      </button>
      {on && <DetailsPanel />}
    </div>
  )}
</Toggle>

The toggle logic is reusable, but each consumer decides what "toggled on" looks like—a dropdown, modal, accordion, or anything else.

Why This Matters

These patterns extract behavior (fetching, toggling) without dictating appearance. It's like having a smart assistant who does the work but lets you make all the decisions about presentation.

Key Takeaway: Data providers and toggles are classic render prop use cases that separate stateful logic from UI concerns, enabling flexible reuse across different visual contexts.