1

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>
       )
}
V R
  • 133
  • 1
  • 8
  • What do you want to do once state is set? Why not just do it next time the component renders, which will be triggered by the update? – jonrsharpe Oct 05 '21 at 20:41

2 Answers2

1

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]);
larz
  • 5,724
  • 2
  • 11
  • 20
0

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.