Created
April 4, 2020 10:45
-
-
Save russellr922/e46466b837c8435551a1cf1c20e6430b to your computer and use it in GitHub Desktop.
React setState hook typescript (merge)
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
function isSimpleObject(value: any): boolean { | |
return !!value && value.constructor === Object; | |
} | |
function useMergeState<T>(initialState?: T) { | |
const [mergeState, setMergeState] = isSimpleObject(initialState) | |
? React.useState<T>(initialState as T) | |
: React.useState<Partial<T>>(); | |
const setState = React.useCallback((newState: Partial<T>) => { | |
if (isSimpleObject(newState)) { | |
setMergeState((state: any) => | |
(state as T) ? { ...state, ...newState } : newState | |
); | |
} | |
}, []); | |
return [mergeState, setState] as [T | undefined, typeof setMergeState]; | |
} | |
export default useMergeState; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment