简体   繁体   中英

React Context API & HOC

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 documentation explains the use case where a lot of components need to access the common theme , and hence can be wrapped with an HOC. without the context , you can make use of HOCs state to store the variable and pass on to the components wrapped with HOC but all of these components will have a different instance of the state and won't react to the theme change together.

Context makes it possible to store the data centrally and all listeners/consumers will react to the change together.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM