I have seen some examples on how to code setState callback. All the examples I have seen are related to class components. My question is how do I write setState callback for a function component?
I have following code for an example
In the following code, after setData is called, due to it's asynchronous nature, I want to attach a call back so that I can perform some operation after setData is complete. Any guidance please...
function MyControl(props){
const[data,setData] = useState(null);
useEffect(()=>{
///fetch data and assign it
setData(studentInformation);
},[]);
return (
<div> </div>
)
}
CodePudding user response:
That is what useEffect
is for - to run code only when certain dependencies change.
useEffect(() => {
// this will only be called when data has changed
// run your code here
}, [data]);
CodePudding user response:
You'll have to use another useEffect that will detect changes to your data object and do whatever you want to accomplish there.
Someone asked this questions before. Check this answer.