-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathindex.ts
25 lines (20 loc) · 871 Bytes
/
index.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
import {type Dispatch, type SetStateAction, useState} from 'react';
import {useRafCallback} from '../useRafCallback/index.js';
import {useUnmountEffect} from '../useUnmountEffect/index.js';
export function useRafState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
export function useRafState<S = undefined>(): [
S | undefined,
Dispatch<SetStateAction<S | undefined>>,
];
/**
* Like `React.useState`, but state is only updated within animation frame.
*/
export function useRafState<S>(
initialState?: S | (() => S),
): [S | undefined, Dispatch<SetStateAction<S>>] {
// eslint-disable-next-line react/hook-use-state
const [state, innerSetState] = useState<S | undefined>(initialState);
const [setState, cancelRaf] = useRafCallback(innerSetState);
useUnmountEffect(cancelRaf);
return [state, setState as Dispatch<SetStateAction<S>>];
}