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
}
@pharmpy-dev-123
Copy link

@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.

The state update is in fact an instance of the forceUpdate pattern.

@tamvo22
Copy link

tamvo22 commented Oct 18, 2022

@zmeyc Thank you for the clarification! I tested with a delayed API calls and found that you are right. As you pointed out, it only reflected the initial mount status hook call. All this time, I was under the assumption that isMounted would return the useRef value at the time of the API request. When I pass the function isMounted() to call during the API return, it does provide the correct mounted value when my test component mounted and unmounted. Thanks again cheers!

@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