Sub topic 3
Render props
This chapter assumes you can write function components, use useState and useEffect, and pass functions as props. A render prop is a prop whose value is a function that returns React elements. The component calls that function instead of deciding by itself what to draw. The component owns the logic, and the caller owns the output.
The core idea
Suppose several screens need an on/off state, but each draws it differently. One shows a button, another a checkbox, another a banner. Copying the useState call everywhere duplicates logic. A render prop lets one component hold the state and let each caller supply the markup.
import { useState } from 'react';
function Toggle({ children }) {
const [on, setOn] = useState(false);
return children({ on, toggle: () => setOn((prev) => !prev) });
}
export function App() {
return (
<Toggle>
{({ on, toggle }) => (
<button onClick={toggle}>{on ? 'On' : 'Off'}</button>
)}
</Toggle>
);
}Toggle does not render a DOM element of its own. It calls children as a function and returns the result. JSX places the function between the opening and closing tags, so it arrives as props.children. This form is called "function as children".
Children or a named prop
The function does not have to be children. A named prop, conventionally render, works the same way and can be clearer when a component accepts more than one function.
import { useEffect, useState } from 'react';
export function MouseTracker({ render }) {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
function handleMove(event) {
setPosition({ x: event.clientX, y: event.clientY });
}
window.addEventListener('mousemove', handleMove);
return () => window.removeEventListener('mousemove', handleMove);
}, []);
return render(position);
}
export function Cursor() {
return (
<MouseTracker
render={({ x, y }) => (
<p>
Pointer at {x}, {y}
</p>
)}
/>
);
}The effect adds a listener once and removes it on unmount. Every caller of MouseTracker gets this cleanup without writing it.
| Form | Example | Best when |
|---|---|---|
| Function as children | `<Toggle>{(api) => ...}</Toggle>` | There is one function and it describes the main output |
| Named prop | `<MouseTracker render={(api) => ...} />` | There are several functions, or the name documents intent |
What you pass to the function
The arguments are the contract of the component. Pass only what the caller needs: state values, event handlers, and derived data. A single object argument is easier to evolve than positional arguments, because you can add fields without breaking existing callers. Destructuring in the parameter list, as in ({ on, toggle }), lets each caller take only what it uses.
Common errors
Rendering a non-function
If a caller writes <Toggle><button /></Toggle>, children is an element, and children(...) throws "children is not a function". Fail early with a clearer message.
import { useState } from 'react';
export function SafeToggle({ children }) {
const [on, setOn] = useState(false);
if (typeof children !== 'function') {
throw new Error('SafeToggle expects a function as its child');
}
return children({ on, toggle: () => setOn((prev) => !prev) });
}Defeating memoization with inline functions
An inline arrow function is a new object on every render of the caller. If the render-prop component is wrapped in React.memo, the changed prop makes the memo useless, because the shallow comparison always sees a different function. Two fixes exist. Define the function outside the component when it needs no closure values, or wrap it in useCallback when it does. Do this only after measuring a real cost, since inline functions are cheap in most screens.
Calling hooks inside the render function
The function you pass is called during Toggle's render. It is not a component. A hook called inside it therefore becomes part of Toggle's hook list, and adding or removing that hook changes the order of hooks for Toggle. React then reports a hook-order error or mixes up state. If the output needs its own state, move it into a real component and render that component from the function.
Forgetting keys when mapping
A render prop can return a list. As with any list, each element needs a stable key. The function returning an array without keys produces the usual warning.
Wrapper nesting
Combining several render-prop components nests the functions one inside another.
<MouseTracker render={(pos) => (
<Toggle>
{(toggle) => <Panel position={pos} toggle={toggle} />}
</Toggle>
)} />Each additional source of logic adds a level of indentation. This is the strongest reason teams moved to hooks.
Render props versus custom hooks
Most logic that used to need a render prop is now a custom hook. The same toggle becomes a function that returns state, with no extra component in the tree.
import { useState } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
return { on, toggle: () => setOn((prev) => !prev) };
}
export function HookApp() {
const { on, toggle } = useToggle();
return <button onClick={toggle}>{on ? 'On' : 'Off'}</button>;
}| Concern | Render prop | Custom hook |
|---|---|---|
| Extra component in the tree | Yes | No |
| Combining several sources | Nested functions | Several hook calls in sequence |
| Works in class components | Yes | No |
| Component can control where its children render | Yes | No, the hook returns data only |
| Hidden hook-order risk | Yes, if hooks run inside the function | Governed by the rules of hooks |
Render props still make sense when the component must render something around the output, such as a wrapper div, a portal, a virtualized list that decides which rows exist, or a context provider whose children depend on its state. The component stays in control of structure and the caller controls the content of each part. Libraries that expose row renderers and cell renderers use this approach.
Edge cases to remember
- A render function that returns
undefinedis an error in React for a component's return value. Returnnullwhen there is nothing to show. - Passing the same function reference each render avoids unnecessary updates in memoized children. A new reference is only a problem if something compares by identity.
- Document the argument object. Callers cannot discover its fields from the JSX alone, so use TypeScript types or a comment.
Exercise
A teammate wraps MouseTracker in React.memo, but it still re-renders every time the parent renders, and the parent passes render={({ x, y }) => <p>{x}, {y}</p>} inline. Why does the memo not help, and how would you fix it?
Show answer
The inline arrow function is created again on every parent render, so the render prop is a new reference each time. React.memo compares props shallowly and sees a change. Move the function to module scope, since it uses no closure values, and pass that stable reference. If the function needed values from the parent, wrap it in useCallback with those values as dependencies.
Exercise
Write a Counter component that uses a function as children and passes { count, increment, decrement } to it. Then say what happens if a caller passes plain text as the child.
Show answer
Use function Counter({ children }) { const [count, setCount] = useState(0); return children({ count, increment: () => setCount((c) => c + 1), decrement: () => setCount((c) => c - 1) }); }. If a caller passes plain text, children is a string, and calling it throws "children is not a function". Add a typeof children !== 'function' check that throws a clearer message.