Skip to content

Instantly share code, notes, and snippets.

@Kashkovsky
Last active August 21, 2019 15:28
Show Gist options
  • Save Kashkovsky/c1355f9cc2a4853e5288b585eebe9f9d to your computer and use it in GitHub Desktop.
Save Kashkovsky/c1355f9cc2a4853e5288b585eebe9f9d to your computer and use it in GitHub Desktop.
useSafeState
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