Safely setState on a Mounted React Component through the useEffect Hook

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

In the class version of this component, we had a method called safeSetState which would check whether the component was still mounted before trying to call setState. This is because our graphql client library is unable to cancel in-flight requests. Let's make that same kind of thing work by tracking the mounted state of our component using the useRef and useEffect hooks.

Gonzalo Pozzo
Gonzalo Pozzo
~ 2 years ago

What is the difference of storing the old value using useRef instead of using a useState?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 2 years ago

When you call the state updater from useState, you force a re-render. When the value of a ref is updated, no re-render happens. Use the hooks accordingly.

V School
V School
~ 2 years ago

Okay, thanks Kent