Table of contents
No headings in the article.
React context is a way to manage state globally.
It can be used together with the useState hook to share state between deeply nested components more easily than with useState alone.
//Pass data from app component to compC ile through file:-
// App->CompA->CompB->CompC
import { createContext } from 'react';
export const NameContext = createContext()
function App(){
return(
<div>
<NameContext.Provider value={'Megha'}>
<CompA/>
</NameContext.provider>
</div>
)
}
CompC File:- code
import { useContext } from 'react';
import { NameContext } from './App';
function CompP(){
const myName = useContext(NameContext)
return(
<div>
<h1>{myName}</h1>
</div>
)
}
Note:- To do this without cintext, we will need to pass the state as "props" through each each nested componets.this is called "prop drilling".
Happy Learning...