Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
use-subscription
Advanced tools
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.
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>;
}
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 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 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.
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).
Most other cases have better long-term solutions:
react-cache
instead.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.
This abstraction can handle a variety of subscription types, including:
HTMLInputElement
.FragmentSpecResolver
.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.
# Yarn
yarn add use-subscription
# NPM
npm install use-subscription
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()
.
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 ...
}
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);
FAQs
Reusable hooks
The npm package use-subscription receives a total of 551,500 weekly downloads. As such, use-subscription popularity was classified as popular.
We found that use-subscription demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.