Context in ReactJs

Published 3 Jun,2021
Passing props Recurrsively to child elements is cumbersome and since we might have multiple components sharing same data . The data here has to be passed recurrsively down the component tree
useContext could be used to maintain a global copy of the data that all the components can share. This provides a cleaner way to share data between components.
One of the common use cases is tracking the currently logged in user details.Instead of passing the same logged status to every component that uses it we can just write can make use of the Context concept to create a clean code.Or designing a theme for a website.
Let's start off with a simple example of using Context concept
import React,{createContext} from 'react';

export const usePersonalization=createContext({book:" ",author:""});

export default (props)=>
{
  const personalized=
  {
  book:"Harry Potter and Prizoner of Azkaban",
  author:"J.K.Rowling"
  }

return(<usePersonalization.Provider 
      value={personalized}>
      {
        props.children
      }
</usePersonalization.Provider>)
}
  

We are creating a context called usePersonalization.The value to the provider is provided by the personalized object having attributes book and author.The provider is initialized to empty string values, whenever React senses a change in the provider value, the child components are again re-rendered reflecting the change. {props.children} is used since we won't know beforehand as to what child components the Provider component will have so, its a way of cautioning of the possibility of a child component. The Provider is like a key necessary to access the data by the child components.

import Preference,{usePersonalization} from './Preference';

const Recommend=()=>{
  const {book,author}=React.useContext(usePersonalization);

  return(<div><h4>{book}</h4><small>{author}</small></div>)
  }

The preference component is a functional component that will be rendered as a child component to the Preference component.useContext is required to read the value supplied by the nearest provider.Here the provider is the Preference component

 <Preference><Recommend/></Preference>
 

Since the Recommend component is a child of Preference, we can use the values broadcasted by the provider

All the child components to the Provider get re-rendered whenever the value of the provider changes, as all the children components have subscribed to the chages in the provider
This blog provides a basic overview on the context concept

Read on How to use React Context effectively by Kent C. Dodds