UNPKG

2.34 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, useCallback, useRef, useState} from 'react';
14import {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 valueRef = useRef(value);
25 let effect = useRef(null);
26
27 valueRef.current = value;
28
29 // Store the function in a ref so we can always access the current version
30 // which has the proper `value` in scope.
31 let nextRef = useRef(null);
32 nextRef.current = () => {
33 // Run the generator to the next yield.
34 let newValue = effect.current.next();
35
36 // If the generator is done, reset the effect.
37 if (newValue.done) {
38 effect.current = null;
39 return;
40 }
41
42 // If the value is the same as the current value,
43 // then continue to the next yield. Otherwise,
44 // set the value in state and wait for the next layout effect.
45 if (value === newValue.value) {
46 nextRef.current();
47 } else {
48 setValue(newValue.value);
49 }
50 };
51
52 useLayoutEffect(() => {
53 // If there is an effect currently running, continue to the next yield.
54 if (effect.current) {
55 nextRef.current();
56 }
57 });
58
59 let queue = useCallback(fn => {
60 effect.current = fn(valueRef.current);
61 nextRef.current();
62 }, [effect, nextRef]);
63
64 return [value, queue];
65}