Created
November 20, 2020 16:00
-
-
Save bmingles/097ab8f164a9f75307d9de603ddef495 to your computer and use it in GitHub Desktop.
Custom React hook for setting properties
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 React from 'react' | |
| /** | |
| * Custom hook to set single properties on state objects. | |
| * | |
| * e.g. | |
| * const [state, setState] = useState({ name: 'John Doe' }) | |
| * const setProp = useSetProp(setState) | |
| * | |
| * const setName = setProp('name') | |
| * setName('Jane Doe') | |
| */ | |
| export function useSetProp<T>(setter: (callback: (t: T) => T) => void) { | |
| return React.useCallback( | |
| <K extends keyof T>(prop: K) => { | |
| return (value: T[K]) => { | |
| setter((t) => ({ ...t, [prop]: value })) | |
| } | |
| }, | |
| [setter] | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment