Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this.context work in React?

Tags:

reactjs

It’s not an official API (yet!), but context can be super useful in React mixins. However, its behavior and contents are not entirely intuitive for me.

Where do the contents of this.context come from?

(As of this writing, React is at version 0.12)

like image 379
Alan H. Avatar asked Nov 27 '14 00:11

Alan H.


People also ask

Why we use React context?

Context's job in React is to share data or the app state across all the app components. This means that the props can be accessed from any component. Therefore, no need to pâss props through other components to send it at the end to our destination component. Less code, less debugging hassle, and more code visibility.

Does context work in react native?

React Context API provides a easy way to pass data through the component tree without having to pass props down manually at every level. You can find more about the Context API in React documentation. You can use the React Context API with React Native Navigation with a limitation.

What is context and explain its components?

Context allows passing data through the component tree without passing props down manually at every level. In React application, we passed data in a top-down approach via props. Sometimes it is inconvenient for certain types of props that are required by many components in the React application.


1 Answers

I was looking into this too earlier, this.context is a set of attributes that are implicitly passed down to its children rather than passing the properties explicitly. You can look at the React testing suites to see how they behave:

https://github.com/facebook/react/blob/0.12-stable/src/core/tests/ReactCompositeComponent-test.js#L1101

https://github.com/facebook/react/blob/0.12-stable/src/core/tests/ReactElement-test.js#L100

I also found this article by Dave King helpful in understanding some of the exposed methods and behaviors: http://web.archive.org/web/20150319074927/https://www.tildedave.com/2014/11/15/introduction-to-contexts-in-react-js.html

like image 80
trekforever Avatar answered Oct 07 '22 17:10

trekforever