ReactJS Context

In ReactJS, if you want to share the data between two or more components, you need to keep that data to their component which is parent component and then you pass that data in the form of properties. If you want to share the same data to further down components, you need to do the same.
Its method is to manage state or data which can be shared among multiple components.
You can pass this data to components without using Props.

Herein the simple example.

import React, {useContext} from 'react';

const MyContext = React.createContext("This my context");

function App() {
    const ctx=useContext(MyContext);
  return (
      <div>
          {ctx}
      </div>
  );
}

export default App;

You would get the output:

This is my context

 

In the following example, you consume context value using Consumer

import React, {useContext} from 'react';

const DayContext = React.createContext("Monday");
function Today(){
    return(
        <DayContext.Consumer>
            {value => <div>Today is {value}</div>}
        </DayContext.Consumer>
    );
}

function App() {
  return (
  <DayContext.Provider value="Tuesday">
      <Today/>
  </DayContext.Provider>

  );
}

export default App;
Output:

*Today is Tuesday*

Class based Component example

import React, {useContext} from 'react';

const DayContext = React.createContext("Monday");

class Today extends React.Component{
    render() {
        return (
            <div>
                <DayContext.Consumer>
                    {value => <div>Today is {value}</div>}
                </DayContext.Consumer>
            </div>
        );
    }
}


function App() {
  return (
  <DayContext.Provider value="Wednesday">
      <Today/>
  </DayContext.Provider>

  );
}

export default App;

Accessing in class-based component using contextType

import React, {useContext} from 'react';

const DayContext = React.createContext("Monday");

class Today extends React.Component{
    static contextType=DayContext;
    render() {
        return (
            <div>
                <div>Today is {this.context}</div>
            </div>
        );
    }
}


function App() {
  return (
  <DayContext.Provider value="Thurday">
      <Today/>
  </DayContext.Provider>

  );
}

export default App;

If you use a Context Provider multiple times with different values, the component uses the value from the nearest context.


Here, we are wrapping Today Component in Day component with context value Wednesday and wrapping Day component in Context with value Tuesday, it would use Wednesday as its nearer Context.

import React, {Component, useContext} from 'react';

const DayContext = React.createContext("Monday");

class Today extends React.Component{
    static contextType=DayContext;
    render() {
        return (
            <div>
                <div>Today is {this.context}</div>
            </div>
        );
    }
}

class Day extends Component{
    render() {
        return (
            <DayContext.Provider value="Wednesday">
                <Today/>
            </DayContext.Provider>
        );
    }
}


function App() {
  return (
  <DayContext.Provider value="Tuesday">
      <Day/>
  </DayContext.Provider>

  );
}

export default App;
Output: Today is Wednesday

We can store object in context.

import React, {useContext} from 'react';

const MyContext = React.createContext({message:'Hello'});

function Component1(){
    const ctx=useContext(MyContext);
    return (
        <div>Component 1 context value : {ctx.message}</div>
    );
}

function App() {
    return (
        <div>
            <Component1/>
        </div>
    );
}

export default App;
Output: 
Component 1 context value : Hello

Sharing same value between all components

Here is the example in which we change value in app component and that changed value gets available in all components.

import React, {useContext} from 'react';

const MyContext = React.createContext({message:'Hello'});

function Component1(){
    const ctx=useContext(MyContext);
    return (
        <div>Component 1 context value : {ctx.message}</div>
    );
}
function Component2(){
    const ctx=useContext(MyContext);
    return (
        <div>Component 2 context value : {ctx.message}</div>
    );
}

function App() {
    const ctx=useContext(MyContext);
    ctx.message="Hi";
    return (
        <div>
            <Component1/>
            <Component2/>
        </div>
    );
}

export default App;
OUTPUT:

Component 1 context value : Hi
Component 2 context value : Hi 

Using Provider Tag to pass value

import React, {useContext} from 'react';

const MyContext = React.createContext({message:'Hello'});

function Component1(){
    const ctx=useContext(MyContext);
    return (
        <div>Component 1 context value : {ctx.message}</div>
    );
}
function Component2(){
    const ctx=useContext(MyContext);
    return (
        <div>Component 2 context value : {ctx.message}</div>
    );
}

function App() {
    return (
        <MyContext.Provider value={{message: 'Hi'}}>
            <div>
                <Component1/>
                <Component2/>
            </div>
        </MyContext.Provider>
    );
}

export default App;

Updating value from sub component

import React, {useContext, useState} from 'react';

const MyContext = React.createContext({timeValue:'Hello', setTimeValue:(val=>{})});

function TimeDisplay(){
    const ctx=useContext(MyContext);
    return (
        <div>Time is  {ctx.timeValue}</div>
    );
}
function TimeUpdate(){
    const ctx=useContext(MyContext);
    const updateTime=()=>{
        ctx.setTimeValue(''+new Date())
    }
    return (
        <div><button onClick={updateTime}>Update timeValue</button></div>
    );
}

function App() {
    const [timeValue, setTimeValue]= useState('no timeValue');
    return (
        <MyContext.Provider value={{timeValue: timeValue,setTimeValue:setTimeValue}}>
            <div>
                <TimeDisplay/>
                <TimeUpdate/>
            </div>
        </MyContext.Provider>
    );
}

export default App;

 

Tags