If you are working with class components in React so maybe you are familiar with the callback function in setState().
setState(updateState, callbackFunction)
this.setState({name: “Azeem Aleem”},()=>{
console.log(“State Response”,this.state.name);
})
This callback function always calls after state update. But in functional components, the scenario is a little bit different.
We cannot use callback directly in the useState hook. To use callback in the useState hook, we need to use the useEffect hook that triggers after state update and call the function after that.
const [state, setState] = useState();
useEffect(() => {callbackFunction()}, [state])
We need to pass state in the useEffect Dependency Array. useEffect is triggered when the state updates and then calls the inside function immediately.
Follow me on LinkedIn
Any questions? Please comment. Thanks! Regards: Azeem Aleem