Skip to content

Instantly share code, notes, and snippets.

@russellr922
Created April 4, 2020 10:45
Show Gist options
  • Save russellr922/e46466b837c8435551a1cf1c20e6430b to your computer and use it in GitHub Desktop.
Save russellr922/e46466b837c8435551a1cf1c20e6430b to your computer and use it in GitHub Desktop.
React setState hook typescript (merge)
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