1.8.0 • Published 6 months ago

use-subscription v1.8.0

Weekly downloads
1,704,230
License
MIT
Repository
github
Last release
6 months ago

use-subscription

React hook that safely manages subscriptions in concurrent mode.

This utility can be used for subscriptions to a single value that are typically only read in one place and may update frequently (e.g. a component that subscribes to a geolocation API to show a dot on a map).

When should you NOT use this?

Most other cases have better long-term solutions:

  • Redux/Flux stores should use the context API instead.
  • I/O subscriptions (e.g. notifications) that update infrequently should use a mechanism like react-cache instead.
  • Complex libraries like Relay/Apollo should manage subscriptions manually with the same techniques which this library uses under the hood (as referenced here) in a way that is most optimized for their library usage.

Limitations in concurrent mode

use-subscription is safe to use in concurrent mode. However, it achieves correctness by sometimes de-opting to synchronous mode, obviating the benefits of concurrent rendering. This is an inherent limitation of storing state outside of React's managed state queue and rendering in response to a change event.

The effect of de-opting to sync mode is that the main thread may periodically be blocked (in the case of CPU-bound work), and placeholders may appear earlier than desired (in the case of IO-bound work).

For full compatibility with concurrent rendering, including both time-slicing and React Suspense, the suggested longer-term solution is to move to one of the patterns described in the previous section.

What types of subscriptions can this support?

This abstraction can handle a variety of subscription types, including:

  • Event dispatchers like HTMLInputElement.
  • Custom pub/sub components like Relay's FragmentSpecResolver.
  • Observable types like RxJS BehaviorSubject and ReplaySubject. (Types like RxJS Subject or Observable are not supported, because they provide no way to read the "current" value after it has been emitted.)

Note that JavaScript promises are also not supported because they provide no way to synchronously read the "current" value.

Installation

# Yarn
yarn add use-subscription

# NPM
npm install use-subscription

Usage

To configure a subscription, you must provide two methods: getCurrentValue and subscribe.

In order to avoid removing and re-adding subscriptions each time this hook is called, the parameters passed to this hook should be memoized. This can be done by wrapping the entire subscription with useMemo(), or by wrapping the individual callbacks with useCallback().

Subscribing to event dispatchers

Below is an example showing how use-subscription can be used to subscribe to event dispatchers such as DOM elements.

import React, { useMemo } from "react";
import { useSubscription } from "use-subscription";

// In this example, "input" is an event dispatcher (e.g. an HTMLInputElement)
// but it could be anything that emits an event and has a readable current value.
function Example({ input }) {

  // Memoize to avoid removing and re-adding subscriptions each time this hook is called.
  const subscription = useMemo(
    () => ({
      getCurrentValue: () => input.value,
      subscribe: callback => {
        input.addEventListener("change", callback);
        return () => input.removeEventListener("change", callback);
      }
    }),

    // Re-subscribe any time our input changes
    // (e.g. we get a new HTMLInputElement prop to subscribe to)
    [input]
  );

  // The value returned by this hook reflects the input's current value.
  // Our component will automatically be re-rendered when that value changes.
  const value = useSubscription(subscription);

  // Your rendered output goes here ...
}

Subscribing to observables

Below are examples showing how use-subscription can be used to subscribe to certain types of observables (e.g. RxJS BehaviorSubject and ReplaySubject).

Note that it is not possible to support all observable types (e.g. RxJS Subject or Observable) because some provide no way to read the "current" value after it has been emitted.

BehaviorSubject

const subscription = useMemo(
  () => ({
    getCurrentValue: () => behaviorSubject.getValue(),
    subscribe: callback => {
      const subscription = behaviorSubject.subscribe(callback);
      return () => subscription.unsubscribe();
    }
  }),

  // Re-subscribe any time the behaviorSubject changes
  [behaviorSubject]
);

const value = useSubscription(subscription);

ReplaySubject

const subscription = useMemo(
  () => ({
    getCurrentValue: () => {
      let currentValue;
      // ReplaySubject does not have a sync data getter,
      // So we need to temporarily subscribe to retrieve the most recent value.
      replaySubject
        .subscribe(value => {
          currentValue = value;
        })
        .unsubscribe();
      return currentValue;
    },
    subscribe: callback => {
      const subscription = replaySubject.subscribe(callback);
      return () => subscription.unsubscribe();
    }
  }),

  // Re-subscribe any time the replaySubject changes
  [replaySubject]
);

