-
Notifications
You must be signed in to change notification settings - Fork 0
/
useStateCallback.ts
42 lines (31 loc) · 983 Bytes
/
useStateCallback.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
import { useCallback, useState } from 'react'
import type { Dispatch, SetStateAction } from 'react'
// --
type StateToggleInitial<T> = T | (() => T)
type StateToggleTuple<T> = [T, Dispatch<SetStateAction<T>>]
// --
/**
* Combines the {@link useCallback} and {@link useState} hooks, returning a tuple containing a stateful value and a setter which will trigger the passed `callback` whenever called.
*
* @param callback A `Function` which is triggered whenever the returned setter is triggered.
* @param initial The initial value the stateful value should be set to.
*/
const useStateCallback = <T = unknown>(
callback: (val: T) => void,
initial?: StateToggleInitial<T>
): StateToggleTuple<T> => {
//
const [state, _setState] = useState<T>(initial)
// --
const setState = useCallback(
(val: T) => {
callback(val)
_setState(val)
},
[callback, _setState]
)
// --
return [state, setState]
}
// --
export default useStateCallback