UNPKG

1.36 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
4var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.default = useSyncState;
9var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
10var React = _interopRequireWildcard(require("react"));
11var _useEvent = _interopRequireDefault(require("./useEvent"));
12/**
13 * Same as React.useState but will always get latest state.
14 * This is useful when React merge multiple state updates into one.
15 * e.g. onTransitionEnd trigger multiple event at once will be merged state update in React.
16 */
17function useSyncState(defaultValue) {
18 var _React$useReducer = React.useReducer(function (x) {
19 return x + 1;
20 }, 0),
21 _React$useReducer2 = (0, _slicedToArray2.default)(_React$useReducer, 2),
22 forceUpdate = _React$useReducer2[1];
23 var currentValueRef = React.useRef(defaultValue);
24 var getValue = (0, _useEvent.default)(function () {
25 return currentValueRef.current;
26 });
27 var setValue = (0, _useEvent.default)(function (updater) {
28 currentValueRef.current = typeof updater === 'function' ? updater(currentValueRef.current) : updater;
29 forceUpdate();
30 });
31 return [getValue, setValue];
32}
\No newline at end of file