import { useSafeSetState } from './custom';
// ...
const [state, safeSetState] = useSafeSetState({ name: '', email: '' })
// ...
Created
February 28, 2020 19:40
-
-
Save mauriciord/c725ef53241c77ab7f5249dd0d5c2614 to your computer and use it in GitHub Desktop.
useState and useSafeSetState
This file contains hidden or 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 { useReducer, useEffect, useRef } from 'react' | |
function useSetState(initialState) { | |
return useReducer( | |
(state, newState) => ({...state, ...newState}), | |
initialState, | |
) | |
} | |
function useSafeSetState(initialState) { | |
const [state, setState] = useSetState(initialState) | |
const mountedRef = useRef(false) | |
useEffect(() => { | |
mountedRef.current = true | |
return () => (mountedRef.current = false) | |
}, []) | |
const safeSetState = (...args) => mountedRef.current && setState(...args) | |
return [state, safeSetState] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment