2023-02-16 05:20:58 +08:00
|
|
|
/*
|
2024-09-06 16:22:13 +08:00
|
|
|
Copyright 2023, 2024 New Vector Ltd.
|
2023-02-16 05:20:58 +08:00
|
|
|
|
2024-09-06 16:22:13 +08:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
Please see LICENSE in the repository root for full details.
|
2023-02-16 05:20:58 +08:00
|
|
|
*/
|
|
|
|
|
2023-01-25 15:30:52 +08:00
|
|
|
import {
|
|
|
|
DependencyList,
|
|
|
|
Dispatch,
|
|
|
|
SetStateAction,
|
|
|
|
useCallback,
|
|
|
|
useRef,
|
|
|
|
useState,
|
|
|
|
} from "react";
|
|
|
|
|
2023-02-16 05:38:49 +08:00
|
|
|
/**
|
|
|
|
* Hook creating a stateful value that updates automatically whenever the
|
|
|
|
* dependencies change. Or equivalently, a version of useMemo that takes its own
|
|
|
|
* previous value as an input, and can be updated manually.
|
|
|
|
*/
|
2023-01-25 15:30:52 +08:00
|
|
|
export const useReactiveState = <T>(
|
|
|
|
updateFn: (prevState?: T) => T,
|
2023-10-11 22:42:04 +08:00
|
|
|
deps: DependencyList,
|
2023-01-25 15:30:52 +08:00
|
|
|
): [T, Dispatch<SetStateAction<T>>] => {
|
|
|
|
const state = useRef<T>();
|
|
|
|
if (state.current === undefined) state.current = updateFn();
|
|
|
|
const prevDeps = useRef<DependencyList>();
|
|
|
|
|
|
|
|
// Since we store the state in a ref, we use this counter to force an update
|
|
|
|
// when someone calls setState
|
|
|
|
const [, setNumUpdates] = useState(0);
|
|
|
|
|
|
|
|
// If this is the first render or the deps have changed, recalculate the state
|
|
|
|
if (
|
|
|
|
prevDeps.current === undefined ||
|
|
|
|
deps.length !== prevDeps.current.length ||
|
2024-07-13 02:01:32 +08:00
|
|
|
// Deps might be NaN, so we compare with Object.is rather than ===
|
2024-05-03 06:44:36 +08:00
|
|
|
deps.some((d, i) => !Object.is(d, prevDeps.current![i]))
|
2023-01-25 15:30:52 +08:00
|
|
|
) {
|
|
|
|
state.current = updateFn(state.current);
|
|
|
|
}
|
|
|
|
prevDeps.current = deps;
|
|
|
|
|
|
|
|
return [
|
|
|
|
state.current,
|
|
|
|
useCallback(
|
|
|
|
(action) => {
|
|
|
|
if (typeof action === "function") {
|
|
|
|
state.current = (action as (prevValue: T) => T)(state.current!);
|
|
|
|
} else {
|
|
|
|
state.current = action;
|
|
|
|
}
|
|
|
|
setNumUpdates((n) => n + 1); // Force an update
|
|
|
|
},
|
2023-10-11 22:42:04 +08:00
|
|
|
[setNumUpdates],
|
2023-01-25 15:30:52 +08:00
|
|
|
),
|
|
|
|
];
|
|
|
|
};
|