Last active
November 5, 2020 15:41
-
-
Save bradyclifford/d8b782a420f750a5411eb6aeab102ae2 to your computer and use it in GitHub Desktop.
Safe Unmounted React Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState, useRef, useEffect, useCallback } from 'react'; | |
/* | |
* useSafeState prevents state from being updated if a component has been | |
* unmounted during an async process, thus preventing React from throwing errors | |
* around it. | |
* | |
* Usage is just like regular useState: | |
* const [myState, setMyState] = useSafeState("Initial state"); | |
*/ | |
export default function useSafeState(initialValue) { | |
const [state, setState] = useState(initialValue); | |
const isMountedRef = useRef(true); | |
const setSafeState = useCallback(val => { | |
if (isMountedRef.current) return setState(val); | |
}, []); | |
useEffect( | |
() => () => { | |
isMountedRef.current = false; | |
}, | |
[] | |
); | |
return [state, setSafeState]; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useRef, useCallback } from 'react'; | |
/* | |
* useWhenMounted prevents state from being updated if a component has been | |
* unmounted during an async process, thus preventing React from throwing errors | |
* around it. | |
*/ | |
const useWhenMounted = () => { | |
const mountedRef = useRef(true); | |
const whenMounted = useCallback(func => { | |
if (!mountedRef.current) return; | |
func(); | |
}, []); | |
useEffect(() => () => (mountedRef.currrent = false), []); | |
return whenMounted; | |
} | |
export default useWhenMounted; | |
/* Usage: | |
* const whenMounted = useWhenMounted(); | |
* whenMounted(() => { | |
* // do things | |
* }); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment