Created
December 29, 2020 18:22
-
-
Save Jtosbornex/5a9e8384de868625520cb568db904b0a to your computer and use it in GitHub Desktop.
React Enhanced State Management
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
import { useState, useCallback } from 'react'; | |
import { PickOne } from 'pick-one.type'; | |
export type UseStateEnhancedManagement<T> = [ | |
T, | |
{ | |
setState: React.Dispatch<React.SetStateAction<T>>; | |
setProperty: (property: PickOne<T>) => void; | |
setProperties: (properties: Partial<T>) => void; | |
} | |
] | |
export const useStateEnhanced = <T>(initialState:T):UseStateEnhancedManagement<T> => { | |
const [state, setState] = useState<T>(initialState); | |
const setProperty = useCallback((property: PickOne<T>) => | |
setState((prevState) => ({ ...prevState, ...property })), []) | |
const setProperties = useCallback((properties: Partial<T>) => | |
setState((prevState) => ({ ...prevState, ...properties })), []) | |
return [ state, {setState, setProperty, setProperties} ] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why this is useful? If you are constantly the following or some variation of the following. We can turn this:
Into this, while preserviing type safety:
Here is an example in how to use: