Reputation:
I have read up on the context API and it looks like an elegant way to solve the uni-directional data communication issues of react.
However there is also Redux which does a good job of sharing a global state.
Are there any performance benefits I will get if I use the context API and hooks?
PS: I read that with the context API we will have to keep the rendering in check since, it even make the entire app re-render at times.
Upvotes: 21
Views: 14659
Reputation: 537
Context API was originally designed for high amount of read, low amount of write operations (like changing the theme between light and dark)
You should use props for 1, 2 or 3 level deep data
Thanks for the downvotes, here is the source
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component reuse more difficult.
If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
Upvotes: 19
Reputation: 3164
With Redux you can fine-tune performance with 4 helper functions:
areStatesEqual
areOwnPropsEqual
areStatePropsEqual
areMergedPropsEqual
All four helpers have some reasonable default functionality you benefit from by default.
With hooks you can use React.memo
as explained here to improve performance, it obviously doesn't come as a default option so you need to explicitly use it.
With Context API I wish I could say that you can use shouldComponentUpdate
but I probably cannot because it belongs to React class components which are out of fashion.
Upvotes: 5
Reputation: 439
Use-context with Use-reducer to replace redux is not a good practice. Context will cause reloading of the pages, this will be identified if we look into the profiler provided by react dev tools, where as redux won't do that. Redux is better than use-context for global state management
Upvotes: 5