Last active
August 21, 2019 15:28
-
-
Save Kashkovsky/c1355f9cc2a4853e5288b585eebe9f9d to your computer and use it in GitHub Desktop.
useSafeState
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, useEffect, useCallback } from "react"; | |
const useSafeState = <T>(initialValue?: T): [T, (value: T) => void] => { | |
let mounted = true; | |
const [current, setCurrent] = useState(initialValue); | |
useEffect(() => () => (mounted = false), []); | |
const setter = useCallback((value: T) => mounted && setCurrent(value), [mounted]); | |
return [current, setter]; | |
} | |
export default useSafeState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment