useContext Hook in ReactJs

 useContext Hook in ReactJs

“useContext” hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level. Context defined will be available to all the child components without involving “props”

App.js
import { createContext } from 'react';
import './App.css';
import CompA from './CompA';

const First = createContext();
const Last = createContext();

function App() {
   return (
    <>
      <First.Provider value={"shreyash "}>
        <Last.Provider value={"kolhe"}>
          <CompA />
        </Last.Provider>
      </First.Provider>
    </>
  );
}

export default App;
export { First,Last };
CompA.js
import React from 'react'
import CompB from './CompB'

export default function CompA() {
    return (
        <div>
            <CompB/>
        </div>
    )
}
CompB.js
import React, {useContextfrom 'react'
import { FirstLast } from './App'

export default function CompB() {
const fname = useContext(First);
const lname = useContext(Last);
    return (
        <>
            <h1>My name is {fname}{lname}</h1>
        </>
    )
}
Output