React JS Context

In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Lets discuss one example. We have one component ParentComponent. ParentComponent have three child component A, B and C.

  • A have no child component.
  • B have B1 child component.
  • C have C1 child component. C1 have C2 childComponent.

Now we have one data value which is used in A , B1 and C2. then we have to pass this value to all child component through props. In this case context will help us to resolve this issue.

1. userContext.js

userContext
import React from 'react'; const UserContext = React.userContext(); const UserProvider = UserContext.Provider; const UserConsumer = UserContext.Consumer; export { UserProvider, UserConsumer}

2. ParentComponent.js

ParentComponent
import React, { Component } from 'react'; import ComponentC from './ComponentC'; import { UserProvider } from './UserProvider'; class ParentComponent extends Component { render() { return( <div> <UserProvider value="React"> <ComponentC /> </UserProvider> </div> ); } } export default ParentComponent;

3. ComponentC

ComponentC
import React, { Component } from 'react'; import ComponentC1 from './ComponentC1'; class ComponentC extends Component { render() { return( <div> <ComponentC1 /> </div> ); } } export default ComponentC;

4. ComponentC1

ComponentC1
import React, { Component } from 'react'; import ComponentC2 from './ComponentC2'; class ComponentC1 extends Component { render() { return( <div> <ComponentC2 /> </div> ); } } export default ComponentC1;

5. ComponentC2

ComponentC2
import React, { Component } from 'react'; import { UserConsumer } from './UserProvider'; class ComponentC2 extends Component { render() { return( <div> <UserConsumer value="React"> { (name) => return <div> Hello {value} </div> } </UserConsumer> </div> ); } } export default ComponentC2;

In above code, We create a UserContext. and Component C > C1 > C2. Now we have to pass one value from ParentComponent to C2 component without adding props in C and C1. So, ParentComponent is out Provider Component and C2 is Our consumer component. Provider Component is responsible to provide value to all the descendants' components. ComponentC2 is consume the name in jsx and show it in browser. Here, we all pass function from provider to consumer. We can also, use multiple context providers at a time.

 

← Previous

Next →