DEV Community

Cover image for Using react-adopt to solve “render props callback hell” in React NextJS GraphQL App
Nabendu
Nabendu

Posted on • Edited on • Originally published at nabendu.blog

Using react-adopt to solve “render props callback hell” in React NextJS GraphQL App

I am building a demo Indian Restaurant Billing App , after completing Advanced React course by Wes Bos.

In my first article i changed the menu to hamburger menu from the normal menu.
In the second article i had given details to upload images through cloudinary.
In the third, we learnt to send transactional email using gmail.

In the app, we are using Apollo Client in the frontend, to get data from the Prisma database. So, we are using Mutation and Query components. In one of the component, we faced the deadly “Render prop callback hell”, with three level of callback.

You can find the starting code for Bill.js here.

The three level of render propsThe three level of render props

Here User is a generic Query component.

User componentUser component

To solve this problem, we use a third-party tool known as react-adopt.

So, let’s npm install react-adopt and use it in our component. Here, we will create a Composed component and use the adopt.

In it we write the three different keys in our Object and the value will be equal to the Mutation/Query we are going to replace.

ComposedComposed

We will now see the benefit of react-adopt. First we will replace the User component with the Compose component and also change the top level render prop to use all the keys from adopt.

Replacing User componentReplacing User component

Now, time to delete the toggle cart Mutation. Go ahead and delete both starting and ending of it.

Mutation deletedMutation deleted

Next, it’s time to delete the Query component.

Query component deletedQuery component deleted

Now, if we go back to our frontend and check we will find everything works fine. But if we open the console, we will find three warnings.

Warning spoilerWarning spoiler

To fix it we have to make child component in Composed component for every value.

Our updated ComposedOur updated Composed

This will solve our warning problem and we get a minimal and readable code, with upper level render-prop.

You can find the updated code for Bill.js here.

Top comments (0)