const value = useSubscription(subscription);
@wouterds/react-native-tvos@dxos/react-clientreact-native-bluetooth2react-native-for-sanbotaerolito-nextnext-sheertexreact-native-template-rfbaseairscanairscan-examplereact-native-esc-pos-sahaab@borisovart/atol-kkt-modulecodeforte-nextdeneme323112@ntt_app/react-native-custom-notificationreact-native-custom-text-hwjamesreact-native-savvreact-native-covid-sdkreact-native-printer-brothersreact-native-shekhar-bridge-testcogoportutilsreact-native-wegowilscanner@oiti/documentoscopy-react-nativereact-native-slider-kf@everything-registry/sub-chunk-3028@shuvi/platform-web-reactreact-native-badge-controlreact-native-bubble-chartreact-native-create-video-thumbnailreact-native-cplusreact-native-arun-ramya-testreact-native-arunjeyam1987react-native-arunmeena1987react-native-arunramya151react-multi-providereact-native-appearancereact-native-biometric-authenticatereact-native-contact-listserhiipalash-nextreact-native-innity-2react-native-innity-remasterreact-native-plugpag-wrapperreact-native-sfreact-native-remote-cloverreact-native-okhttp-forkreact-native-payu-payment-testingreact-native-responsive-sizereact-native-sayhello-modulereact-native-flyyreact-native-dishreact-native-expendable-viewreact-native-dm-playerreact-native-dsphoto-modulereact-native-firebase-messagingreact-native-kakao-mapsreact-native-jsi-device-inforeact-native-xprinter-thermal-blereact-native-wtfreact-pouchdbreact-native-android-scoped-storagereact-native-aventonfacetec-aventonreact-native-pulsator-nativereact-native-ytximkitreact-native-hlf-wrapperreact-native-modal-progress-bar@damian.lnc/core@damruravihara/react-native-testing-package@divmain/nextreductiveruxdreact-warehousern-adyen-dropinrn-flatlist-forkrn-my-libraryrn-session-multiplier-demorn-tm-notifyrn-use-modal-hookspirokit-native-basereact-native-testwebreact-native-is7react-native-my-first-try-arun-ramyareact-native-library-testing-422522react-native-teads-sdk-modulereact-native-transtracker-libraryreact-native-trackierreact-native-tvos-nzreact-native-test-module-hhh@classyllama/code-style@symph/joy@con-test/react-native-concent-commonpulsar-player-controller@corelmax/react-native-my2c2p-sdk@buscojobs/next@blkmarketco/components-librarypayutesting@apardellass/react-native-audio-streamnuxusbn-react-nativeraact-native-arunramya151@docler/next
1.8.0

2 years ago

1.7.0

2 years ago

1.6.0

2 years ago

1.6.0-rc.3

2 years ago

1.6.0-rc.2

2 years ago

1.6.0-rc.1

2 years ago

1.6.0-rc.0

2 years ago

0.0.0-d75105fa9

3 years ago

0.0.0-0eea57724

3 years ago

0.0.0-3c2341416

3 years ago

0.0.0-44cdfd6b7

3 years ago

0.0.0-46926993f

3 years ago

0.0.0-28625c6f4

3 years ago

0.0.0-a8964649b

3 years ago

0.0.0-cc4d24ab0

3 years ago

0.0.0-76f85b3e5

3 years ago

0.0.0-bb1c82155

3 years ago

0.0.0-3f8f4675d

3 years ago

0.0.0-2bf4805e4

3 years ago

0.0.0-bd070eb2c

3 years ago

0.0.0-8ea11306a

3 years ago

0.0.0-d1542de3a

3 years ago

0.0.0-b8fda6cab

3 years ago

0.0.0-46491dce9

3 years ago

0.0.0-79740da4c

3 years ago

0.0.0-2d8d133e1

3 years ago

0.0.0-269dd6ec5

3 years ago

0.0.0-51ebccc37

3 years ago

0.0.0-459c34fde

3 years ago

0.0.0-709f94841

3 years ago

0.0.0-af1a4cbf7

3 years ago

0.0.0-63927e084

3 years ago

0.0.0-89847bf6e

3 years ago

0.0.0-78120032d

3 years ago

0.0.0-57768ef90

3 years ago

0.0.0-1a2d79250

3 years ago

0.0.0-a15586001

3 years ago

0.0.0-3890fb52f

3 years ago

0.0.0-132b72d7b

3 years ago

0.0.0-48740429b

