You guys have probably seen this error, if not it usually looks something like this:
Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
Firstly this isn't a question about what the error means. It seems to me that there are some cases when this warning is (as far as I can tell) a bit unjustified.
Consider this component
() => {
const [foo, setFoo] = useState(false)
return (
<>
<p>Is foo: {foo}</p>
<button onClick={() => {
setFoo(true)
window.setTimeout(() => setFoo(false), 1000)
}}>Click me</button>
</>
)
}
Ok, so in this contrived example we wanna show Is foo: true
for 1 second after the button is clicked. If the component unmounts during that second it's going to call setFoo and we'll get that warning. As far as I can tell, this isn't a memory leak. It might be holding onto setFoo a bit longer than necessary but this won't build up over time, the timer will release setFoo albeit slightly later than it could. Am I missing something? My boss is telling me to get rid of the warning but to cancel the timeout adds a bunch of complexity to something which shouldn't be complex, and imo not going to offer any meaningful performance benefit.
This lead me to this idea:
export default () => {
const [state, setState] = useState(true)
useEffect(() => () => setState(false), [])
return state
}
const useSafeState = <T extends unknown>(defaultState: T): [T, (newState: T) => void] => {
const [state, setState] = useState<T>(defaultState)
const isMounted = useIsMounted()
return [
state,
(newState: T) => {
if (isMounted) {
setState(newState)
}
},
]
}
by changing the first example to use useSafeState
it automatically checks, effectively suppressing the warning. What do you guys think of this? Use safe state functionally does nothing, because as the react warning states it's a no op. I feel like the warning is there for when people forget to cancel their setIntervals from their useEffect, but for these other scenarios we're forced to do something silly like this just to get rid of the warning.
Thoughts?
setFoo
around, preventing it from being vacuumed. Here you are using a timeout so, the timeout would eventually run. But it could also cause trouble down the road if someone decided to lift the foo state out of this component and you would affect the state after leaving this component as the timer wasn't being stopped.