# Hooks (/docs/hooks)



Components cover the common case: a `Popover` opens, a `DataTable` sorts, a `FileUpload` takes a drop. Hooks expose the state and behaviour underneath, so you can build what a prop can't express: your own trigger, your own layout, your own upload transport.

That split is deliberate. When a component has behaviour worth reusing, the kit exposes it as **state plus a hook**, not as a growing list of props that each switch one behaviour on. `Collapse` takes a single `open` boolean, and `useDisclosure` is how you drive it from a trigger of your own:

```tsx
import { useDisclosure } from '@42-central/ui-react';
import { Collapse } from '@42-central/ui-react/collapse';

const [opened, { toggle }] = useDisclosure();

<button aria-expanded={opened} aria-controls="details" onClick={toggle}>
  Details
</button>
<Collapse id="details" open={opened}>…</Collapse>
```

Schedule works the same way. It has no navigation prop, because what a click means is yours to decide; `view`, `date` and `selected` are controlled pairs, and [`useSchedule`](/docs/schedule#selection--navigating-between-views) holds them for you and hands back `goTo` handlers.

## Contracts every hook keeps [#contracts-every-hook-keeps]

### SSR-safe first render [#ssr-safe-first-render]

A server can't know the visitor's viewport, stored preferences or clock. So every hook that reads the browser returns a **fixed value** on the server and on the first client render, and reads the real one right after hydration. The server HTML and the hydrating render always agree, so there's never a hydration mismatch.

```tsx
const isNarrow = useMediaQuery('(width < 640px)');
// Server HTML and first client render: false.
// Right after hydration: the real match. On a phone, this re-renders once.
```

That's why a value can **flip on mount**: `useMediaQuery`, `useContainerQuery`, `useReducedMotion` and [`useApplePlatform`](/docs/hooks/use-apple-platform) start at `false`, [`useNow`](/docs/hooks/use-now) starts at a placeholder you can test with `isNowPending`, `useLocalStorage` starts at its `defaultValue`, `useObjectUrl` returns `undefined` for a `Blob` until its effect has made the URL, and [`useInView`](/docs/hooks/use-in-view) is `undefined` until its first observation. To hold back output of your own until after hydration, use [`useHydrated`](/docs/hooks/use-hydrated).

<Callout title="Visuals belong in CSS">
  A flip is harmless for behaviour (whether to autoplay, which way to scroll) but visible when it decides what gets painted. For anything visual, prefer the CSS equivalent, which is right from the first frame: a responsive Tailwind variant, `motion-reduce:`, or `dark:` instead of `useTheme().resolvedTheme`.
</Callout>

### Same naming as the components [#same-naming-as-the-components]

The kit's components all take `value` / `defaultValue` / `onChange`, or `open` / `defaultOpen` / `onOpenChange` for something that opens. Both pairs are built on [`useUncontrolled`](/docs/hooks/use-uncontrolled), so a component of your own built on it is controlled and uncontrolled the same way a kit one is:

```tsx
function Panel({ open, defaultOpen, onOpenChange }) {
  const [isOpen, setOpen] = useUncontrolled({
    value: open,
    defaultValue: defaultOpen,
    finalValue: false,
    onChange: onOpenChange,
  });
  // …
}
```

[`useDisclosure`](/docs/hooks/use-disclosure) is the lighter tool for state you own outright: an uncontrolled boolean with `open` / `close` / `toggle`, whose value you pass to a component's `open`.

### Headless: the I/O stays yours [#headless-the-io-stays-yours]

A hook that touches the outside world runs the state machine and leaves the network to you. [`useFileQueue`](/docs/hooks/use-file-queue) decides when each file uploads, tracks progress, cancel and retry, but never makes a request: you pass the `upload` function.

```tsx
const queue = useFileQueue({
  upload: (file, { signal, onProgress }) => send(file, { signal, onProgress }),
});
```

The same goes for data: `DataTable`'s sorting, filters and pagination are plain [controlled state](/docs/data-table#controlled-state), so a `useState` or your query library owns them.

### Concrete values [#concrete-values]

[`useLocale`](/docs/hooks/use-locale) and [`useTimeZone`](/docs/hooks/use-time-zone) never return `"auto"` or `undefined`. They resolve the component's own prop, then the nearest [`IntlProvider`](/docs/intl), then the default, and hand back a tag and a zone you can pass straight to `Intl`:

```tsx
const locale = useLocale(props.locale); // "fr-FR", never "auto"
const timeZone = useTimeZone(props.timeZone); // "Europe/Paris", never "auto"
```

`"auto"` follows the browser, so it flips on mount like any other browser read: the server and the first client render report `"en-US"` and `"UTC"`.

### Client-only, imported from the root [#client-only-imported-from-the-root]

Hooks only run in Client Components, so the file that calls one starts with `"use client"`. The general-purpose hooks are exported from the package root. A hook that belongs to one component lives on that component's subpath, next to it:

```tsx
'use client';

import { useMediaQuery } from '@42-central/ui-react';
import { useSchedule } from '@42-central/ui-react/schedule';
```

## Catalogue [#catalogue]

### Environment [#environment]

<Cards>
  <Card title="useMediaQuery" href="/docs/hooks/use-media-query" description="Reach for it when behaviour depends on the viewport or another media feature." />

  <Card title="useContainerQuery" href="/docs/hooks/use-container-query" description="Reach for it when a component should respond to its own width, not the window's." />

  <Card title="useReducedMotion" href="/docs/hooks/use-reduced-motion" description="Reach for it when motion is driven from JS: a smooth scroll, an autoplay." />

  <Card title="useApplePlatform" href="/docs/hooks/use-apple-platform" description="Reach for it when a shortcut hint should read ⌘K on a Mac and Ctrl K elsewhere." />

  <Card title="useHydrated" href="/docs/hooks/use-hydrated" description="Reach for it when browser-only output must wait until hydration to avoid a mismatch." />

  <Card title="useNow" href="/docs/hooks/use-now" description="Reach for it when you show the current time or a now line that ticks on the minute." />

  <Card title="useDocumentVisibility" href="/docs/hooks/use-document-visibility" description="Reach for it when work nobody can see should stop while the tab is hidden: polling, a video, a timer." />
</Cards>

### Intl [#intl]

<Cards>
  <Card title="useLocale" href="/docs/hooks/use-locale" description="Reach for it when you format dates or numbers and need the active BCP-47 tag." />

  <Card title="useTimeZone" href="/docs/hooks/use-time-zone" description="Reach for it when you show times and need the active IANA zone." />
</Cards>

### State [#state]

<Cards>
  <Card title="useUncontrolled" href="/docs/hooks/use-uncontrolled" description="Reach for it when your component should take value/defaultValue/onChange like a kit one." />

  <Card title="useDisclosure" href="/docs/hooks/use-disclosure" description="Reach for it when you need an open/closed boolean with open, close and toggle." />

  <Card title="usePagination" href="/docs/hooks/use-pagination" description="Reach for it when you draw a pager of your own or page a list on the client." />

  <Card title="useLocalStorage" href="/docs/hooks/use-local-storage" description="Reach for it when a piece of state should survive a reload and stay in sync across tabs." />

  <Card title="useDebouncedValue / useDebouncedCallback" href="/docs/hooks/use-debounced" description="Reach for it when fast changes, like keystrokes in a search box, should act once the user pauses." />
</Cards>

### DOM & refs [#dom--refs]

<Cards>
  <Card title="useIsomorphicLayoutEffect" href="/docs/hooks/use-isomorphic-layout-effect" description="Reach for it when you must measure or write the DOM before paint, without the SSR warning." />

  <Card title="useMergedRefs" href="/docs/hooks/use-merged-refs" description="Reach for it when a component keeps its own ref to a node and must also forward the caller's ref." />

  <Card title="useElementSize" href="/docs/hooks/use-element-size" description="Reach for it when a layout depends on a number CSS can't give you, like how many columns or pills fit in an element's width." />

  <Card title="useInView" href="/docs/hooks/use-in-view" description="Reach for it when something should happen as an element scrolls into view: lazy media, the next page of a list, an entrance that plays once." />

  <Card title="useScrollSpy" href="/docs/hooks/use-scroll-spy" description="Reach for it when a table of contents of your own should follow the heading being read, and scroll to one below a sticky header." />
</Cards>

### Interaction [#interaction]

<Cards>
  <Card title="useHotkey" href="/docs/hooks/use-hotkey" description="Reach for it when a keyboard shortcut like mod+k should run a handler: page-wide, outside or only inside text fields, in a focused or hovered element, and quiet while an overlay is open above it." />
</Cards>

### Files [#files]

<Cards>
  <Card title="useFileQueue" href="/docs/hooks/use-file-queue" description="Reach for it when files upload through your own transport, with concurrency, cancel and retry." />

  <Card title="useObjectUrl" href="/docs/hooks/use-object-url" description="Reach for it when you show a picked or dropped file in an img, video or object." />
</Cards>

### Integration [#integration]

<Cards>
  <Card title="useTheme" href="/docs/hooks/use-theme" description="Reach for it when you build a light/dark/system switch." />

  <Card title="useLinkComponent" href="/docs/hooks/use-link-component" description="Reach for it when a component of your own renders links and should use the app's router Link." />

  <Card title="useOpenIndex" href="/docs/hooks/use-open-index" description="Reach for it when a collection of your own should open its items in a Lightbox, or a viewer should open a Gallery's." />
</Cards>

### Dev [#dev]

<Cards>
  <Card title="useLogger" href="/docs/hooks/use-logger" description="Reach for it when you debug a component's mounts, updates and unmounts in the console." />
</Cards>

### Component hooks [#component-hooks]

These belong to one component and are documented on its page.

<Cards>
  <Card title="useTable" href="/docs/data-table" description="TanStack's own hook, for composing the Table parts yourself. Register dataTableFeatures to reuse DataTable's pieces." />

  <Card title="useSchedule" href="/docs/schedule#selection--navigating-between-views" description="Reach for it when clicks should navigate a Schedule: view, date and selection state plus goTo handlers." />

  <Card title="useScheduleSelection" href="/docs/schedule#usescheduleselection" description="Reach for it when a view of your own needs Schedule's selection model." />

  <Card title="useCamera" href="/docs/camera#usecamera" description="Reach for it when you compose the Camera parts around your own layout." />

  <Card title="usePhotoCapture" href="/docs/photo-capture#composable-parts" description="Reach for it when you arrange the photo-capture steps yourself." />

  <Card title="usePillOverflow" href="/docs/pills-input#usepilloverflow" description="Reach for it when a row of pills of your own should cap at a number of lines with a +N counter." />
</Cards>

A few compound components also expose a **context hook**, which reads the component's state from a part of your own rendered inside it: [`useCameraContext`](/docs/camera#a-file-alternative), [`usePhotoCaptureContext`](/docs/photo-capture#composable-parts), [`useImageCropperContext`](/docs/image-cropper#export) and [`useAppShell`](/docs/app-shell#useappshell).
