UNPKG

2.21 kBPlain TextView Raw
1/*
2 * Copyright 2020 Adobe. All rights reserved.
3 * This file is licensed to you under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License. You may obtain a copy
5 * of the License at http://www.apache.org/licenses/LICENSE-2.0
6 *
7 * Unless required by applicable law or agreed to in writing, software distributed under
8 * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
9 * OF ANY KIND, either express or implied. See the License for the specific language
10 * governing permissions and limitations under the License.
11 */
12
13import {Dispatch, useRef, useState} from 'react';
14import {useEffectEvent, useLayoutEffect} from './';
15
16type SetValueAction<S> = (prev: S) => Generator<any, void, unknown>;
17
18// This hook works like `useState`, but when setting the value, you pass a generator function
19// that can yield multiple values. Each yielded value updates the state and waits for the next
20// layout effect, then continues the generator. This allows sequential updates to state to be
21// written linearly.
22export function useValueEffect<S>(defaultValue: S | (() => S)): [S, Dispatch<SetValueAction<S>>] {
23 let [value, setValue] = useState(defaultValue);
24 let effect = useRef(null);
25
26 // Store the function in a ref so we can always access the current version
27 // which has the proper `value` in scope.
28 let nextRef = useEffectEvent(() => {
29 // Run the generator to the next yield.
30 let newValue = effect.current.next();
31
32 // If the generator is done, reset the effect.
33 if (newValue.done) {
34 effect.current = null;
35 return;
36 }
37
38 // If the value is the same as the current value,
39 // then continue to the next yield. Otherwise,
40 // set the value in state and wait for the next layout effect.
41 if (value === newValue.value) {
42 nextRef();
43 } else {
44 setValue(newValue.value);
45 }
46 });
47
48 useLayoutEffect(() => {
49 // If there is an effect currently running, continue to the next yield.
50 if (effect.current) {
51 nextRef();
52 }
53 });
54
55 let queue = useEffectEvent(fn => {
56 effect.current = fn(value);
57 nextRef();
58 });
59
60 return [value, queue];
61}