Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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