In this lesson we look at how to use react-adopt to compose multiple Context Consumers into one reusable component to avoid render prop hell.
Additional Resources: https://github.com/pedronauck/react-adopt
Instructor: [00:00] In this example, I'm using React's new context API to pass a theme as a string and a user as an object. As you can see in my example, the context API provides a render prop, or a child as a function, with the value of assign and create context.
[00:17] Render props are a great pattern, but sometimes, you'll run into a situation like this, where you'll have to nest them, and you can fall into render prop hell. Much like callback hell, it can be difficult to read and determine what's going on.
[00:28] React Adopt is a library that can help solve this issue by allowing you to compose a single component with multiple render props, and use it instead. The first thing I need to do is invoke this adopt function that we've imported.
[00:40] I'm going to create a variable called context, which is going to be a component I can use. This could really be called anything, but I'm going to call it context. We're going to invoke the function, pass it an object. I'm going to say theme and themeContext.consumer and userContext.consumer.
[00:57] The contextConsumer component implements the children as a function pattern, which is pretty much the same thing as a render prop component, but your render function is passed as children instead of a render prop.
[01:13] If you need to compose a render prop that doesn't accept a function as children, you can do something like this instead, but we don't need that for this example. Let's get rid of that. Finally, to use the newly composed render prop component in place of the nested ones.
[01:28] You'll notice how composing components like this flattens things out and makes it more readable. That's it. React Adopt is pretty clean. Check out their docs and see what else it can do.