Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 241
Samuel Avatar asked Apr 01 '18 08:04

Samuel


People also ask

What is the context API in React?

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.

What is context API in React JS with example?

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.

Is context API deprecated?

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.


1 Answers

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.

like image 89
Tomasz Mularczyk Avatar answered Sep 21 '22 17:09

Tomasz Mularczyk