Skip to content

Instantly share code, notes, and snippets.

@Jtosbornex
Created December 29, 2020 18:22
Show Gist options
  • Select an option

  • Save Jtosbornex/5a9e8384de868625520cb568db904b0a to your computer and use it in GitHub Desktop.

Select an option

Save Jtosbornex/5a9e8384de868625520cb568db904b0a to your computer and use it in GitHub Desktop.
React Enhanced State Management
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} ]
}
@Jtosbornex
Copy link
Copy Markdown
Author

Jtosbornex commented Dec 29, 2020

Why this is useful? If you are constantly the following or some variation of the following. We can turn this:

setState((prevState) => ({...prevState, updatedProp1: 'hello' }));

Into this, while preserviing type safety:

setProperty({ updatedProp1: 'hello' });

Here is an example in how to use:

  const [state, {setState, setProperty, setProperties}] = useStateEnhanced<IProductSearchState>({
    productSearchResults: [],
    searchValue: '',
    selectedProductToAdd: undefined,
    isSearching: false,
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment