Skip to content

Instantly share code, notes, and snippets.

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