React context Hook
React context API we use to share the state of our application between components in clean and easy way.
Why we need to use contextHook when we can manage the application state using components props?
Ans : When the application components tree become huge and complex then time maintaining the state using props become difficult.
For Example:
Parent component ->child component 1 ->child component 2 ->child component 3 ->child component 4
In above case if we want to pass the data from parent component to the child component 4 , that would be difficult , first parent component will pass the state through props to child component 1 then child component 2 will pass the state through props to child component 3 and then child component 3 will pass the data to child component 4 , this is very log process and this is one kind of problem called prop drilling.
export default function Parent(){
let data={name:"Application data"}
return (
<div>
Parent
<Child1 data={data}/>
</div>
)
}
function Child1(props){
return (
<div>
Child1
<Child2 data={props.data}/>
</div>
)
}
function Child2(props){
return (
<div>
Child2
<Child3 data={props.data}/>
</div>
)
}
function Child3(props){
return (
<div>
Child3
<Child4 data={props.data}/>
</div>
)
}
function Child4(props){
return (
<div>
Child4
{props.data.name}
</div>
)
}
In order to fix this kind of issue we use context API to manage the state of the application.
In the below example i have shown how to fix the prop drill issue using context API
To create the context import createContext from react.
Since the Parent component is wrapped by the context provider , so the state is available to all the child component of the Parent.
To use the context import useContext from react. useContext always has to be called inside the component function.
import {createContext , useContext } from "react"
const ContextData=createContext({name:''})
export default function Parent(){
let data={name:"Application data"}
return (
<ContextData.Provider value={data}>
Parent
<Child1/>
</ContextData.Provider>
)
}
function Child1(){
return (
<div>
Child1
<Child2/>
</div>
)
}
function Child2(){
return (
<div>
Child2
<Child3/>
</div>
)
}
function Child3(){
return (
<div>
Child3
<Child4/>
</div>
)
}
function Child4(){
const data = useContext(ContextData)
return (
<div>
Child4
{data.name}
</div>
)
}