Before diving into what Render Props Pattern is, understanding whatProps in React is crucial.
Props (short for properties) are a way to pass data from a parent component to a child component. It is a means by which the parent communicates and controls the child component.
For example:
function Greeting(props) {
return <h1>Hello, {props.name}</h1>
}
The <Greeting /> component is asking the name in order to display which can be passed like this:
<Greeting name="Raj" />
The output will be:
Hello, Raj
Here, name="Raj" is a prop. The Greeting component receives it through props.name
Props make components reusable. For example:
<Greeting name="Raj" />
<Greeting name="John" />
From the example, you can see the same component is used multiple times but it receives different data.
Render Props Pattern
Render props are a React pattern where a component receives a function as a prop, and calls that function to decide what UI to render.
Think of it like this
“I will handle the logic/state. You tell me what to display.”
The idea 💡
Instead of this
<User />
You do this:
<User render={(user) => <p>Hello, {user.name}</p>} />
What happens now is the User component owns the data, but the parent controls the UI.
Simple example ⬇️
const Toggle = ({ render }) => {
const [isOpen, setIsOpen] = useState(false);
const toggleState = () => {
setIsOpen((prev) => !prev);
};
return <>{render({ isOpen, toggle })}</>;
};
export default Toggle;
The above component maintains the logic and the UI is maintained separately in the parent component
Usage
<Toggle
render={({ isOpen, toggle }) => (...)}
/>
Here,
render={({ isOpen, toggle }) => (...)}
is the render prop and the UI stays here.
Use case
Render props are useful when you want to reuse logic but you want different UI using the same logic.
That way, you write less code which is awesome.
Here are the two different UIs built using the render props. Their state can be toggled as well.
I will put the Github link at the end of the article.
children as a render prop
For simplicity, people often use children as a render prop.
Lets take above example. We use children instead of render and below is the example:
const ToggleWithChildren = ({ children }: ToggleProps) => {
const [isOpen, setIsOpen] = useState(false);
const toggleState = () => {
setIsOpen((prev) => !prev);
};
return <>{children({ isOpen, toggle })}</>;
};
export default ToggleWithChildren;
And we can use that as
<ToggleWithChildren>
{({ isOpen, toggle }) => (
....
)}
</ToggleWithChildren>
So this was it for the render props pattern. You can get the code here. Kindly visit this Youtube link for more information.

Comments
Nothing yet. Say the first thing.
Sign in to join the conversation.