Complexity level: Intermediate
In the previous post we covered the props combination pattern where we looked at the different ways to group props to what made more sense and what are the pros and cons of passing a function down as a prop and how we can memorise the value using useMemo. Next up, we will be looking into the render props pattern and how we can use this pattern to make our components share the same logic without sharing the same UI.
What is the render props pattern?
Render props is a common pattern you will see in popular NPM packages like Formik or React Final form and it is very useful for building components that manage the logic and pass information to their children/prop so they can use that logic in the UI layer.
With children
You can use the render props via react default prop children.
<HelloWorld>{({ hello }) => <p>{hello}</p>}</HelloWorld>;Under the hood of our HelloWorld component this look like children({ hello: 'world' }) instead of seeing children be rendered as standard {children} .
const HelloWorld = ({ children }) => children({ hello: 'world' });You look at this and think why? Well children can either be a function of some JSX and we just handle it however.
With props
You can do the same thing with a custom prop. You can see this in libraries like formik where their Field component can take a render prop or render children.
<HelloWorld render={({ hello }) => <p>{hello}</p>} />;and under the hood that would look like:
const HelloWorld = ({ render }) => render({ hello: 'world' });Personally I prefer doing it the children way instead of this but it’s always good to have alternatives.
Why is this still relevant now since hooks are a thing?
Hooks do not work in React class components. Yes, sadly they do exist. React has been out now for around 5–6 years and there will be legacy apps that still use class components.
This approach is a good way to make an abstraction from that class component and pass props down into the class for it to behave how it’s meant to behave without impacting your new code.
Originally published on Medium.