Skip to content

Instantly share code, notes, and snippets.

@mic-css
Last active April 14, 2020 11:33
Show Gist options
  • Save mic-css/6703224e66338cd72b13f9462d462753 to your computer and use it in GitHub Desktop.
Save mic-css/6703224e66338cd72b13f9462d462753 to your computer and use it in GitHub Desktop.
Custom hook that keeps track of whether a component is mounted, useful for canceling asynchronous setStates
import { useRef, useEffect } from 'react'
export const useIsMounted = () => {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current = true
return () => {
isMounted.current = false
}
}, [])
return isMounted
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment