npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@uxf/core-react

v11.100.0

Published

UXF Core

Downloads

1,048

Readme

UXF Core-React

Components


Hide

Conditionally hide some jsx content.

import { Hide } from "@uxf/core-react/components/hide";

<Hide when={SOME_CONDITION}>
    ...some content
</Hide>

Show

Conditionally show some jsx content.

import { Show } from "@uxf/core-react/components/show";

<Show when={SOME_CONDITION}>
    ...some content
</Show>

ViewportHeightPolyfill

Polyfill for custom css variable --viewport-height to mimic functionality of browser's dynamic viewport height.

Add component to react app root (eg. _app.tsx).

import { ViewportHeightPolyfill } from "@uxf/core-react/components/viewport-height-polyfill";

<ViewportHeightPolyfill />

Add css variable declaration with fallback to app global styles (eg. base.css) if already not there.

:root {
    --viewport-height: 100vh;

    @supports (height: 100dvh) {
        --viewport-height: 100dvh;
    }
}

Hooks


useBodyScrollLock

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>

isMounted

Check if component is mounted.

import { useIsMounted } from "@uxf/core-react/hooks/use-is-mounted";

const isMounted = useIsMounted();

useIsomorphicLayoutEffect

Returns useEffect on client and useLayoutEffect on server.

import { useIsomorphicLayoutEffect } from "@uxf/core-react/hooks/use-isomorphic-layout-effect";

useIsomorphicLayoutEffect(() => {/* code */}, [/* deps */]);

useKey

Trigger callback on given key.

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>

useMinWindowWidth

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";

usePagination

Returns array of pagination items.

import { usePagination } from "@uxf/core-react/hooks/use-pagination";

const paginationItems = usePagination({ page: 1, count: 10 })

useRafState

Updates state only in the callback of requestAnimationFrame.

import { useRafState } from "@uxf/core-react/hooks/use-raf-state";

const [state, setState] = useRafState<boolean>(false);

useOnMount

Calls the callback on component mount.

import { useOnUnmount } from "@uxf/core-react/hooks/use-on-unmount";

const exampleCallback = () => {};

useOnUnmount(exampleCallback());

useOnUpdate

Calls the callback only on component update, except initial mount.

import { useOnUpdate } from "@uxf/core-react/hooks/use-on-update";

useOnUpdate(() => {/* code */}, [/* deps */]);

useWindowScroll

Returns x and y scroll coordinates of window on scroll.

import { useWindowScroll } from "@uxf/core-react/hooks/use-window-scroll";

const windowScroll = useWindowScroll();

const example = windowScroll && windowScroll.y > 100 ? "scroled" : "on top";

useWindowSize

Returns window width and height.

import { useWindowSize } from "@uxf/core-react/hooks/use-window-size";

const windowSize = useWindowSize();

const example = windowSize && windowSize.width > 1200 ? "desktop" : "tablet";

useFocusTrap

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>

useFocusReturn

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);

useAnchorProps

Returns props for anchor element.

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>

useButtonProps

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>

useClickableProps

Returns props for clickable element.

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>

useMouseDragToScroll

Allow to scroll element by dragging mouse.

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>

useInputFocus

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} />

useLatest

Allways returns latest value of 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])

usePrevious

Returns previous value of 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])

useToggle

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>

useIncrement

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>

useDebounce

Returns the latest value after given delay.

import { useDebounce } from "@uxf/core-react/hooks/use-debounce";

const debouncedValue = useDebounce<string>("some value", 300);

String helpers

import { nl2br } from "@uxf/core-react/string/nl2br";

<div>{nl2br("Hello\nWorld")}</div>

useMediaQuery

Returns if the media query is matched.

import { useMediaQuery } from "@uxf/core-react/hooks/use-media-query";
import { twScreens } from "@generated/tw-tokens/tw-screens";

const isDesktop = useMediaQuery(`(min-width: ${twScreens.sm})`);

Drag and Drop (DND) Hooks

Provides a set of hooks built on top of @dnd-kit for implementing drag-and-drop functionality with different patterns.

useSortableCore

Low-level hook that provides the core drag-and-drop functionality. Used as a building block for other sortable hooks.

import { useSortableCore } from "@uxf/core-react/dnd/hooks/use-sortable-core";

const {
  activeElement,      // Currently dragged element
  setActiveElement,   // Set active element manually
  onDragStart,        // Drag start handler
  onDragCancel,       // Drag cancel handler
  sensors,            // DND sensors (pointer, keyboard)
  dropAnimationConfig // Animation configuration for drop
} = useSortableCore();

useSortableSingle

Hook for implementing drag-and-drop sorting within a single list. Manages item reordering and state internally.

