UNPKG

1.41 kBJavaScriptView Raw
1import * as React from "rehackt";
2import { useSyncExternalStore } from "./useSyncExternalStore.js";
3/**
4 * Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.
5 *
6 * @example
7 * ```jsx
8 * import { makeVar, useReactiveVar } from "@apollo/client";
9 * export const cartItemsVar = makeVar([]);
10 *
11 * export function Cart() {
12 * const cartItems = useReactiveVar(cartItemsVar);
13 * // ...
14 * }
15 * ```
16 * @since 3.2.0
17 * @param rv - A reactive variable.
18 * @returns The current value of the reactive variable.
19 */
20export function useReactiveVar(rv) {
21 return useSyncExternalStore(React.useCallback(function (update) {
22 // By reusing the same onNext function in the nested call to
23 // rv.onNextChange(onNext), we can keep using the initial clean-up function
24 // returned by rv.onNextChange(function onNext(v){...}), without having to
25 // register the new clean-up function (returned by the nested
26 // rv.onNextChange(onNext)) with yet another callback.
27 return rv.onNextChange(function onNext() {
28 update();
29 rv.onNextChange(onNext);
30 });
31 }, [rv]), rv, rv);
32}
33//# sourceMappingURL=useReactiveVar.js.map
\No newline at end of file