State lifting is a technique where the state is shared between multiple child components so they can share and synchronize the same state.
When we nest a component as child to a parent component, then the communication happens between the Parent and Child:
Parent can communicate to the Child Component by passing props to the child.
//Parent.jsx
<Child greet={"hello"} />
//Child.jsx
props.greet // => gives "hello"
Children can communicate to the Parent using functions passed by the Parent as props.
//Parent.jsx
let [counter, setCounter] = useState(0)
<Child count={{counter, setCounter}} />
//Child.jsx
props.count.Counter // => gives counter value
props.count.seCounter(0) //=> gives the setCounter()
But When we want to pass the stateVariable
and stateFunction
from the Child to Parent:
//Parent.jsx
function getDataFromChild(data){
// code to handle the DATA from CHILD
}
<Child passToParent={getDataFromChild} />
// Child.jsx
<button className="btn btn-success p-3" onClick={()=>{
setSample(sample+1)
props.passToParent(sample)
}} >Send Data to Parent</button>