Home > Software engineering >  How to perform some actions when the state changes, but only for the first update?
How to perform some actions when the state changes, but only for the first update?

Time:10-25

I have a state which initially is undefined. After certain actions have been done, I am updating that state and I need to run something as soon as that state is updated. But, since, that state changes quite often, I don't want to use useEffect cuz, I don't want the code to be executed everytime state changes. Just for the first update. How can I achieve that? Here is the code demonstartion

const [annotations,setAnnotations] =useState()

// A bunch of changes and after some time, called setAnnotations(value)

useEffect(()=> {
// here I need to do something. But, don't have the latest annotations.
// I only need to do // something only for the first time
},[]) 

CodePudding user response:

I don't want the code to be executed everytime state changes. Just for the first update

You could for example set a custom flag to check whether it already called or not yet. And depend on it.

const flag = useRef<boolean>(true);

useEffect(() => {
   if (flag.current) {
     // do stuff
     flag.current = false; // set flag to false so it won't be called anymore
   }
}, []);
  

CodePudding user response:

I would do the same as kind user, but add your state as a dependency of the useEffect. That way it only runs when the state changes in the first place. Just makes the code a little more robust.

const [annotations,setAnnotations] =useState() 

const flag = useRef<boolean>(true);

useEffect(() => {
   if (flag.current) {
     // do stuff
     flag.current = false; // set flag to false so it won't be called anymore
   }
}, [annotations]);
  • Related