Last active
July 18, 2023 11:46
-
-
Save andreievg/f1bef9429eb5101cbbc016c4df9936b9 to your computer and use it in GitHub Desktop.
Use state wrapper to expose partial state setter
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
export const usePartialState = <T extends object>( | |
initial: T | |
): { | |
state: T; | |
setState: Dispatch<SetStateAction<T>>; | |
setPartialState: (newPartialState: Partial<T>) => void; | |
} => { | |
const [state, setState] = useState<T>(initial); | |
return { | |
state, | |
setState, | |
setPartialState: newPartialState => | |
setState(state => ({ ...state, ...newPartialState })), | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simplifiest partial state update