main
js 30 lines 1.05 KB
Raw
1 /**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 *
7 * @flow
8 */
9
10 import {useSyncExternalStore} from 'use-sync-external-store/shim';
11
12 // Hook used for safely managing subscriptions in concurrent mode.
13 //
14 // In order to avoid removing and re-adding subscriptions each time this hook is called,
15 // the parameters passed to this hook should be memoized in some way–
16 // either by wrapping the entire params object with useMemo()
17 // or by wrapping the individual callbacks with useCallback().
18 export function useSubscription<Value>({
19 // (Synchronously) returns the current value of our subscription.
20 getCurrentValue,
21
22 // This function is passed an event handler to attach to the subscription.
23 // It should return an unsubscribe function that removes the handler.
24 subscribe,
25 }: {
26 getCurrentValue: () => Value,
27 subscribe: (callback: Function) => () => void,
28 }): Value {
29 return useSyncExternalStore(subscribe, getCurrentValue);
30 }