- The new React Context API is touted (at least on Twitter and a number of articles) as solving the need to use a state management tool, when I think in reality what it solves is easy dependency injection: Take something that lives at the top of your app and directly…
- It essentially gives you an easy way to have state live at the top level in your component tree ( in this case) but “inject” it as a prop in a lower level component in the state tree.
- A Consumer works hand-in-hand with the Context’s Provider, essentially allowing you to reach into your Context, and easily inject the Context’s value into a component, skipping many levels in the component tree.
- Now that we’ve set up our Context and have created the Provider which wraps our app at the top level, we can now inject its into any of our lower level components.
- When thinking of how to organize an app which uses React Context, I wanted to avoid having the Consumer code in the same file as the component which it “wraps”… the reason for this is because it makes it difficult to test the component in isolation.
We’ll take a look at the new React Context API, how to use it, what it does, and if it should replace Redux or MobX for your go-to state management option.
Continue reading “Introducing the React Context API”