Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to execute useEffect when boolean changes in one direction?

I want to execute effect when val goes from false to true, but not the other way around.

This is the best I came up with:

 const valPrev = useRef(val);
  useEffect(() => {
    if (val && !valPrev.current) {
      // do stuff
    }
    valPrev.current = val;
  }, [val]);

But it feels like there might be a more clever way, maybe using return function somehow?

Edit: my bad, I've neglected to stress, I want effect run on change. Whenever val goes from false to true. Which means it should skip the initial render.

like image 808
seeker_of_bacon Avatar asked Mar 16 '26 14:03

seeker_of_bacon


1 Answers

And what about this?

useEffect(() => {
  if (val) {
    // do stuff
   }
}, [val]);
like image 173
Max Avatar answered Mar 19 '26 22:03

Max