Use Context:
it is used to solve the prop drilling issue.
Prop drilling means the state is passing to children.
Parent
|
Child
|
Sub child
CreateContext: creating context variable Syntax : const store = createContext();
Passing the data through provider property: < store.provider > //Wrapping the all components < /store.provider >
Note: If you wrap your components in multiple providers, it will consume the data from the nearest provider.
useContext: using the data.
Disadvantages of context API: if the state is changed, then all the components in the context will be re-rendered.
import {createContext} from "react" export const appContext=createContext(data); export const AppProducer = appContext.Provider; export const AppConsume = appContext.Consumer ;
//producer component :
<AppProducer value={data}>
<components>
//wrap components which are required data
</AppProducer>
//consumer components :
<AppConsumer>
{(data)=>(
<div>{data}</div>
)}
</AppConsumer>
Applications : 1). login username displayed in the application
2). theme (light and dark mode).
Note: the data is real-time.
useContext: useContext hook allows us to use hooks to consume data instead of using appConsumer. syntax : const data=useContext(appcontext)
example in typescript : create context: you can create this context outside your app tree.