React’s new Context API

React's new Context API  #React  #reactjs

  • The provider component puts the data into context, and the Higher Order Component pulls the data out of context.
  • So in reality, redux isn’t allowing your data to be accessible anywhere… context is!
  • The first pull request to that repository is from Andrew Clark (react core team member) and it’s called “New version of context”.
  • The React team will remove the warning about context being an experimental feature because it’s now a “first-class feature” of the framework.
  • One question that I’ve seen a lot about the new context API (or the render prop pattern in general) is how to compose providers and consumers together.

Have you heard of the context API in React? If you’ve heard of it, are you like many others afraid to use it directly because you saw this in the official docs:

The first result of that search is showing “Why Not To Use Context”. Doesn’t inspire a whole lot of confidence in the context API. To make things even more concerning, that section says:

Have you ever experienced the pain of trying to get state from the top of your react tree to the bottom? This pain you’re feeling is called “prop drilling” and it’s super annoying. You wind up having to pass props through components that don’t care about the data just so you can send it down to components that do care. And as you move components around this pain is magnified.

You could actually use a regular JavaScript module to avoid these problems. Just put the data in a singleton module and poof, it’s accessible/importable anywhere. But then you have trouble with updates (you have to implement an event emitter to notify subscribers when there are updates), and server side rendering can be problematic with singletons as well.

So this is where state management libraries like redux comes into play. They allow you to get data from the store easily anywhere in the tree. All you have to do is use this thing called a and…

React’s new Context API