DEV Community

Discussion on: React race condition bug

Collapse
 
ap13p profile image
Afief S

Hi, great article! 😄

But, I think using useRef feels like magic to me, because I never know whether useEffect will update ref.current or not.
So, instead of using useRef, I use something like a skip method.
For example:

useEffect(() => {
  let canceled = false;

  getPet(pets.selectedPet)
    .then(data => {
      if (!canceled) dispatch({ type: "FETCH_PET_SUCCESS", payload: data });
  });

  return () => canceled = true;
}, [pets.selectedPet])

In the above snippet I know for sure (I have tried it before) that dispatch will not run if pets.selectedPet are changed, because useEffect will always call tear down function whenever it's dependencies array are changed.

Collapse
 
sag1v profile image
Sagiv ben giat • Edited

Thanks for the feedback 😊
I agree, this is another possible solution and it should work great.
The only thing to look for here, is that your effect doesn't have different logic with none relevant dependencies (which it shouldn't have!), though i did see some mixed logic inside effects in some code sources.

I think i will add this as another solution in the post. Thank you 🙏

Edit
Forgot to mention, regarding the magic of ref.current in effects. Its actually just a mutable box handled by react, not different than state or reducers really. It will change every time the effect runs, its just attached to the "instance" of the component so you can access it outside the effect's scope.