Make your state safe
Imagine you have a simple component Post
which just renders a post page.
export const Post = (): JSX.Element => {
const [value, setValue] = useState<string>()
const url = 'http://somewhere.com/something'
useEffect(() => {
axios.get(url).then<string>((response) => {
setValue(response.data)
})
}, [])
return <div>{value}</div>
}
Just for simplicity purpose let’s output just a single string.
And now a question: What will be, if we go to another page (or Post
component will be unmounted in some other way) before the data load finish?
In this case we will get this warning in the console:
Nothing is broken. The app still works. App users may not even notice any problems except for the red warning in the console.
You can leave it as is, but you should know that each such event causes a memory leak. At some point, it could become a problem.
The easiest solution is to use the useSafeState
hook from the ahooks package. Just replace your useState
with useSafeState
, and everything will work out of the box.
const [value, setValue] = useSafeState<string>();
I highly recommend to check the source code of useSafeState
and research how it works. The code is not too large, so it’s not a big deal.
By the way useSafeState
under the hood uses highly usefull useUnmountedRef
hook, which checks if component is unmounted.
However, that is a topic for another story 🙂
Dodaj komentarz