I've been reading up on the new context API and have a question regarding using it alongside HOC to inject props instead of directly wrapping every child that needs access to some state with a Consumer.
Isn't the above achievable without context? Isn't it possible to just house some state in a HOC and inject that into wrapped components that need access?
The React Context API is a way for a React app to effectively produce global variables that can be passed around. This is the alternative to "prop drilling" or moving props from grandparent to child to parent, and so on. Context is also touted as an easier, lighter approach to state management using Redux.
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. For example, in the code below we manually thread through a “theme” prop in order to style the Button component: class App extends React.
The legacy context API will be removed in a future major version. Use the new context API introduced with version 16.3. The legacy API will continue working for all 16.
It is possible but each wrapped component will have it's own data passed from HOC. While using context, this data is shared between components.
So changing data in a context will make all Consumers
re-render, while HOC will work only for the wrapped component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With