import { DndContext, DragOverlay } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { useSortableSingle } from "@uxf/core-react/dnd/hooks/use-sortable-single";
import { SortableItem } from "./sortable-item"; // Your sortable item component

interface Task {
  id: string;
  title: string;
}

function TaskList() {
  const initialTasks: Task[] = [
    { id: "1", title: "Write documentation" },
    { id: "2", title: "Review PR" },
    { id: "3", title: "Deploy to production" }
  ];

  const {
    items,              // Current items state
    setItems,           // Update items manually
    activeItem,         // Currently dragged item
    onDragStart,
    onDragEnd,
    onDragCancel,
    sensors,
    dropAnimationConfig
  } = useSortableSingle(
    initialTasks,
    (fromIndex, toIndex, updatedList) => {
      // Optional callback when items are reordered
      console.log(`Moved from ${fromIndex} to ${toIndex}`, updatedList);
    }
  );

  return (
    <DndContext
      sensors={sensors}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      onDragCancel={onDragCancel}
    >
      <SortableContext items={items.map(item => item.id)} strategy={verticalListSortingStrategy}>
        {items.map(task => (
          <SortableItem key={task.id} id={task.id}>
            {task.title}
          </SortableItem>
        ))}
      </SortableContext>

      <DragOverlay dropAnimation={dropAnimationConfig}>
        {activeItem ? <div>{activeItem.title}</div> : null}
      </DragOverlay>
    </DndContext>
  );
}

useSortableMulti

Hook for implementing drag-and-drop between multiple sections/lists. Ideal for kanban boards, categorized lists, or visible/hidden column management.

import { DndContext, DragOverlay, rectIntersection } from "@dnd-kit/core";
import { SortableContext, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { useSortableMulti } from "@uxf/core-react/dnd/hooks/use-sortable-multi";
import { SortableItem } from "./sortable-item"; // Your sortable item component

interface Task {
  id: string;
  title: string;
}

interface Sections {
  todo: Task[];
  inProgress: Task[];
  done: Task[];
}

function KanbanBoard() {
  const [sections, setSections] = useState<Sections>({
    todo: [
      { id: "1", title: "Design UI" },
      { id: "2", title: "Write tests" }
    ],
    inProgress: [
      { id: "3", title: "Implement feature" }
    ],
    done: [
      { id: "4", title: "Setup project" }
    ]
  });

  const {
    getSectionItemsIds, // Get IDs for a section (handles empty sections)
    activeItem,         // Currently dragged item
    onDragStart,
    onDragEnd,
    onDragCancel,
    sensors,
    dropAnimationConfig
  } = useSortableMulti<Task, Sections>(
    sections,
    setSections,
    (sourceKey, destKey, fromIndex, toIndex, nextState) => {
      // Optional callback when items are moved between sections
      console.log(`Moved from ${String(sourceKey)} to ${String(destKey)}`);
      // Save to backend, analytics, etc.
    }
  );

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={rectIntersection}
      onDragStart={onDragStart}
      onDragEnd={onDragEnd}
      onDragCancel={onDragCancel}
    >
      <div className="kanban-board">
        {(Object.keys(sections) as Array<keyof Sections>).map((sectionKey) => (
          <div key={sectionKey} className="kanban-column">
            <h3>{sectionKey}</h3>
            <SortableContext
              items={getSectionItemsIds(sectionKey)}
              strategy={verticalListSortingStrategy}
            >
              {sections[sectionKey].map(task => (
                <SortableItem key={task.id} id={task.id}>
                  {task.title}
                </SortableItem>
              ))}
            </SortableContext>
          </div>
        ))}
      </div>

      <DragOverlay dropAnimation={dropAnimationConfig}>
        {activeItem ? <div>{activeItem.title}</div> : null}
      </DragOverlay>
    </DndContext>
  );
}

Notes:

  • Items must have an id: string property
  • getSectionItemsIds automatically handles empty sections by returning placeholder IDs
  • Use rectIntersection collision detection for better multi-section behavior
  • The hook manages item movement between sections automatically

useSortableItems

Legacy hook for drag-and-drop sorting. Consider using useSortableSingle for new implementations.

import { useSortableItems } from "@uxf/core-react/dnd/hooks/use-sortable-items";

const {
  memoizedSensors,
  dropAnimationConfig,
  itemsIds,
  activeItem,
  onDragStart,
  onDragEnd,
  onDragCancel
} = useSortableItems({
  items: myItems,
  handleDragEnd: (activeIndex, overIndex) => {
    // Handle reorder
  }
});

Translations

Provides a translation system that can be used in both single-language and multi-language projects.

Single-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>
  );
}

Multi-language projects

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>
  );
}

Using translations in components

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>
  );
}