Created
August 21, 2019 15:27
-
-
Save Kashkovsky/d458eadb74dabc0f46cfaf765e5aa491 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