React 16.3 Context API explained in 2 minutes

We talked about unidirectional data-flows and how connecting multiple components means you have to hoist common state and then connect with props and callbacks.

You see, when you're deeply nesting your components and they all have to know about some common state, it means you have to go props, props, props ...

We have this state here, and it's shared between very deeply nested components. This one and this one need to know about the state. Here you have to pass props like this.

But if you use the new Context API you can basically rep everything into a shared space. You have access directly to the state that you care about.

Let's look at it in code.

First create a new file where we're going to create a context for everyone to share. Create context ... The reason we're creating it in a new file is so that we can share it between multiple different files.

Import, add context. Going to render a context provider. AppContext.Provider, where we're gonna say value equals this.state.

So we now have a context. Into message we're going to import AppContext over here instead of using the hovered prop. Say this uses the context consumer, and the context consumer uses something called function-as-children, and it gets the value, which is our state ... We return what we're rendering. We're gonna talk about what this is and function-as-children and render props and all of that a bit later.

Instead of hovered we're going to say state.hoveredMessages[0] to our button, and we say this is a consumer here instead of background. State dot ...

This is all stuff that we can improve later, but ...

We now have this common shared state that everybody has access to, that tells us whether the ... We're still spelunking callbacks, but we can move those callbacks into state as well.

We take out mouse-over stuff from here. onMouseOver ... state.onHover. onMouseOut ... state.onUnhover.

Back into app.js, and here where we're defining onHover and onUnhover we're gonna take those out of our component body and put them into state. Fix the syntax. We no longer pass them into our button.

And it still works.

And that's how you use the new React context API to get rid of all of Redux and MobX ... and you should probably still use those for some things.

Know someone who wants to learn React and its whole ecosystem? Share 👇


Cheers,
~Swizec