What is use-subscription?
The use-subscription npm package is a React hook that allows you to subscribe to external data sources and automatically re-render your component when the data changes. It is particularly useful for integrating with state management libraries or any other data sources that can change over time.
What are use-subscription's main functionalities?
Basic Subscription
This feature allows you to create a basic subscription to an external data source. The `useSubscription` hook takes a subscription object with `getCurrentValue` and `subscribe` methods. The component will re-render whenever the data source changes.
const { useSubscription } = require('use-subscription');
const mySubscription = {
getCurrentValue: () => myDataSource.getCurrentValue(),
subscribe: (callback) => {
myDataSource.subscribe(callback);
return () => myDataSource.unsubscribe(callback);
}
};
function MyComponent() {
const value = useSubscription(mySubscription);
return <div>{value}</div>;
}
Subscription with Cleanup
This feature demonstrates how to use the `useSubscription` hook with a cleanup function. The `useEffect` hook is used to perform cleanup when the component unmounts, ensuring that any resources are properly released.
const { useSubscription } = require('use-subscription');
const mySubscription = {
getCurrentValue: () => myDataSource.getCurrentValue(),
subscribe: (callback) => {
myDataSource.subscribe(callback);
return () => myDataSource.unsubscribe(callback);
}
};
function MyComponent() {
const value = useSubscription(mySubscription);
React.useEffect(() => {
return () => {
myDataSource.cleanup();
};
}, []);
return <div>{value}</div>;
}
Other packages similar to use-subscription
react-use
The react-use package is a collection of essential React hooks, including hooks for subscriptions. It offers a broader range of hooks compared to use-subscription, making it a more versatile choice for developers who need multiple hooks in their projects.
recoil
Recoil is a state management library for React that provides a way to manage global state and subscriptions. It offers more advanced state management capabilities compared to use-subscription, making it suitable for larger applications with complex state requirements.
zustand
Zustand is a small, fast, and scalable state management solution for React. It provides a simple API for creating and subscribing to state, similar to use-subscription, but with additional features for state management and middleware support.
use-subscription
React Hook for subscribing to external data sources.
You may now migrate to use-sync-external-store
directly instead, which has the same API as React.useSyncExternalStore
. The use-subscription
package is now a thin wrapper over use-sync-external-store
and will not be updated further.
Installation
yarn add use-subscription
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";
function Example({ input }) {
const subscription = useMemo(
() => ({
getCurrentValue: () => input.value,
subscribe: callback => {
input.addEventListener("change", callback);
return () => input.removeEventListener("change", callback);
}
}),
[input]
);
const value = useSubscription(subscription);
}
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();
}
}),
[behaviorSubject]
);
const value = useSubscription(subscription);
ReplaySubject
const subscription = useMemo(
() => ({
getCurrentValue: () => {
let currentValue;
replaySubject
.subscribe(value => {
currentValue = value;
})
.unsubscribe();
return currentValue;
},
subscribe: callback => {
const subscription = replaySubject.subscribe(callback);
return () => subscription.unsubscribe();
}
}),
[replaySubject]
);
const value = useSubscription(subscription);