useExternalStore
Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive accessor.
Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive
accessor. The one bridge for every external source, and the ShadowJS form of React's
useSyncExternalStore and Solid's from.
subscribe(notify) is called in an effect after the owner is created and returns the
unsubscribe function, which runs when the owner is disposed. getSnapshot() is read untracked
at creation, on every notification, and once after subscribing (so a change made between the
first read and the subscription is not lost). The accessor updates only when the snapshot differs
by equals. On the server nothing is subscribed: the accessor returns getServerSnapshot().
Import#
import { useExternalStore } from "@shadow-js/core";
Signature#
function useExternalStore<T>(
subscribe: (notify: () => void) => () => void,
getSnapshot: () => T,
options?: ExternalStoreOptions<T>,
): Accessor<T>
Parameters#
| Name | Description |
|---|---|
subscribe |
Registers notify; returns the unsubscribe function. |
getSnapshot |
Returns the current value. Reads inside it are not tracked. |
options |
Server snapshot, equality and a devtools name. Undefined uses the defaults. |
Returns#
An accessor of the current snapshot.
Examples#
import { useExternalStore } from "@shadow-js/core";
function subscribe(notify: () => void): () => void {
window.addEventListener("online", notify);
window.addEventListener("offline", notify);
return () => {
window.removeEventListener("online", notify);
window.removeEventListener("offline", notify);
};
}
function OnlineBadge() {
const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });
return <span>{online() ? "online" : "offline"}</span>;
}