Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
create-subscription
Advanced tools
utility for subscribing to external data sources inside React components
create-subscription
is a utility for subscribing to external data sources inside React components. It is officially supported and maintained by the React team.
This utility should 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).
Other cases have better long-term solutions:
react-cache
instead.The main motivation for create-subscription
is to provide a way for library authors to ensure compatibility with React's upcoming asynchronous rendering mode. create-subscription
guarantees correctness in async mode, accounting for the subtle bugs and edge cases that a library author might otherwise miss.
However, it achieves correctness by sometimes de-opting to synchronous mode, obviating the benefits of async 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 asynchronous 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.)# Yarn
yarn add create-subscription
# NPM
npm install create-subscription
To configure a subscription, you must provide two methods: getCurrentValue
and subscribe
.
import { createSubscription } from "create-subscription";
const Subscription = createSubscription({
getCurrentValue(source) {
// Return the current value of the subscription (source),
// or `undefined` if the value can't be read synchronously (e.g. native Promises).
},
subscribe(source, callback) {
// Subscribe (e.g. add an event listener) to the subscription (source).
// Call callback(newValue) whenever a subscription changes.
// Return an unsubscribe method,
// Or a no-op if unsubscribe is not supported (e.g. native Promises).
}
});
To use the Subscription
component, pass the subscribable property (e.g. an event dispatcher, observable) as the source
property and use a render prop, children
, to handle the subscribed value when it changes:
<Subscription source={eventDispatcher}>
{value => <AnotherComponent value={value} />}
</Subscription>
This API can be used to subscribe to a variety of "subscribable" sources, from event dispatchers to RxJS observables. Below are a few examples of how to subscribe to common types.
Below is an example showing how create-subscription
can be used to subscribe to event dispatchers such as DOM elements.
import React from "react";
import { createSubscription } from "create-subscription";
// Start with a simple component.
// In this case, it's a function component, but it could have been a class.
function FollowerComponent({ followersCount }) {
return <div>You have {followersCount} followers!</div>;
}
// Create a wrapper component to manage the subscription.
const EventHandlerSubscription = createSubscription({
getCurrentValue: eventDispatcher => eventDispatcher.value,
subscribe: (eventDispatcher, callback) => {
const onChange = event => callback(eventDispatcher.value);
eventDispatcher.addEventListener("change", onChange);
return () => eventDispatcher.removeEventListener("change", onChange);
}
});
// Your component can now be used as shown below.
// In this example, 'eventDispatcher' represents a generic event dispatcher.
<EventHandlerSubscription source={eventDispatcher}>
{value => <FollowerComponent followersCount={value} />}
</EventHandlerSubscription>;
Below are examples showing how create-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 BehaviorSubscription = createSubscription({
getCurrentValue: behaviorSubject => behaviorSubject.getValue(),
subscribe: (behaviorSubject, callback) => {
const subscription = behaviorSubject.subscribe(callback);
return () => subscription.unsubscribe();
}
});
ReplaySubject
const ReplaySubscription = createSubscription({
getCurrentValue: replaySubject => {
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: (replaySubject, callback) => {
const subscription = replaySubject.subscribe(callback);
return () => subscription.unsubscribe();
}
});
Below is an example showing how create-subscription
can be used with native Promises.
Note that an initial render value of undefined
is unavoidable due to the fact that Promises provide no way to synchronously read their current value.
Note the lack of a way to "unsubscribe" from a Promise can result in memory leaks as long as something has a reference to the Promise. This should be taken into consideration when determining whether Promises are appropriate to use in this way within your application.
import React from "react";
import { createSubscription } from "create-subscription";
// Start with a simple component.
function LoadingComponent({ loadingStatus }) {
if (loadingStatus === undefined) {
// Loading
} else if (loadingStatus === null) {
// Error
} else {
// Success
}
}
// Wrap the function component with a subscriber HOC.
// This HOC will manage subscriptions and pass values to the decorated component.
// It will add and remove subscriptions in an async-safe way when props change.
const PromiseSubscription = createSubscription({
getCurrentValue: promise => {
// There is no way to synchronously read a Promise's value,
// So this method should return undefined.
return undefined;
},
subscribe: (promise, callback) => {
promise.then(
// Success
value => callback(value),
// Failure
() => callback(null)
);
// There is no way to "unsubscribe" from a Promise.
// create-subscription will still prevent stale values from rendering.
return () => {};
}
});
// Your component can now be used as shown below.
<PromiseSubscription source={loadingPromise}>
{loadingStatus => <LoadingComponent loadingStatus={loadingStatus} />}
</PromiseSubscription>
18.0.0 (March 29, 2022)
Below is a list of all new features, APIs, deprecations, and breaking changes. Read React 18 release post and React 18 upgrade guide for more information.
useId
is a new hook for generating unique IDs on both the client and server, while avoiding hydration mismatches. It is primarily useful for component libraries integrating with accessibility APIs that require unique IDs. This solves an issue that already exists in React 17 and below, but it’s even more important in React 18 because of how the new streaming server renderer delivers HTML out-of-order.startTransition
and useTransition
let you mark some state updates as not urgent. Other state updates are considered urgent by default. React will allow urgent state updates (for example, updating a text input) to interrupt non-urgent state updates (for example, rendering a list of search results).useDeferredValue
lets you defer re-rendering a non-urgent part of the tree. It is similar to debouncing, but has a few advantages compared to it. There is no fixed time delay, so React will attempt the deferred render right after the first render is reflected on the screen. The deferred render is interruptible and doesn't block user input.useSyncExternalStore
is a new hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. It removes the need for useEffect
when implementing subscriptions to external data sources, and is recommended for any library that integrates with state external to React.useInsertionEffect
is a new hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you’ve already built a CSS-in-JS library we don’t expect you to ever use this. This hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout.These new APIs are now exported from react-dom/client
:
createRoot
: New method to create a root to render
or unmount
. Use it instead of ReactDOM.render
. New features in React 18 don't work without it.hydrateRoot
: New method to hydrate a server rendered application. Use it instead of ReactDOM.hydrate
in conjunction with the new React DOM Server APIs. New features in React 18 don't work without it.Both createRoot
and hydrateRoot
accept a new option called onRecoverableError
in case you want to be notified when React recovers from errors during rendering or hydration for logging. By default, React will use reportError
, or console.error
in the older browsers.
These new APIs are now exported from react-dom/server
and have full support for streaming Suspense on the server:
renderToPipeableStream
: for streaming in Node environments.renderToReadableStream
: for modern edge runtime environments, such as Deno and Cloudflare workers.The existing renderToString
method keeps working but is discouraged.
react-dom
: ReactDOM.render
has been deprecated. Using it will warn and run your app in React 17 mode.react-dom
: ReactDOM.hydrate
has been deprecated. Using it will warn and run your app in React 17 mode.react-dom
: ReactDOM.unmountComponentAtNode
has been deprecated.react-dom
: ReactDOM.renderSubtreeIntoContainer
has been deprecated.react-dom/server
: ReactDOMServer.renderToNodeStream
has been deprecated.flushSync
.<Suspense>
boundary in the tree. This ensures the hydrated tree is consistent and avoids potential privacy and security holes that can be caused by hydration mismatches.Promise
, Symbol
, and Object.assign
. If you support older browsers and devices such as Internet Explorer which do not provide modern browser features natively or have non-compliant implementations, consider including a global polyfill in your bundled application.scheduler/tracing
APIundefined
: React no longer throws if you return undefined
from a component. This makes the allowed component return values consistent with values that are allowed in the middle of a component tree. We suggest to use a linter to prevent mistakes like forgetting a return
statement before JSX.act
warnings are now opt-in: If you're running end-to-end tests, the act
warnings are unnecessary. We've introduced an opt-in mechanism so you can enable them only for unit tests where they are useful and beneficial.setState
on unmounted components: Previously, React warned about memory leaks when you call setState
on an unmounted component. This warning was added for subscriptions, but people primarily run into it in scenarios where setting state is fine, and workarounds make the code worse. We've removed this warning.renderToString
: Will no longer error when suspending on the server. Instead, it will emit the fallback HTML for the closest <Suspense>
boundary and then retry rendering the same content on the client. It is still recommended that you switch to a streaming API like renderToPipeableStream
or renderToReadableStream
instead.renderToStaticMarkup
: Will no longer error when suspending on the server. Instead, it will emit the fallback HTML for the closest <Suspense>
boundary and retry rendering on the client.useTransition
and useDeferredValue
to separate urgent updates from transitions. (#10426, #10715, #15593, #15272, #15578, #15769, #17058, #18796, #19121, #19703, #19719, #19724, #20672, #20976 by @acdlite, @lunaruan, @rickhanlonii, and @sebmarkbage)useId
for generating unique IDs. (#17322, #18576, #22644, #22672, #21260 by @acdlite, @lunaruan, and @sebmarkbage)useSyncExternalStore
to help external store libraries integrate with React. (#15022, #18000, #18771, #22211, #22292, #22239, #22347, #23150 by @acdlite, @bvaughn, and @drarmstr)startTransition
as a version of useTransition
without pending feedback. (#19696 by @rickhanlonii)useInsertionEffect
for CSS-in-JS libraries. (#21913 by @rickhanlonii)<StrictMode>
re-run effects to check for restorable state. (#19523 , #21418 by @bvaughn and @lunaruan)object-assign
polyfill. (#23351 by @sebmarkbage)unstable_changedBits
API. (#20953 by @acdlite)useEffect
resulting from discrete events like clicks synchronously. (#21150 by @acdlite)fallback={undefined}
now behaves the same as null
and isn't ignored. (#21854 by @rickhanlonii)lazy()
resolving to the same component equivalent. (#20357 by @sebmarkbage)setImmediate
when available over MessageChannel
. (#20834 by @gaearon)useReducer
observing incorrect props by removing the eager bailout mechanism. (#22445 by @josephsavona)setState
being ignored in Safari when appending iframes. (#23111 by @gaearon)ZonedDateTime
in the tree. (#20617 by @dimaqq)null
in tests. (#22695 by @SimenB)onLoad
not triggering when concurrent features are on. (#23316 by @gnoff)NaN
. (#23333 by @hachibeeDI)package.json
as one of the entry points. (#22954 by @Jack)createRoot
and hydrateRoot
. (#10239, #11225, #12117, #13732, #15502, #15532, #17035, #17165, #20669, #20748, #20888, #21072, #21417, #21652, #21687, #23207, #23385 by @acdlite, @bvaughn, @gaearon, @lunaruan, @rickhanlonii, @trueadm, and @sebmarkbage)aria-description
to the list of known ARIA attributes. (#22142 by @mahyareb)onResize
event to video elements. (#21973 by @rileyjshaw)imageSizes
and imageSrcSet
to known props. (#22550 by @eps1lon)<option>
children if value
is provided. (#21431 by @sebmarkbage)aspectRatio
style not being applied. (#21100 by @gaearon)renderSubtreeIntoContainer
is called. (#23355 by @acdlite)renderToNodeStream
. (#23359 by @sebmarkbage)act
is used in production. (#21686 by @acdlite)global.IS_REACT_ACT_ENVIRONMENT
. (#22561 by @acdlite)act
batch updates. (#21797 by @acdlite)exports
field to package.json
. (#23087 by @otakustay)lazy
support. (#24068 by @gnoff)globalThis
instead of window
for edge environments. (#22777 by @huozhi)FAQs
utility for subscribing to external data sources inside React components
The npm package create-subscription receives a total of 1,599 weekly downloads. As such, create-subscription popularity was classified as popular.
We found that create-subscription demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 6 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.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.