UNPKG

957 BJavaScriptView Raw
1import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
2import * as React from 'react';
3import useEvent from "./useEvent";
4/**
5 * Same as React.useState but will always get latest state.
6 * This is useful when React merge multiple state updates into one.
7 * e.g. onTransitionEnd trigger multiple event at once will be merged state update in React.
8 */
9export default function useSyncState(defaultValue) {
10 var _React$useReducer = React.useReducer(function (x) {
11 return x + 1;
12 }, 0),
13 _React$useReducer2 = _slicedToArray(_React$useReducer, 2),
14 forceUpdate = _React$useReducer2[1];
15 var currentValueRef = React.useRef(defaultValue);
16 var getValue = useEvent(function () {
17 return currentValueRef.current;
18 });
19 var setValue = useEvent(function (updater) {
20 currentValueRef.current = typeof updater === 'function' ? updater(currentValueRef.current) : updater;
21 forceUpdate();
22 });
23 return [getValue, setValue];
24}
\No newline at end of file