3 years ago

0.0.0-5027eb465

3 years ago

0.0.0-11b07597e

3 years ago

0.0.0-ea155e226

3 years ago

0.0.0-84c06fef8

3 years ago

0.0.0-9d48779b3

3 years ago

0.0.0-bdc23c3db

3 years ago

0.0.0-1214b302e

3 years ago

0.0.0-172e89b4b

3 years ago

0.0.0-ee6a05c2b

3 years ago

0.0.0-a817840ea

3 years ago

0.0.0-b4f119cdf

3 years ago

0.0.0-2c9fef32d

3 years ago

0.0.0-b48b38af6

3 years ago

0.0.0-634cc52e6

3 years ago

0.0.0-a77dd13ed

3 years ago

0.0.0-6a589ad71

3 years ago

0.0.0-7b84dbd16

3 years ago

0.0.0-12adaffef

3 years ago

0.0.0-1fafac002

3 years ago

0.0.0-7d06b80af

3 years ago

0.0.0-25bfa287f

3 years ago

0.0.0-3fb11eed9

3 years ago

0.0.0-0203b6567

3 years ago

0.0.0-825c3021f

3 years ago

0.0.0-00d4f95c2

3 years ago

0.0.0-10cc40018

3 years ago

0.0.0-bd245c1ba

3 years ago

0.0.0-73e900b0e

3 years ago

0.0.0-5fe091c77

3 years ago

0.0.0-ec372faef

3 years ago

0.0.0-ee4326357

3 years ago

0.0.0-d857f9e4d

3 years ago

0.0.0-553440bd1

3 years ago

0.0.0-9209c30ff

3 years ago

0.0.0-4190a3458

3 years ago

0.0.0-0cf9fc10b

3 years ago

0.0.0-8af27aeed

3 years ago

0.0.0-af3d52611

3 years ago

0.0.0-e2fd460cc

3 years ago

0.0.0-6f8843837

3 years ago

0.0.0-1a7472624

3 years ago

0.0.0-696e736be

3 years ago

0.0.0-483358c38

3 years ago

0.0.0-3b870b1e0

3 years ago

0.0.0-6c526c515

3 years ago

0.0.0-bbb2ba8c8

3 years ago

0.0.0-4e08fb10c

3 years ago

0.0.0-a703c3f7e

3 years ago

0.0.0-4c019585e

3 years ago

0.0.0-0935a1db3

3 years ago

0.0.0-dc27b5aaa

3 years ago

1.5.1

3 years ago

0.0.0-8e5adfbd7

3 years ago

1.5.0

3 years ago

0.0.0-4ead6b530

4 years ago

1.5.0-rc.3

4 years ago

1.5.0-rc.2

4 years ago

0.0.0-3834174dd

4 years ago

1.5.0-rc.1

4 years ago

0.0.0-4e6999103

4 years ago

1.5.0-rc.0

4 years ago

0.0.0-94c0244ba

4 years ago

0.0.0-f77c7b9d7

4 years ago

0.0.0-3d0895557

4 years ago

0.0.0-7f28234f8

4 years ago

0.0.0-33c3af284

4 years ago

0.0.0-d7382b6c4

4 years ago

1.4.1

4 years ago

0.0.0-da834083c

4 years ago

0.0.0-235a6c4af

4 years ago

1.4.0

4 years ago

0.0.0-d28bd2994

4 years ago

0.0.0-8d7535e54

4 years ago

0.0.0-5de5b6150

4 years ago

0.0.0-ea6ed3dbb

4 years ago

0.0.0-241c4467e

4 years ago

0.0.0-57333ca33

4 years ago

0.0.0-f42431abe

4 years ago

1.3.0

4 years ago

0.0.0-b53ea6ca0

4 years ago

0.0.0-38dd17ab9

4 years ago

0.0.0-f6b8d31a7

4 years ago

1.2.0

4 years ago

0.0.0-5faf377df

4 years ago

0.0.0-1022ee0ec

4 years ago

0.0.0-7082d5a2d

5 years ago

1.1.2

5 years ago

0.0.0-4ab6305f6

5 years ago

1.1.1

5 years ago

0.0.0-d346d9208

5 years ago

1.1.0

5 years ago

0.0.0-3694a3b5e

5 years ago

0.0.0-b4b8a349a

5 years ago

0.0.0-45b6443c9

5 years ago

1.0.0

5 years ago

0.0.0-8d5403877

5 years ago

0.0.0

5 years ago