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

The Children-as-Function Pattern

Understanding how passing a function as children enables flexible component composition and data sharing.

The Children-as-Function Pattern

What you'll learn: How passing a function as children creates a special, flexible type of render prop.

The Core Idea

You've seen render props passed as named props like render={...}. But there's a powerful variant: passing a function as the children prop itself. Instead of writing <Component render={data => <div>{data}</div>} />, you write:

<Component>
  {data => <div>{data}</div>}
</Component>

This works because children is just another prop. When you place a function between JSX tags, React passes it as props.children, and your component can invoke it.

Why It Feels Natural

The children-as-function pattern reads more like native JSX. Compare:

// Named render prop
<MouseTracker render={position => <p>X: {position.x}</p>} />

// Children-as-function
<MouseTracker>
  {position => <p>X: {position.x}</p>}
</MouseTracker>

The second form looks cleaner and more component-like. You're "wrapping" content with behavior, similar to how you'd wrap JSX in a <div>.

How to Implement It

Inside your component, check if children is a function, then call it with your shared data:

function DataProvider({ children }) {
  const [data, setData] = useState('Hello');
  
  return typeof children === 'function' 
    ? children(data) 
    : children;
}

Now consumers use it naturally:

<DataProvider>
  {data => <h1>{data}</h1>}
</DataProvider>

Key Takeaway: The children-as-function pattern is render props with a nicer syntax—it makes data-sharing components feel more like native wrappers while keeping all the flexibility of passing behavior through props.