Introduction React Context

 

1. Prop Drilling

Props are passed from one Component to another Component that does not need the data but only helps in passing it through the tree is called Prop Drilling.

2. React Context

Context is a mechanism that provides different Components and allows us to pass data without doing prop drilling.

2.1 Creating Context

Syntax:

React.createContext(INITIAL_VALUE)
JSX

It returns an object with different properties to update and access values from the context.

2.2 Context Properties

The Context object provides two properties.

  1. Consumer
  2. Provider

2.3 How to Access the Value?

We can access the value in the Context using

Consumer Component
provided by the Context Object.

3. Consumer Component

Syntax:

<ContextObject.Consumer>
{/*callback function*/}
</ContextObject.Consumer>
JSX
  • We access the 
    Consumer component
     using dot notation from the 
    context object
    .
  • We will give a 
    callback function
     as children for 
    Consumer Component
    .

3.1 Understanding Syntax

The callback function receives the current context value as an argument and returns a component or a JSX element.


Make an seprate Folder for Context

Because we require Language in all the Components so instead of sending every time in props we will make a seprate Context Folder and Make file for realated to context

like ./src/context/LanguageContext.js

refer below code  and how to use this Context in our Component refer components-NewWaysToConnect.js file


..............

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form