Context API (useContext) in React Js

 

Before Context API:

ComA.jsx

import ComB from './ComB'

const ComA = () => {
    return (
        <>
         <ComB value = {{name : "himanshu", age : 24}} />
        </>
    )
}
export default ComA

ComB.jsx

import ComC from './ComC'

const ComB = (props=>{
    return (
        <>
       <ComC value = {props.value} />
        </>
    )
}
export default ComB

ComC.jsx


const ComC = (props=> {
    return (           
            <>
        <h1>hello from ComC</h1>
        <p>{props.value.name}</p>
        <p>{props.value.age}</p>
        </>         
    ) }        
export default ComC

Every time we have to pass props manually, know as prop drilling.

This method is not optimized, because we have to pass props to every child component to reach the specific child where we actually want to show.

After ContextAPI:

//1. create context
//2. provider
//3 . consumer (useContext)

The consumer is a bit lengthy, so it has been replaced by use context()



1.create context
const bioData = createContext();

2.provide value that needs to be passed using provider
<bioData.Provider  value = {[{name : "himanshu", age : 24} ]}>
        <ComB />
 </bioData.Provider>

3.Wrap the child with the provider
<bioData.Provider  value = {[{name : "himanshu", age : 24} ]}>
                <ComB />
            </bioData.Provider>

4.export that provider
export {bioData}

5.import the provider value to the child component where data needs to be
actually passed
import {bioData} from './ComA'

6. create useContexct and pass the provider value
const dataContext = useContext(bioData)

7. Boom! you got the value
return (         
            <>
        <h1>Hello from ComC {dataContext[0].name} </h1>
        <h2>Hello from ComC {dataContext[0].age} </h2>
        </>    

ComA.jsx

import { createContext } from 'react'
import ComB from './ComB'

const bioData = createContext();

const ComA = () => {
    return (
        <>
            <bioData.Provider  value = {[{name : "himanshu", age : 24} ]}>
                <ComB />
            </bioData.Provider>
        </>
    )
}

export default ComA
export {bioData}

ComB.jsx

import ComC from './ComC'

const ComB = () =>{
    return (
        <>
        <ComC />
        </>
    )
}
export default ComB

ComC.jxs

import React, { useContext } from "react"
import {bioData} from './ComA'

const ComC = () => {
    
    const dataContext = useContext(bioData)
    console.log(dataContext);
    
    return (           
            <>
        <h1>Hello from ComC {dataContext[0].name} </h1>
        <h2>Hello from ComC {dataContext[0].age} </h2>
        </>         
    ) }        
export default ComC

// no redundancy issue of passing props to every child

//this method helps to directly pass the data to that child component where we actually want

0 Comments