'Why Context API is worse than Redux for high frequency updates?
I saw many articles that Redux is better than Context API in performance than high frequency updates, but nothing is specific and tell why.
What makes people say Redux is better than Context API for high frequency updates?
Solution 1:[1]
I covered this extensively in my posts Why React Context is Not a "State Management" Tool (and Why It Doesn't Replace Redux), React, Redux, and Context Behavior, and The History and Implementation of React-Redux.
Summarizing: currently, passing a new value into a <MyContext.Provider>
forces every component subscribed to that context to re-render. There's no way to bail out if a component only cares about part of the Context value and that part did not change.
Also, React currently has to do a fair amount of work to loop over the entire component tree to figure out which components are subscribed to a given context.
React-Redux, on the other hand, relies on direct subscriptions to the Redux store. It runs your selectors when an action is dispatched, and only forces that component to re-render if the extracted data has changed. So, at the moment, that provides better performance in most cases than Context does, because fewer components will need to re-render for a given change.
The React team has been working on some potential implementations for "context selectors" and "lazy context propagation", which may help speed things up in the future. Right now there's no timeline for when those might be released.
Solution 2:[2]
TL;DR
Yes, because context API re-render every subscribed component as markerikson mentioned. But there are workarounds.
After some research, I found this article. There are 4 approach mentioned. I tried the "container" in my project. It did solve my performance issue.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | markerikson |
Solution 2 | EthanSnow |