React context is being used extensively for sharing state between React components. If you want proof, just go to facebook.com and open the React developer tools to see for yourself.
So if Facebook is using it so much - it must be a good way to manage state, right? Well, it turns out that React Context has its drawbacks that even Facebook developers are aware of.
The main 2 challenges are:
- Performance - unnecessary re-renders
- Flexibility - coupling state with the component tree
Performance
The first main challenge is performance. React Context doesn't allow us to use selectors and bailout of rendering. This makes it hard to reduce unnecessary renders and forces you to bend the architecture and reshape the providers all the time.
Flexibility
Context Providers are tied to components on the tree. This means that having dependencies between them forces you to carefully design the order of providers. Also, you cannot shape them as a tree of dependencies, since they are all on the same lineage.
The benefits
The main benefits of context are that it's a built-in mechanism inside React, which means it will naturally support concurrent mode and other changes by the React team. Also, since the state is eventually just a local component state (where the provider resides) - then you can manage it using hooks as you do for the local component state.
Are selectors coming to Context?
The second characteristic is built-in to Context, but there is a light at the end of the tunnel for selectors.
There is currently an open RFC for Context selectors, and we can all hope that it gets accepted sometime soon:
https://github.com/reactjs/rfcs/pull/119
Found mistakes? Think otherwise? Please let me know in the comments section below.
Top comments (1)
Re: context selectors, @dai_shi has written a useContextSelector hook for the time being (mentioned in the comments of the RFC you linked).