Conditionally hide some jsx content.
import { Hide } from "@uxf/core-react/components/hide";
<Hide when={SOME_CONDITION}>...some content</Hide>;
Conditionally show some jsx content.
import { Show } from "@uxf/core-react/components/show";
<Show when={SOME_CONDITION}>...some content</Show>;
Lock scrolling on body element. Useful for modals, popovers, etc.
import { useBodyScrollLock } from "@uxf/core-react/hooks/use-body-scroll-lock";
import { useState } from "react";
const innerRef = useRef<HTMLDivElement>(null);
const [isOpen, setIsOpen] = useState<boolean>();
const clearAllOnclose = false;
useBodyScrollLock<HTMLDivElement>(innerRef, isOpen, {
allowTouchMove: undefined, // https://github.com/willmcpo/body-scroll-lock#allowtouchmove
clearAllOnClose: false, // optionally call clearAllBodyScrollLocks method on unmount
reserveScrollBarGap: undefined, // https://github.com/willmcpo/body-scroll-lock#reservescrollbargap
});
<div ref={innerRef}>Element which activates scroll lock on its parent elements.</div>;
Check if component is mounted.
import { useIsMounted } from "@uxf/core-react/hooks/use-is-mounted";
const isMounted = useIsMounted();
Deprecated in favour of useIsHydrated for rendering something only in the browser. Keep it only where the code
needs effects to have run (refs attached).
False on the server and during hydration, true in every other render, including the first render of a component
that mounts later on the client. Use it to render something only in the browser (window, a portal into
document.body, an editor) without the extra commit and the flash of fallback that useIsMounted costs on every
client-side mount. It does not mean effects have run: refs are not attached yet in the render where it turns true.
import { useIsHydrated } from "@uxf/core-react/hooks/use-is-hydrated";
const isHydrated = useIsHydrated();
return isHydrated ? <Editor /> : <Loader />;
Deprecated – use useLayoutEffect. It only silenced React's server warning about useLayoutEffect, which
React 19 removed; on the server useLayoutEffect simply does not run.
Returns useLayoutEffect in the browser and useEffect on the server.
import { useIsomorphicLayoutEffect } from "@uxf/core-react/hooks/use-isomorphic-layout-effect";
useIsomorphicLayoutEffect(
() => {
/* code */
},
[/* deps */],
);
Trigger callback on given key. The callback and the key filter are always the latest ones, also when passed inline.
The listener follows targetRef: a target that mounts later or is replaced gets it after the next commit.
import { useKey } from "@uxf/core-react/hooks/use-key";
import { useRef } from "react";
const targetRef = useRef<HTMLDivElement>(null);
const disabled = false; // eg. for passing disabled state
useKey<HTMLDivElement>("Enter", () => console.log("callback"), {
disabled,
targetRef, // if not provided, then `document` will be used
type: "keydown",
});
<div ref={targetRef} tabIndex={0}>
Element with callback triggerable by enter key.
</div>;
Deprecated — Use
useMediaQueryinstead.
Returns boolean if window width is equal or greater than given value.
import { useMinWindowWidth } from "@uxf/core-react/hooks/use-min-window-width";
const isDesktop = useMinWindowWidth(1200);
const isDesktopWithDebounce = useMinWindowWidth(1200, 200); // will be updated every 200 ms
const example = isDesktop ? "desktop" : "tablet";
const debouncedExample = isDesktopWithDebounce ? "debouncedDesktop" : "debouncedTablet";
Returns array of pagination items.
import { usePagination } from "@uxf/core-react/hooks/use-pagination";
const paginationItems = usePagination({ page: 1, count: 10 });
Updates state only in the callback of requestAnimationFrame.
import { useRafState } from "@uxf/core-react/hooks/use-raf-state";
const [state, setState] = useRafState<boolean>(false);
Calls the callback on component mount; a returned function runs on unmount.
import { useOnMount } from "@uxf/core-react/hooks/use-on-mount";
useOnMount(() => console.log("mounted"));
Calls the callback on component unmount, in its version from the latest render.
import { useOnUnmount } from "@uxf/core-react/hooks/use-on-unmount";
useOnUnmount(() => clearTimeout(timer.current));
Calls the callback when the deps change, not on mount. It compares the deps with those of its previous run, so
StrictMode's second mount run is skipped too, and so is a reconnect with the same deps (an <Activity> shown again),
whose cleanup has already run. Work that has to survive a reconnect, like a pending timer, belongs in a plain
useEffect.
import { useOnUpdate } from "@uxf/core-react/hooks/use-on-update";
useOnUpdate(
() => {
/* code */
},
[/* deps */],
);
Returns the window's scroll position (x, y), updated at most once per animation frame. undefined on the
server and during hydration, the current position from the first render of a component mounted later.
import { useWindowScroll } from "@uxf/core-react/hooks/use-window-scroll";
const windowScroll = useWindowScroll();
const example = windowScroll && windowScroll.y > 100 ? "scrolled" : "on top";
Returns the window's inner width and height, updated at most once per animation frame. undefined on the
server and during hydration, the current size from the first render of a component mounted later.
import { useWindowSize } from "@uxf/core-react/hooks/use-window-size";
const windowSize = useWindowSize();
const example = windowSize && windowSize.width > 1200 ? "desktop" : "tablet";
Locks focus inside given element.
import { useFocusTrap } from "@uxf/core-react/hooks/use-focus-trap";
import { useState } from "react";
const [active, setActive] = useState<boolean>();
const focusTrapRef = useFocusTrap(active);
<div ref={focusTrapRef}>Element which trap focus inside if `active` is truthy.</div>;
Returns focus to last active element.
import { useFocusReturn } from "@uxf/core-react/hooks/use-focus-return";
import { useState } from "react";
const [active, setActive] = useState<boolean>();
// Returns focus to last active element, e.g. in Modal or Popover
useFocusReturn(active);
Returns props for anchor element.
type: "submit" works like a native submit button, through form.requestSubmit() on the form the element sits in
(or, outside any form, the form that has focus). The browser validates first (required, type="email", …) unless
the form has noValidate, which @uxf/form's Form sets. A form whose submit handler does not call
preventDefault() is then submitted natively, so the page navigates. Earlier versions dispatched a bare submit
event instead: no validation and no native submission.
import { useAnchorProps } from "@uxf/core-react/clickable/use-anchor-props";
import { AnchorHTMLAttributes } from "react";
// extends <a /> by `analyticsCallback`, `disabled`, `loading`, `submit` props
const anchorProps = useAnchorProps<AnchorHTMLAttributes<HTMLAnchorElement>>({
analyticsCallback: () => console.log("analytics"),
disabled: false,
href: "https://www.google.com/",
loading: false,
onClick: () => console.log("success"),
type: "submit", // simulate <button type="submit" /> function
});
<a {...anchorProps}>Click me</a>;
// example with generics
import { UseAnchorProps, useAnchorProps } from "@uxf/core-react/clickable/use-anchor-props";
import { AnchorHTMLAttributes } from "react";
interface Props extends UseAnchorProps, AnchorHTMLAttributes<HTMLAnchorElement> {
customProp?: boolean;
}
const anchorProps = useAnchorProps<Props>({
customProp: true,
loading: false,
href: "https://www.google.com/",
});
<a {...anchorProps}>Click me</a>;
Returns props for button element.
import { useButtonProps } from "@uxf/core-react/clickable/use-button-props";
import { ButtonHTMLAttributes } from "react";
// extends <button /> by `analyticsCallback` and `loading` props
const buttonProps = useButtonProps<ButtonHTMLAttributes<HTMLButtonElement>>({
analyticsCallback: () => console.log("analytics"),
disabled: false,
loading: false,
onClick: () => console.log("success"),
type: "submit",
});
<button {...buttonProps}>Click me</button>;
// example with generics
import { UseButtonProps, useButtonProps } from "@uxf/core-react/clickable/use-button-props";
import { ButtonHTMLAttributes } from "react";
interface Props extends UseButtonProps, ButtonHTMLAttributes<HTMLButtonElement> {
customProp?: boolean;
}
const buttonProps = useButtonProps<Props>({
customProp: true,
loading: false,
type: "submit",
});
<button {...buttonProps}>Click me</button>;
Returns props for clickable element. type: "submit" submits the element's form through requestSubmit(), as
described under useAnchorProps.
import { useClickableProps } from "@uxf/core-react/clickable/use-clickable-props";
import { HTMLAttributes } from "react";
// extends any HTML element by `analyticsCallback`, `disabled`, `loading`, `submit` props
const clickableProps = useClickableProps<HTMLAttributes<HTMLDivElement>>({
analyticsCallback: () => console.log("analytics"),
disabled: false,
loading: false,
onClick: () => console.log("success"),
type: "submit", // simulate <button type="submit" /> function
});
<div {...clickableProps}>Click me</div>;
// example with generics
import { UseClickableProps, useClickableProps } from "@uxf/core-react/clickable/use-clickable-props";
import { HTMLAttributes } from "react";
interface Props extends UseClickableProps, HTMLAttributes<HTMLDivElement> {
customProp?: boolean;
}
const buttonProps = useClickableProps<Props>({
customProp: true,
hidden: false,
loading: false,
});
<button {...buttonProps}>Click me</button>;
Allow to scroll element by dragging mouse.
The click that ends a drag is swallowed, so releasing the mouse over a tab or a link inside the element does not activate it, and the native drag of links and images is turned off. Clicks from the keyboard are never swallowed.
import { useMouseDragToScroll } from "@uxf/core-react/hooks/use-mouse-drag-to-scroll";
const targetRef = useRef<HTMLDivElement>(null);
const style = useMouseDragToScroll(scrollRef);
<div style={style}>Drag to scroll</div>;
Manage focus states of input element.
import { useInputFocus } from "@uxf/core-react/hooks/use-input-focus";
const focusRef = useRef<HTMLInputElement>(null); // or HTMLTextAreaElement
const { onBlur, onFocus } = props;
const input = useInputFocus(focusRef, onBlur, onFocus);
<div>Input is {input.focused}</div>
<button onClick={input.focus}>Focus input</button>
<input onBlur={input.onBlur} onFocus={input.onFocus} ref={focusRef} />
Deprecated. It writes ref.current during render, which React 19 asks not to do. To read the latest props or
state from an effect or a listener it registers, use useEffectEvent; for a value read during render, use the value
itself.
Always returns the latest value of the given variable.
import { useLatest } from "@uxf/core-react/hooks/use-latest";
const latestState = useLatest(someUnstableWhatever);
useEffect(() => {
latestState.current(); // use newest state of 'someUnstableWhatever' without affecting this effetct update
}, [latestState]);
Puts several refs on one element. The composed ref keeps its identity until one of the refs changes, so React does not detach and re-attach it on every render.
import { useComposedRefs } from "@uxf/core-react/hooks/use-composed-refs";
function Field(props: FieldProps & RefAttributes<HTMLInputElement>) {
const innerRef = useRef<HTMLInputElement>(null);
const ref = useComposedRefs(innerRef, props.ref);
return <input ref={ref} />;
}
composeRefs from @uxf/core-react/utils/compose-refs does the same without the memoisation. It makes a new
callback on every call, so use it only outside a component.
Deprecated. Its ref is only useful when read during render, which React 19 asks not to do. To react to a change, keep the previous value in state and compare during render (React docs).
Returns the previous value of the given variable.
import { usePrevious } from "@uxf/core-react/hooks/use-previous";
const previousState = usePrevious(someUnstableWhatever);
useEffect(() => {
previousState.current(); // use state of 'someUnstableWhatever' from previous render without affecting this effetct update
}, [previousState]);
Returns boolean state and methods to toggle it.
import { useToggle } from "@uxf/core-react/hooks/use-toggle";
const [isVisible, toggleIsVisible, setVisible, setInvisible] = useToggle(false);
<button onClick={toggleIsVisible}>Toggle visibility</button>;
Returns number state and methods to increment, decrement and reset.
import { useIncrement } from "@uxf/core-react/hooks/use-increment";
const [count, increment, decrement, reset] = useIncrement(5, 1);
<button onClick={increment}>Toggle visibility</button>;
Returns the latest value after given delay.
import { useDebounce } from "@uxf/core-react/hooks/use-debounce";
const debouncedValue = useDebounce<string>("some value", 300);
Returns whether the given media query is currently matched. Optionally accepts a callback that is called on every change.
Reads window.matchMedia through useSyncExternalStore: false on the server and during hydration (no mismatch),
the real value from the first render of a component mounted on the client, and updated on every change.
import { useMediaQuery } from "@uxf/core-react/hooks/use-media-query";
import type { UseMediaQueryCallback } from "@uxf/core-react/hooks/use-media-query";
import { twScreens } from "@generated/tw-tokens/tw-screens";
// Basic usage – reactive boolean, SSR-safe
const isDesktop = useMediaQuery(`(min-width: ${twScreens.sm})`);
// With optional callback – fired on every match change
const callback: UseMediaQueryCallback = (isMatching, mediaQueryString) => {
console.log(isMatching, mediaQueryString);
};
const isDesktopWithCallback = useMediaQuery(`(min-width: ${twScreens.sm})`, callback);
Parameters:
mediaQueryString – CSS media query stringcallback (optional) – called with (isMatching, mediaQueryString) once after mount and on every match change; always the latest callback, without resubscribingisSSR – deprecated and ignored; a client-only component gets the real value in its first render anywayimport { nl2br } from "@uxf/core-react/string/nl2br";
<div>{nl2br("Hello\nWorld")}</div>;
Moved to its own package. The sortable hooks and a facade over @dnd-kit now live in
@uxf/dnd, so that @dnd-kit is a dependency only of the projects that actually render drag and drop —
it used to be a peer of this package, and therefore of everything that depends on it.
See the @uxf/dnd README, and the migration note
for the import rewrites.
createGlobalContext is a thin wrapper around React.createContext that caches the resulting Context object on globalThis, keyed by a unique name. Use it instead of createContext for any Context exported from a library package.
Under Turbopack a single "use client" module can be evaluated more than once — typically once per "use client" boundary that imports it. Each evaluation calls createContext(...) separately, producing distinct Context identities in the same JS realm. The Provider ends up writing into one identity and useContext reads from another, so consumers silently fall back to the default value. Caching the Context on globalThis collapses all evaluations to a single identity.
Webpack does not exhibit this because its chunking layer deduplicates by module ID; Turbopack does not (yet) guarantee that for client-boundary modules.
import { createGlobalContext } from "@uxf/core-react/global-context";
import { useContext } from "react";
const themeContext = createGlobalContext<"light" | "dark">("ui/theme", "light");
export const ThemeProvider = themeContext.Provider;
export function useTheme() {
return useContext(themeContext);
}
The name argument must be unique across the monorepo. Use "<package>/<context>", for example:
"core-react/translations""localize/locale""ui/color-scheme"The same name on subsequent calls returns the original Context — the defaultValue argument is honored only on the first call.
Use createGlobalContext for any Context that is:
@uxf/*), or"use client" boundary.For Contexts that are private to a single app file and never imported elsewhere, plain React.createContext is fine.
Provides a translation system that can be used in both single-language and multi-language projects.
For single-language projects, use the TranslationsProvider context and createDefaultT function to provide translations for the packages you use:
import { TranslationsProvider } from "@uxf/core-react/translations";
import { createDefaultT } from "@uxf/core-react/translations/create-default-t";
// Import translations for packages you use
import uiTranslations from "@uxf/ui/translations/cs.json";
import formTranslations from "@uxf/form/translations/cs.json";
// Create a translation function for your language
const t = createDefaultT({
...uiTranslations,
...formTranslations,
});
// Provide the translation function to your app
function App() {
return <TranslationsProvider value={t}>{/* Your app content */}</TranslationsProvider>;
}
For multi-language projects, use the TranslationsProvider context with a translation function from your preferred translation library (e.g., next-translate):
import { TranslationsProvider } from "@uxf/core-react/translations";
import useTranslation from "next-translate/useTranslation"; // Or any other translation library
function App() {
// Get the translation function from your translation library
const { t } = useTranslation();
return <TranslationsProvider value={t}>{/* Your app content */}</TranslationsProvider>;
}
To use translations in your components, use the useUxfTranslation hook:
import { useUxfTranslation } from "@uxf/core-react/translations";
function MyComponent() {
const t = useUxfTranslation();
return <div>{t("form:validation.required")}</div>;
}