reactjs(useContext Hook)

useContext hook notes:

1- The useContext hook accepts a context object and returns it.

2- If we wanna pass global variable in a react tree of components then using contextAPI and useContext hook makes it very simple & efficient .

Basically it follows three steps as mentioned below:

Step1: const SampleObjectContext = React.CreateContext(SampleObject.sample1); // this creates a context object with a default value.

Step2: <SampleObjectContext.Provider value={SampleObject.sample2}>

<FetaureComponentOne/>

</SampleObjectContext> // in this step the component(FetaureComponentOne) where the value was required is binded with in the context provider once this is done then the current context value becomes available to FetaureComponentOne and all its children components.

Step3: const MonthData = useContext(SampleObjectContext); // in the final step we receive the context object.

Please refer to the Sample Code below also added comments for better explanation:

// Below is the sample code demonstrating the useContext hook:

const SampleObject = {

sample1: {

weekday: "Monday",

month: "January"

},

sample2: {

weekday: "Tuesday",

month: "February"

}

};

const SampleObjectContext = React.CreateContext(SampleObject.sample1); // context object is created with initial/default value.

function App() {

return (

<SampleObjectContext.Provider value={SampleObject.sample2}>

<FetaureComponentOne/>

</SampleObjectContext>

);

}

function FetaureComponentOne() {

return (

<div>

<FetaureComponentTwo/>

</div>

);

}

function FetaureComponentTwo() {

const MonthData = useContext(SampleObjectContext); // here we are receiving SampleObject.sample2 as passed in context provider and assigning to MonthData.

return (

<div>

Week-day:{MonthData.weekday}, Month:{MonthData.month}

</div>

)

};

// end line.

Thanks, happy coding