-
Notifications
You must be signed in to change notification settings - Fork 0
/
useNullableState.ts
53 lines (52 loc) · 1.32 KB
/
useNullableState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import * as React from 'react'
/**
* This function is a react hook for state of type of your choosing. It comes
* with two memoized functions, one for setting state and one for clearing it.
*
* The items returned in the array can be destructured and named whatever you
* like:
*
* ```js
* import { useNullableState } from '@oneblink/apps-react'
*
* const startingProfile = {
* name: 'Forest Gump',
* profession: 'Military, Athlete, Other',
* }
*
* const [userProfile, setUserProfile, unsetUserProfile] =
* useBooleanState(startingProfile)
* ```
*
* `setUserProfile` can then be called with an object of type `T` like:
*
* ```js
* setUserProfile({
* name: 'Walter White',
* profession: 'Chemistry Teacher (Secondary School), Other',
* })
* ```
*
* And `unsetUserProfile` can be called like:
*
* ```js
* unsetUserProfile()
* ```
*
* @typeParam T The type of the state
* @param defaultValue
* @returns
* @group Hooks
*/
export default function useNullableState<T>(
/** The starting state for the hook. */
defaultValue: T | null,
): [
state: T | null,
setState: React.Dispatch<React.SetStateAction<T | null>>,
clearState: () => void,
] {
const [state, setState] = React.useState(defaultValue)
const unsetState = React.useCallback(() => setState(null), [])
return [state, setState, unsetState]
}