Skip to content

Instantly share code, notes, and snippets.

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
return () => (ref.current = false)
}, [])
return () => ref.current

This comment has been minimized.

Copy link

timoxley commented Jun 4, 2019

@jaydenseric why setIsMounted(true)


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.


This comment has been minimized.

Copy link

christiaanwesterbeek commented Jun 7, 2019

Use this one instead:
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.