DEV Community

Cover image for Pitfalls of overusing React Context

Pitfalls of overusing React Context

Brian Neville-O'Neill on February 04, 2020

Written by Ibrahima Ndaw✏️ For the most part, React and state go hand-in-hand. As your React app grows, it becomes more and more crucial to manage...
Collapse
 
markerikson profile image
Mark Erikson • Edited

We briefly tried using Context to pass down the Redux store state in React-Redux v6, but we ran into these perf problems. That's why we had to go back to direct store subscriptions in components as part of the React-Redux v7 rewrite.

I covered all the history of how and why we use context in React-Redux in my post The History and Implementation of React-Redux.

There's an interesting looking React RFC that was filed to add "context selector" functionality, but I will be surprised if the React team actually decides to do anything about it. Dan Abramov commented on Twitter that he doesn't think a selector-based API is a good approach.

Folks might also want to read through these other articles discussing context and Redux:

Collapse
 
karataev profile image
Eugene Karataev

Having one global context for an app is like providing a full state for every connected component in redux version. In both versions every context consumer/connected component will be re-rendered on any context/state update.
With react-redux it's important to connect a component to minimum slice of a global state to avoid unnecessary re-renders. The similar rule is true for contexts - keep separate contexts for every logical part of an app and avoid using unnecessary contexts in the components.

Collapse
 
sharlos profile image
Chris

Doesn't react-redux use context under the hood? How does it avoid the re-rendering issue?

Collapse
 
markerikson profile image
Mark Erikson

Because we only use context to pass the store instance, not the store state.

I just put up a blog post recently explaining the difference:

React, Redux, and Context Behavior

And for complete details on how React-Redux actually works internally, see my post The History and Implementation of React-Redux.

Collapse
 
joserfelix profile image
Jose Felix

Hi, great post!

Dan Abramov gives three solutions to this problem, check this issue.