useContext hook explained React

useContext hook explained React

React useContext hook

·

4 min read

➜ Before directly jumping into the useContext we have to discuss about the Important & simple topic called Prop drilling.

➜ What do you think about word drilling , like water drill i.e purpose of drilling holes into the earth surface till ground water level is reached.

like passing prop to one component to another component till the last component reached called prop drilling. passing the prop through every child comes in the way before reaching the last component.

prop .png

Let's understand with the following example

➜ In App.js(parent component) we should first declare the state called 'name' value assigned to any random name say 'John'. and Create child four child components.

import the First child component named child1 into App.js.

    // App.js 
import React, { useState } from "react";
import Child1 from './Child1'
export default function App() {

const[name,setName] = useState('John')
  return (
    <>
       <Child1  name={name} />
    </>
  );
}

And return the prop(child1 component ) into the App.js (parent component),

Now into Child1 component import the second Child component called Child2 into the Child1, don't forget to add the curly brackets {} to the parenthesis function.

             // Child1
import React from 'react';
import Child2 from './Child2'

function Child1({name}){
  return(
    <div>
        <Child2 name={name} />
    </div>
  )
}

export default Child1;

Similarly as we did above Now we have to push the prop till the last Child component import the child3 component in to child2 and take a prop forward.

     //Child2
import React from 'react';
import Child3 from './Child3'

function Child2({name}){
  return(
    <div>
        <Child3 name={name} />
    </div>
  )
}

export default Child2;

Again import the next component into the Child3 to push the prop, the process of pushing the prop till the end called 'Prop drilling' .

       //Child3
import React from 'react';
import Child4 from './Child4'

function Child3({name}){
  return(
    <div>
        <Child4 name={name} />
    </div>
  )
}

export default Child3;

Comming to the last prop now print the name of the user and also using the any heading tag that's it.

 //Child4
import React  from 'react';

function Child4({name}){

  return(
    <div>
        <h1>{name}</h1>
    </div>
  )
}

export default Child4;

Output : -

jonh.png

Then what is solution for this promblem . You got it right , useContext hook 🚀💯

Instead of passing prop from one component to another component, pushing the prop till end to avoid all the unneccessary things we use simple hook called useContext. Just store some information and can use directly to any child component,

The hook it self as the name says 'useContext' to use content, data or some stored Information which we can use later , whenever it is necessary,

useContext used to pass the data from one component to second component and to many other components,share data easily with other components with all nested components,

The useContext hook is used to manage data globally. Once data is saved to the useContext and then you can use any all the nested components easily using state like global state. The useContext hook is the new addition in React 16.8.

In this Blog post we see how to use useContext hook works

To write useContext hook first we need to know

  1. How to create context
  2. How to provide the created context to componets and
  3. How to consume/take that context

First step is we need to import the useContext hook.

import React, { useContext } from "react";

➤➤ 1. create context ↯

There is a default function which is already present to create a context - createContext() Have to assign to a variable const with the {variable name} to store the context.

const NameContext = createContext();

➤➤ 2. provide to context ↯

Context.Provider function used to provide the context to the child components. the prop , 'name' used to stored while consuming the context.

   <NameContext.Provider value={name}>
      <Child1/>
    </NameContext.Provider>

➤➤ 3. Consuming the context ↯

The final step to consuming the context , we can consuming in the any of the child component whatever child you want to consume should be placed inside the provider component.

useContext() is used to access the context.

 const name = useContext(NameContext)
  return(
    <div>
      <h1>{name} from child2</h1>
    </div>
  )

That's all we have succesfully used the Context hook using simple steps
➜ Create context
➜ Provide context
➜ Consume context

import React, {createContext} from "react";
import Child1 from './Child1'

export const NameContext = createContext(); // create a context

export default function App({name}) {
  return (
    <div>
      <NameContext.Provider value={name}>  // providing the context
      <Child1/>
     </NameContext.Provider>
    </div>
  );
}

App.defaultProps = {
  name: 'john'
}

export default App;
===================================================================

// If we want to consume the from the second child

import React, {useContext} from 'react';
import {NameContext} from './App'

function Child2(){
  const name = useContext(NameContext)  // using the context
  return(
    <div>
![chikd2fjdk.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1659876225232/Q4RnL3-tf.png align="left")
      <h1>{name} from child2</h1>
    </div>
  )
}

export default Child2;

Output : - chikd2fjdk.png

THANKS FOR READING💐 If you found it helpfull hit a like👍😊