Skip to content

Instantly share code, notes, and snippets.

@jaydenseric
Created February 21, 2019 06:22
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaydenseric/a67cfb1b809b1b789daa17dfe6f83daa to your computer and use it in GitHub Desktop.
Save jaydenseric/a67cfb1b809b1b789daa17dfe6f83daa to your computer and use it in GitHub Desktop.
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
}
@neilhsmith
Copy link

neilhsmith commented Mar 17, 2023

One more option to the initial value being true or false debate:

const useIsMounted = (initialValue = true) => {
  const ref = useRef(initialValue)

  useEffect(() => {
    ref.current = true
    return () => {
      ref.current = false
    }
  }, [])

  return ref
}

Let that value be passed in. If true then it behaves like its mounted initially and only changes to false when it's unmounted. Useful to stop yourself from setting state when an async action is done after a component was unmounted. But if false then it's treated like the original solution where it still flips to false when unmounted but also flips to true when ready in the client.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment