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 |
|
13 | import {Dispatch, MutableRefObject, useRef, useState} from 'react';
|
14 | import {useEffectEvent, useLayoutEffect} from './';
|
15 |
|
16 | type 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.
|
22 | export function useValueEffect<S>(defaultValue: S | (() => S)): [S, Dispatch<SetValueAction<S>>] {
|
23 | let [value, setValue] = useState(defaultValue);
|
24 | let effect: MutableRefObject<Generator<S> | null> = useRef<Generator<S> | null>(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 | if (!effect.current) {
|
30 | return;
|
31 | }
|
32 | // Run the generator to the next yield.
|
33 | let newValue = effect.current.next();
|
34 |
|
35 | // If the generator is done, reset the effect.
|
36 | if (newValue.done) {
|
37 | effect.current = null;
|
38 | return;
|
39 | }
|
40 |
|
41 | // If the value is the same as the current value,
|
42 | // then continue to the next yield. Otherwise,
|
43 | // set the value in state and wait for the next layout effect.
|
44 | if (value === newValue.value) {
|
45 | nextRef();
|
46 | } else {
|
47 | setValue(newValue.value);
|
48 | }
|
49 | });
|
50 |
|
51 | useLayoutEffect(() => {
|
52 | // If there is an effect currently running, continue to the next yield.
|
53 | if (effect.current) {
|
54 | nextRef();
|
55 | }
|
56 | });
|
57 |
|
58 | let queue = useEffectEvent(fn => {
|
59 | effect.current = fn(value);
|
60 | nextRef();
|
61 | });
|
62 |
|
63 | return [value, queue];
|
64 | }
|