Skip to content

Instantly share code, notes, and snippets.

@agnel
Created March 9, 2022 13:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agnel/6d4a69516f6d22e65bc5eb87257ed3ae to your computer and use it in GitHub Desktop.
Save agnel/6d4a69516f6d22e65bc5eb87257ed3ae to your computer and use it in GitHub Desktop.
useObjectState hook in react with type definitions
import { Dispatch, SetStateAction } from 'react';
/**
* This method needs to provide the type of the initialState like
* `useObjectState<initialStateInterface>(initialState)`
* @param {*} initialState The initial state the user wants to set
* @returns Array containing `state` object, `setState` method and `updateState` method
*/
function useObjectState<S>(initialState: S): [
S,
Dispatch<SetStateAction<S>>,
Dispatch<Partial<S>>
];
import { useState } from 'react';
/**
* This method needs to provide the type of the initialState like
* `useObjectState<initialStateInterface>(initialState)`
* @param {object} initialState The initial state the user wants to set
* @returns Array containing `state` object, `setState` method and `updateState` method
*/
export const useObjectState = (initialState) => {
const [state, setState] = useState(initialState);
const updateState = (newState) => {
setState((prevState) => {
return {
...prevState,
...newState
}
});
}
return [state, setState, updateState];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment