Created
February 13, 2023 23:45
-
-
Save IrvingArmenta/0495a61231a128358a95387a34262c8e to your computer and use it in GitHub Desktop.
useObjectState: simple hook for object state as it was with class based components
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
import { type SetStateAction, useState } from 'react' | |
// import deepMerge from './deepmerge' | |
// this would be necessary if deep merge is used | |
// type Subset<K> = { | |
// [attr in keyof K]?: K[attr] extends object | |
// ? Subset<K[attr]> | |
// : K[attr] extends object | null | |
// ? Subset<K[attr]> | null | |
// : K[attr] extends object | null | undefined | |
// ? Subset<K[attr]> | null | undefined | |
// : K[attr] | |
// } | |
/** | |
* Hook that helps to keep state on objects using the classic this.setState style of function that class components had | |
* | |
* it takes an object as a parameter and you can update specific keys without spreading them yourself. | |
* | |
* `IMPORTANT` | |
*```markdown | |
* This hook is meant to be used with simple objects (`Record<string, string | number | boolean`) | |
* complex objects with nesting, arrays, functions or dates should be handled differently | |
*``` | |
* @param obj state object that will be tracked and updated | |
* @returns the object state and it's setter function just like `useState()` | |
*/ | |
export function useObjectState<T extends Record<string, unknown>>(obj: T) { | |
const [objectState, setObjectState] = useState(obj) | |
const setStateHandler = (objPartial: SetStateAction<Partial<T>>) => { | |
setObjectState((prev) => ({ ...prev, ...objPartial })) | |
} | |
return [objectState, setStateHandler] as const | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment