THE SOLUTION:

Thankfully, there is a better way and that is with the new Context API.

To demonstrate, I am going to make the following component:

Its a simple table that shows a list of classic cars. The user can click on a row, the row will enter an edit mode, changes can be made, and the table can be taken out of edit mode.

This isn’t going to be a super long component tree but it will help demonstrate the Context API. First let’s make the container component.

All of the components that we will be using are in the table.component.js file. Notice that we are importing TableContext from the table component as well.

Now in the render method is where the magic is happening. Notice how we are using the TableContext . The container is now becoming the Provider for this context. The container is providing the properties for all of the sub components in the component tree. We aren’t passing anything into the Table , Header , or Body components. They are going to grab what they need from the context.

Let’s take a look at table.component.js:

At the top:

import { createContext } from 'react';

export const TableContext = createContext();

Now that we’ve created the context, any one of the components can use this context like so:

export const Header = () => (

<TableContext.Consumer>

{({ columns }) => (

<thead>

<tr>

// map the column names

</tr>

</thead>

)}

</TableContext.Consumer>

);

The sub components underneath the context provider become the Consumer of the context. The component can then pull out only the properties it needs from the context.

I won’t go over each of the components as that isn’t the focus here. But if you look over each of the components in table.component.js , you can see that each component is accessing only the props that it is immediately interested in. Also, changing the hierarchy of these components would not cause a problem with the properties being pulled from the context.

I hope this helped to show how the Context API has the potential to change the way you architect your application in a big way. Reliance on Redux will go down, and prop-drilling will become obsolete, making your code easier to maintain and less buggy.