React hooks for online status, page visibility, breakpoints, viewport proximity, clamped text, new builds, and theme colors, each safe in a server render.
import { isBreakpointAtLeast, useBreakpoint, useDocumentVisibility, useIsWindowScrolledPast, useOnlineStatus,} from 'jg-react';export const useLayoutState = () => { const isOnline = useOnlineStatus(); // the browser's guess, from its network interfaces const isVisible = useDocumentVisibility(); // false while the tab is hidden const breakpoint = useBreakpoint(); // 'xs' on a phone, then 'sm' to '2xl' const isScrolled = useIsWindowScrolledPast(8); return { isOnline, isVisible, isDesktop: isBreakpointAtLeast(breakpoint, 'lg'), isScrolled };};
Hook
Returns
Re-renders when
In a server render
useOnlineStatus()
Whether the browser is online
It goes online or offline
true
useDocumentVisibility()
Whether the page is visible
Its tab is hidden or shown
true
useBreakpoint()
Tailwind CSS’s breakpoint: xs below sm, up to 2xl
The viewport crosses a breakpoint
undefined
useIsWindowScrolledPast(pixels)
Whether the window is scrolled further than pixels
The answer changes, not every scroll
false
useFormChanges(options)
Whether a form’s command differs from the last confirmed one, a submit-time check, and confirmChanges
The commands or the baseline change
Compared as usual
useResendCooldown(options)
Whether a resend must wait, the seconds left, and startCooldown
Every second while cooling down
{ isCoolingDown: false, remainingSeconds: 0 }
useCopyFeedback(options?)
Whether a copy just succeeded, and copy(write)
A copy succeeds, and its feedback ends
isCopied: false
useFileUploadQueue(options)
The upload queue’s items, summary, announcement, and controls
The queue changes
An empty queue
useResolvedTheme(preference)
light or dark, following the system while the preference is system
The system’s color scheme changes, for system
dark for dark, otherwise light
useAppliedTheme(preference, options?)
The theme it sets as the light or dark class on <html>
As useResolvedTheme
As useResolvedTheme, without touching the document
Keep a save button disabled until the form holds a real change, and a resend button waiting after each send:
ts
import { useFormChanges, useResendCooldown } from 'jg-react';const trim = ({ name }: { name: string }) => ({ name: name.trim() });export const useProfileEditor = (saved: { name: string }, draft: { name: string }) => { // a whitespace-only edit isn't a change, and the baseline advances only once a save succeeds const { hasChanges, confirmChanges } = useFormChanges({ confirmedCommand: saved, currentCommand: draft, normalizeCommand: trim, }); // the deadline survives a reload of the tab, apart from other accounts and actions const resend = useResendCooldown({ durationSeconds: 60, cooldownKey: 'account-a:verify-email' }); return { canSave: hasChanges, confirmChanges, resend };};
The browser hooks read the browser through useSyncExternalStore, so every component sees the same value in the same render, and a server render gets a fixed value instead of failing. The breakpoints are Tailwind CSS’s defaults, in rem, read through media queries, so they follow the browser’s font size as CSS does. Prefer CSS for layout, and useBreakpoint for what CSS can’t do, such as rendering a different component.
Copy feedback
useCopyFeedback shows that a copy worked, for a moment. copy takes the function that writes, such as jg-clipboard’s copyText, and calls it at once, before awaiting anything, so the write stays inside the click that browsers require for clipboard access:
ts
import { copyText } from 'jg-clipboard';import { useCopyFeedback } from 'jg-react';const { isCopied, copy } = useCopyFeedback({ durationSeconds: 1.4, onError: showCopyError });const onClick = () => void copy(() => copyText(inviteLink)); // resolves to whether it worked
isCopied stays true for durationSeconds, DEFAULT_COPY_FEEDBACK_SECONDS (1.4) by default. A new copy clears it while it runs, so an earlier copy’s state never claims the new one worked, and restarts it once the new one succeeds. A copy while another runs is ignored and resolves to false. A failed one resolves to false and calls the latest onError; copy never rejects. After unmount, a copy that settles changes nothing and calls nothing. A duration that isn’t positive and finite throws INVALID_COPY_FEEDBACK_DURATION.
Dialog sessions
createDialogSession keeps one dialog’s state outside React, so any code can open it and await what the user chose, while one host component renders it with useDialogSession:
ts
import { createDialogSession, useDialogSession } from 'jg-react';import { useDialogNavigationDismissal } from 'jg-react-router';export const confirmDialog = createDialogSession<{ title: string }, boolean>();// anywhere, such as a delete button's handlerconst isConfirmed = await confirmDialog.open({ title: 'Delete the project?' }); // true, false, or undefined// in the host componentconst session = useDialogSession(confirmDialog); // the open session, or nulluseDialogNavigationDismissal({ getSession: confirmDialog.getSnapshot, // a navigation closes the dialog onDismiss: () => confirmDialog.close(),});const confirm = () => confirmDialog.close(true, session?.id);
At most one session is open. Opening another resolves the open one’s caller with undefined, or, with whileOpen: 'keep', resolves the new call with undefined, so no caller waits forever, and no promise rejects. A close that names its session’s id does nothing once that session ended, so a late click on a closing dialog can’t close a newer one. One frame after a close, focus returns to the element the session opened from, the focused one by default, when it’s still in the page, enabled, and not inert, no other session opened, and focus is lost on the body; a session that replaces another returns focus where that one would have. A server render reads no open session.
File uploads
useFileUploadQueue runs a file upload queue without rendering anything, for a drop zone or a file input in the app’s own markup:
Checks: each selection is checked file by file, in a fixed order: empty, type, size, duplicate, count, and total size, with existingFiles counted toward the limits. A validateFile function runs next, such as for an image’s dimensions, and the built-in checks run again after it, since the queue may have changed meanwhile. Selections are checked one at a time.
Uploads: admitted files upload first in, first out, up to maxConcurrentUploads at once, 2 by default, or wait for startUploads without autoUpload. Progress is coalesced per frame and never goes backwards. At 100%, a file is processing: it waits for its result, can’t be canceled, and survives removal and reset.
Cancel and retry: a canceled upload is aborted through its signal, and its late result is ignored, but its slot frees only when its promise settles. A retry keeps the item’s uploadId and starts the next attemptNumber.
One file: with maxFiles 1, the default, a new file replaces the current one only once it passes its checks, so a rejected replacement leaves the current file alone.
Cleanup: preview object URLs are revoked on remove, replace, reset, and unmount, and an error a callback throws goes to reportError without stopping the queue. Shown again after an <Activity> hid it, files whose work stopped are canceled.
Text: every message and announcement comes from DEFAULT_FILE_UPLOAD_MESSAGES, which messages overrides, and getErrorFeedback decides what a failed upload shows, messages.uploadFailed by default.
A policy that isn’t valid, such as a maxFileBytes that isn’t a positive integer, throws INVALID_FILE_UPLOAD_POLICY, with a message for each field. resolveFileUploadPolicy, validateFileUploadCandidate, isFileUploadItemCancelable, and hasDraggedFiles work on their own too.
Light and dark themes
createThemeInitScript builds an inline script that applies the stored preference before the page paints, so a server render never flashes the wrong theme, and useAppliedTheme keeps the class on <html> in step once React runs:
tsx
import { createThemeInitScript, useAppliedTheme } from 'jg-react';// jg-storage's createLocalStore('preferences') keeps { theme } under this keyconst script = createThemeInitScript({ storageKey: 'jg-storage:preferences', field: 'theme' });export const ThemeScript = ({ nonce }: { nonce: string }) => ( <script nonce={nonce} dangerouslySetInnerHTML={{ __html: script }} />);export const ThemeRoot = ({ preference }: { preference: 'light' | 'dark' | 'system' }) => { useAppliedTheme(preference); // turns transitions off while the class changes return null;};
Set color-scheme per class in your stylesheet, such as :root.dark { color-scheme: dark; }, so form controls and scrollbars follow the theme.
The preference and theme types, IThemePreference and IResolvedTheme, with THEME_PREFERENCES, in the order ['system', 'light', 'dark'], and resolveThemePreference, come from jg-site, which jg-react depends on, so a site and an app share one definition.
A component far from the one applying the theme, such as a chart that picks its colors in script, reads the theme the page shows with useDocumentTheme, without the user’s preference: <html>’s dark class, then light, then the system’s color scheme. It re-renders only when that theme changes, not for another class, and reads light on a server and while hydrating, as the init script’s fallback does:
useDebouncedSearch searches once the trimmed query has stayed the same for 0.3 seconds, aborting the previous search when the query changes, the search is disabled, or the component unmounts:
A search that settles after its query changed is ignored, even when search doesn’t stop on the signal. The previous results stay while the next search runs, and an empty query or a disabled search clears everything. retry, such as for a Retry button after error, searches the current query again. A new search function on each render doesn’t restart the wait.
Table of contents
useActiveHeading follows which heading the reader is at: the one the URL’s hash names, on mount and on every hashchange, then, as the page scrolls, the last heading whose top passed topOffsetPx, the height of a sticky header, or the first one before any has:
Scrolling is followed with an IntersectionObserver, and only the hash where there’s none. A new array with the same ids keeps the observer. A top offset that isn’t a finite number of pixels of at least 0 throws INVALID_ACTIVE_HEADING_OFFSET.
Element width
useElementWidth turns an element’s width into the value a component needs, such as how many columns fit, and re-renders only when that value changes, not on every pixel:
ts
import { useElementWidth } from 'jg-react';const { ref, value: columns } = useElementWidth((width) => Math.max(1, Math.floor(width / 280)));// <ul ref={ref}>, laid out in `columns ?? 1` columns
It measures the element’s border box as soon as ref attaches it, before the browser paints, then follows it with a ResizeObserver, or the window’s resize event where there’s none. A width of 0, such as while the element is hidden with display: none, keeps the last value. Attaching another element measures that one, and detaching resets the value to undefined, as on a server. Return a primitive from the function, so an unchanged result never re-renders.
Near the viewport
useNearViewport tells when an element is within a margin of the viewport, such as a sentinel at the end of a list that loads the next page before the reader gets there:
ts
import { useNearViewport } from 'jg-react';const { ref, isNear } = useNearViewport({ rootMargin: '0px 0px 512px 0px' });// <div ref={ref} /> after the last row; load the next page while `isNear`
It reads false with no element attached, on a server, and in a browser without IntersectionObserver. A new margin starts a new observer.
Clamped text
useIsTextClamped tells whether a text runs past the lines its CSS line-clamp shows, so a Show all control appears only on text the clamp cuts off:
ts
import { useIsTextClamped } from 'jg-react';const { ref, isClamped } = useIsTextClamped({ lines: 3, content: message });// <p ref={ref} className={isExpanded ? '' : 'line-clamp-3'}>, with Show all while `isClamped`
It compares the text’s full height with those lines, so the answer holds whether the text shows clamped or in full, and a row that opens expanded still offers Show less. It measures again before the browser paints when content changes, and whenever the box resizes. Lines that aren’t a positive safe integer throw INVALID_CLAMPED_LINES.
The current time
useCurrentTime keeps the time for labels that read relative to it, moving it on once an interval, a minute by default, so “5 minutes ago” changes without a re-render every second:
ts
import { useCurrentTime } from 'jg-react';import { formatRelativeTime } from 'jg-utilities';const label = formatRelativeTime(observedAt, { now: useCurrentTime() });
An interval that isn’t a positive, finite number of seconds throws INVALID_CURRENT_TIME_INTERVAL.
The browser’s theme color
useThemeColorMeta keeps every <meta name="theme-color"> tag, which colors the browser’s chrome and an installed app’s title bar, on the color of the theme the page shows:
It follows <html>’s theme as useDocumentTheme reads it, so a theme the user picks in the app wins over the system’s. Leave media queries off those tags, or start them with the system’s colors.
New builds
useNewBuildAvailable tells when the server serves a newer build of the app than the open page, so an old tab can offer a reload:
ts
import { useNewBuildAvailable } from 'jg-react';const { isNewBuildAvailable, check } = useNewBuildAvailable();// show a Reload banner while `isNewBuildAvailable`; call `check()` when the server is back
It reads the entry page, / by default, without the cache and without following redirects, and compares the entry script it loads from /assets/ with the open page’s, each time the page becomes visible again and when check asks. A lazy chunk that’s gone after a deploy, which Vite reports with vite:preloadError, counts as a new build while the browser is online; the hook prevents that event’s default, so the import resolves with no module instead of rejecting, which jg-react-router’s loadRouteModule treats as code that couldn’t load. A read that fails, is redirected or isn’t HTML, such as a proxy’s sign-in page, says nothing, and the page never reloads on its own.
Generated from TSDoc
API reference
Every export of [email protected], 89 in all, with its signature, its errors, and an example.
Creates one dialog's sessions, outside React, so any code can open the dialog and await its result, such as a confirmation, while one host component renders it. At most one session is open: opening another resolves the open one's caller with undefined (whileOpen: 'replace', the default), or resolves the new call with undefined ('keep'), so no caller waits forever. A promise never rejects. A close can name the session's id, so a stale close, such as from a dialog that already closed, does nothing. One frame after a close, focus returns to the element the session was opened from, when it's still in the page, enabled, and not inert, no other session opened, and focus is lost on the body. useDialogSession reads the open session.
Builds the inline script that applies the stored theme before the page paints, so a server render doesn't flash the wrong theme. It reads the preference from localStorage, as JSON or as a raw string, from a field of a stored object when field is given, falls back to defaultPreference when it's missing or invalid, and sets the light or dark class on <html>. Storage that can't be read and a browser without matchMedia never make it throw.
Render it at the top of <head>, with your CSP nonce, as <script nonce={nonce} dangerouslySetInnerHTML={{ __html: script }} />. Its output is the same for the same options, so a hash-based CSP works too. A jg-storage store's key is jg-storage:<id>. Set color-scheme per class in your stylesheet.
Checks whether a breakpoint is at least as wide as another, such as to show a sidebar from md up. An unknown breakpoint, as in a server render, is never wide enough.
Checks and normalizes an upload policy: accepted types trimmed, lowercased, and without repeats, the defaults filled in, concurrency capped at maxFiles, and single-file replacement only for one file.
Follows which heading the reader is at, for a table of contents that highlights it: the heading the URL's hash names, on mount and on every hashchange, and then, as the page scrolls, the last heading whose top has passed topOffsetPx, the height of a sticky header, or the first heading before any has. Scrolling is followed with an IntersectionObserver, and only the hash without one. The ids are compared by value, so a new array with the same ids doesn't restart anything, and a heading missing from the page is skipped.
Applies a theme preference to the page: the light or dark class on <html>, following the system's color scheme while the preference is system. The class changes before the browser paints, with transitions off by default, so colors switch at once. Pair it with createThemeInitScript, so the page shows the right theme before React loads, and set color-scheme per class in your stylesheet.
Reports the viewport's Tailwind CSS breakpoint, re-rendering only when the viewport crosses one: xs below sm, such as on a phone, then sm, md, lg, xl, and 2xl. A server render, which has no viewport, reports undefined, so prefer CSS for layout and this for what CSS can't do.
Shows that a copy worked, for a moment, such as a "Copied" label on a copy button. copy calls the write function at once, before it awaits anything, so a clipboard write still runs inside the click that browsers require; then isCopied stays true for durationSeconds. A new copy clears an earlier one's copied state while it runs, a copy while another runs is ignored, and a failed one calls onError and leaves isCopied false. copy never rejects, and after unmount nothing changes and nothing is called.
Keeps the current time for labels that read relative to it, such as "5 minutes ago", moving it on once an interval, a minute by default, so they change without re-rendering every second. The first render reads the time it renders at, which a server render reads too.
Signature
useCurrentTime(options?: IUseCurrentTimeOptions): number
Parameters
options?IUseCurrentTimeOptions
How often the time moves on, in seconds.
Defaults to {}.
Returns
number
The current time, in Unix milliseconds.
Throws
INVALID_CURRENT_TIME_INTERVALThe current time's interval must be a positive, finite number of seconds.
Searches as the user types: once the trimmed query has stayed the same for 0.3 seconds, it calls search with it and a signal, and keeps the results. A new query, disabling the search, and unmounting abort the search in flight, and a search that settles after its query changed is ignored, even when search doesn't stop on the signal. The previous results stay while the next search runs, and an empty query or a disabled search clears everything.
Reads a dialog session's open session, re-rendering when one opens or closes, such as in the component that renders the dialog. A server render reads null.
The open session, the same object while it lasts, or null.
Example
import { createDialogSession, useDialogSession } from 'jg-react';export const confirmDialog = createDialogSession<{ title: string }, boolean>();// in the component that renders the dialogexport const useConfirmDialog = () => { const session = useDialogSession(confirmDialog); return { isOpen: session !== null, title: session?.options.title ?? '', // the id keeps a click on a dialog that already closed from closing a newer one confirm: () => confirmDialog.close(true, session?.id), cancel: () => confirmDialog.close(false, session?.id), };};
Reads the theme the page shows from <html>'s class, as useAppliedTheme and createThemeInitScript write it: dark wins, then light, then the system's color scheme. It re-renders only when that theme changes, not for another class, so a component far from the one applying the theme, such as a chart, can follow it without the user's preference. A server render, and so the hydration render, reads light.
Reports whether the page is visible, re-rendering when its tab is hidden or shown again, such as to pause polling while nobody looks. A server render reports visible.
Reads an element's width as a value the component needs, such as how many columns fit, and re-renders only when that value changes, not on every pixel. It measures the element's border box as soon as it's attached, before the browser paints, then follows it with a ResizeObserver, or the window's resize event where there's none. A width of 0, such as while the element is hidden with display: none, keeps the last value. Attaching another element measures that one, and detaching resets the value to undefined, as on a server.
Runs a headless file upload queue, for a drop zone or a file input in the app's own markup. Selections are checked one at a time, against the built-in checks, then validateFile, then the built-in checks again, since the queue may have changed meanwhile. Admitted files upload first in, first out, up to maxConcurrentUploads at once, with progress coalesced per frame. At 100%, an upload is processing: it can't be canceled anymore, and it survives removal and reset. A canceled upload is aborted and its late result ignored, but its slot frees only once its promise settles. A retry keeps the item's id. With maxFiles 1, a new file replaces the current one only once it validates. Object URLs are revoked on remove, replace, reset, and unmount, and errors the callbacks throw go to reportError. Shown again after an <Activity> hid it, items whose work stopped are canceled.
Tells whether a form holds unsaved changes, by comparing the command it edits with the last one the server confirmed, so a save button can stay disabled until something changed. Commands are compared by value, as JSON: a Map or a Set compares as {}, a key whose value is undefined doesn't count, and a BigInt throws UNABLE_TO_SERIALIZE_JSON. Pass normalizeCommand to compare commands the way the server stores them, such as with trimmed text.
The baseline advances only when confirmedCommand changes by value, or through confirmChanges once a save succeeds, so a failed save keeps the changes. guardSubmission checks again as the form submits, in case the command changed since the last render.
Measures whether a text runs past the lines its clamp shows, so a Show all control appears only on text the clamp cuts off. It compares the text's full height with those lines, which holds whether the text shows clamped or in full, so a row that opens already expanded still offers Show less. A ResizeObserver measures it again whenever its box changes, such as on a narrower screen, and new content is measured as it renders, before the browser paints.
Reports whether the window is scrolled past a number of pixels, such as to shadow a sticky header or show a back-to-top button. It re-renders only when the answer changes, not on every scroll. A server render reports false.
Signature
useIsWindowScrolledPast(pixels: number): boolean
Parameters
pixelsnumber
How far down the window must be scrolled, in pixels.
Watches whether an element is within a margin of the viewport, such as a sentinel at the end of a list that loads more as it comes into view, with one IntersectionObserver for the element and the margin. A browser without IntersectionObserver, and a server, read it as not near.
Tells when the server serves a newer build of the app than the open page, so an old tab can offer a reload instead of missing what a deploy changed. It compares the entry script the entry page loads now with the open page's, each time the page becomes visible again and when check asks, and treats a lazy chunk the open build named that's gone, which Vite reports with vite:preloadError, as a new build, unless the browser is offline. It prevents that event's default, so the import resolves with no module instead of rejecting, which route loaders such as jg-react-router's loadRouteModule treat as code that couldn't load. A read that fails, is redirected or isn't HTML says nothing. The page never reloads on its own.
Reports whether the browser is online, re-rendering when it goes online or offline. It's the browser's own guess, from its network interfaces, not proof that a server can be reached, so use it to explain a failure, not to skip a request. A server render reports online.
Signature
useOnlineStatus(): boolean
Returns
boolean
Whether the browser is online.
Example
import { useOnlineStatus } from 'jg-react';export const OfflineBanner = () => { const isOnline = useOnlineStatus(); return isOnline ? null : 'You are offline. Changes will sync when you reconnect.';};
Makes a resend button, such as for a verification email or a one-time code, wait after each send, with a countdown. Call startCooldown once the server acknowledged a send. With a cooldownKey, the deadline is kept in sessionStorage, so it survives a reload of the tab, and in memory when storage fails. Until the tab sends itself, lastAttemptedAt, when the server says the last send happened, sets the deadline; a time in the future counts as now.
The first render, on the server and while hydrating, is always { isCoolingDown: false, remainingSeconds: 0 }, and the deadline is read right after mount, before the browser paints. So a server-rendered button looks enabled until hydration, when it can't be clicked anyway.
Resolves a theme preference to the theme a page shows, following the system's color scheme while the preference is system, and re-rendering when it changes. A server render, which can't read the system, gives dark for dark and light otherwise.
Keeps the browser's chrome, and an installed app's title bar, on the theme the page shows: it sets every <meta name="theme-color"> tag to the theme's color whenever <html>'s theme changes, as useAppliedTheme and createThemeInitScript write it. Keep media queries off those tags, or start them with the system's colors, since the page's theme decides from then on.
type IDialogSessionOpenInit = { returnFocusTo?: HTMLElement | null | undefined;};
Members
returnFocusToproperty
HTMLElement | null
the element focus returns to once the session closes. Defaults to the element that has focus when the session opens, or, when it replaces one, to that session's element
what open does while a session is open: 'replace', the default, resolves the open session's caller with undefined and opens the new one; 'keep' leaves the open one and resolves the new call with undefined
restoreFocusproperty
boolean
whether closing returns focus to the element the session was opened from. Defaults to true
calls write at once, inside the click that called copy, clearing an earlier copy's state, and resolves to whether it succeeded. It never rejects, and resolves to false at once while another copy runs
the last search's results, kept while the next one runs, or undefined before the first, after a failed one, and while the query is empty or the search is disabled
isSearchingproperty
boolean
whether a search for the current query is waiting or running
errorproperty
unknown
what the current query's search rejected with, or null
retryproperty
() => void
searches the current query again, such as from a Retry button after an error
type IUseResendCooldownOptions = { durationSeconds: number; cooldownKey?: string | undefined; lastAttemptedAt?: string | number | Date | null | undefined; storeId?: string | undefined;};
Members
durationSecondsproperty
number
how long a resend waits after a send, in seconds: a positive integer
cooldownKeyproperty
string
what the cooldown is for, such as ${accountId}:verify-email, so it survives a reload of the tab and stays apart from other accounts' and actions'. Without it, nothing is stored
lastAttemptedAtproperty
string | number | Date | null
when the server says the last send happened, used until the tab sends one itself
storeIdproperty
string
the jg-storage session store holding the deadlines: letters, digits, underscores, and hyphens. Defaults to 'resend-cooldowns'