Skip to content

Instantly share code, notes, and snippets.

@coryhouse
Created January 23, 2020 01:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryhouse/9b7b5265b6e9038558adf71e70d96841 to your computer and use it in GitHub Desktop.
Save coryhouse/9b7b5265b6e9038558adf71e70d96841 to your computer and use it in GitHub Desktop.
React useSafeState hook - Only set state if mounted
import { useEffect, useRef, useState } from "react";
/**
* Provides the functionality of React.useState() with the only difference that
* it sets a state only if its parent component is still mounted, aka "safe setState".
*/
export default function useSafeState(initialState) {
const mountedRef = useRef(false);
const [state, setState] = useState(initialState);
useEffect(() => {
mountedRef.current = true;
return () => (mountedRef.current = false);
}, []);
const safeSetState = (...args) => mountedRef.current && setState(...args);
return [state, safeSetState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment