Skip to content

Instantly share code, notes, and snippets.

@NataliaNagaeva
Created April 14, 2023 17:34
Show Gist options
  • Save NataliaNagaeva/0ee871b8a75d82e7ce4038d179c069d9 to your computer and use it in GitHub Desktop.
Save NataliaNagaeva/0ee871b8a75d82e7ce4038d179c069d9 to your computer and use it in GitHub Desktop.
function useSafeState(initValue) {
const [state, setState] = useState(initValue);
const isMounted = useIsMounted();
// useCallback because we need to add updateState function to effect deps
const updateState = useCallback((newValue) => {
if(isMounted.current) {
setState(newValue);
}
}, [isMounted]);
return [state, updateState];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment