Created
March 9, 2022 13:32
-
-
Save agnel/6d4a69516f6d22e65bc5eb87257ed3ae to your computer and use it in GitHub Desktop.
useObjectState hook in react with type definitions
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 { 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>> | |
]; |
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 } 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