Skip to content

Instantly share code, notes, and snippets.

@bradyclifford
Last active November 5, 2020 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradyclifford/d8b782a420f750a5411eb6aeab102ae2 to your computer and use it in GitHub Desktop.
Save bradyclifford/d8b782a420f750a5411eb6aeab102ae2 to your computer and use it in GitHub Desktop.
Safe Unmounted React Hooks
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];
}
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