Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A React hook that tells if the component is mounted.
import React from 'react'
export const useIsMounted = () => {
const ref = React.useRef(false)
const [, setIsMounted] = React.useState(false)
React.useEffect(() => {
ref.current = true
setIsMounted(true)
return () => (ref.current = false)
}, [])
return () => ref.current
}
@timoxley

This comment has been minimized.

Copy link

timoxley commented Jun 4, 2019

@jaydenseric why setIsMounted(true)

@jaydenseric

This comment has been minimized.

Copy link
Owner Author

jaydenseric commented Jun 4, 2019

@timoxley I have since found ways to avoid having to use a useIsMounted hook, but from my rusty memory, the state is updated arbitrarily in the useEffect callback to trigger a re-render? I worked through a lot of gotchas to get it going.

@christiaanwesterbeek

This comment has been minimized.

Copy link

christiaanwesterbeek commented Jun 7, 2019

Use this one instead: https://github.com/jmlweb/isMounted
It doesn't use state for this, which is good.

yarn add ismounted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.