Hooks
The React hooks exported from @gio.js/react: the router, the URL, the locale, form state and WebSockets.
tsx
import {
usePathname,
useParams,
useSearchParams,
useRouter,
useLocale,
useGioFormState,
useWebSocket,
} from '@gio.js/react';Router and URL
These read the route the server matched. The value travels with the page, so the server render and the hydration render agree, and after a soft navigation hydrated components read the new page's values.
| Hook | Returns |
|---|---|
usePathname() | The path, without query, hash or locale prefix: '/blog/hello'. |
useParams<T>() | The dynamic segments: { id: '42' }, typed from a route pattern. |
useSearchParams() | The query as a read-only URLSearchParams. |
useRouter() | { push, replace, back, forward, refresh, prefetch } - one stable object. |
useLocale() | The request locale, '' without [i18n]. |
app/posts/[id]/toolbar.tsx
import { usePathname, useParams, useRouter, useSearchParams } from '@gio.js/react';
export function Toolbar() {
const pathname = usePathname(); // '/posts/42'
const { id } = useParams<'/posts/:id'>(); // '42'
const tab = useSearchParams().get('tab'); // 'comments' or null
const router = useRouter();
return (
<button onClick={() => void router.push(`${pathname}?tab=comments`, { scroll: false })}>
Comments on post {id} {tab === 'comments' ? '(open)' : ''}
</button>
);
}Forms
| Hook | Returns |
|---|---|
useGioFormState() | { pending, lastResult } of the enclosing <GioForm>. |
Realtime
| Hook | Returns |
|---|---|
useWebSocket(url, options) | { send, lastMessage, readyState, reconnectAttempts, isReconnecting, close, reconnect }, with automatic reconnects. |
Where hooks work
- Pages and nested layouts are rendered on the server and hydrated in the browser: hooks work there as in any React app. GioJS has no Server Components, so there is no
'use client'directive to add. - The root layout (
app/layout.tsx) is rendered on the server only. The URL hooks return the values of the page loaded in full and are not updated by soft navigations, and effects never run there, souseWebSocketnever connects. - Outside a tree GioJS rendered - a component in a unit test or a separate React root - the URL hooks fall back to
window.location(and'/',{}on the server), anduseLocaletodocument.documentElement.lang. - To navigate outside components, use
navigate().