Created
January 23, 2020 01:35
-
-
Save coryhouse/9b7b5265b6e9038558adf71e70d96841 to your computer and use it in GitHub Desktop.
React useSafeState hook - Only set state if mounted
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, 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