UNPKG

2.92 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 // Must be stable so that `queue` is stable.
28 let nextIter = useCallback(() => {
29 // Run the generator to the next yield.
30 let newValue = effect.current.next();
31 while (!newValue.done && valueRef.current === newValue.value) {
32 // If the value is the same as the current value,
33 // then continue to the next yield. Otherwise,
34 // set the value in state and wait for the next layout effect.
35 newValue = effect.current.next();
36 }
37 // If the generator is done, reset the effect.
38 if (newValue.done) {
39 effect.current = null;
40 return;
41 }
42
43 // Always update valueRef when setting the state.
44 // This is needed because the function is not regenerated with the new state value since
45 // they must be stable across renders. Instead, it gets carried in the ref, but the setState
46 // is also needed in order to cause a rerender.
47 setValue(newValue.value);
48 valueRef.current = newValue.value;
49 // this list of dependencies is stable, setState and refs never change after first render.
50 }, [setValue, valueRef, effect]);
51
52 useLayoutEffect(() => {
53 // If there is an effect currently running, continue to the next yield.
54 if (effect.current) {
55 nextIter();
56 }
57 });
58
59 // queue must be a stable function, much like setState.
60 let queue = useCallback(fn => {
61 effect.current = fn(valueRef.current);
62 nextIter();
63 // this list of dependencies is stable, setState and refs never change after first render.
64 // in addition, nextIter is stable as outlined above
65 }, [nextIter, effect, valueRef]);
66
67 return [value, queue];
68}