Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

ClientOnly.tsx

67 lines1.8 KB

1'use client'
2​
3import React from 'react'
4​
5const getSnapshot = () => true
6const getServerSnapshot = () => false
7​
8export interface ClientOnlyProps {
9 /**
10 * The children to render when the JS is loaded.
11 */
12 children: React.ReactNode
13 /**
14 * The fallback component to render if the JS is not yet loaded.
15 */
16 fallback?: React.ReactNode
18​
19/**
20 * Render the children only after the JS has loaded client-side. Use an optional
21 * fallback component if the JS is not yet loaded.
22 *
23 * @example
24 * Render a Chart component if JS loads, renders a simple FakeChart
25 * component server-side or if there is no JS. The FakeChart can have only the
26 * UI without the behavior or be a loading spinner or skeleton.
27 *
28 * ```tsx
29 * return (
30 * <ClientOnly fallback={<FakeChart />}>
31 * <Chart />
32 * </ClientOnly>
33 * )
34 * ```
35 */
36export function ClientOnly({ children, fallback = null }: ClientOnlyProps) {
37 return <React.Fragment>{useHydrated() ? children : fallback}</React.Fragment>
39​
40/**
41 * Return a boolean indicating if the JS has been hydrated already.
42 * When doing Server-Side Rendering, the result will always be false.
43 * When doing Client-Side Rendering, the result will always be false on the
44 * first render and true from then on. Even if a new component renders it will
45 * always start with true.
46 *
47 * @example
48 * ```tsx
49 * // Disable a button that needs JS to work.
50 * let hydrated = useHydrated()
51 * return (
52 * <button type="button" disabled={!hydrated} onClick={doSomethingCustom}>
53 * Click me
54 * </button>
55 * )
56 * ```
57 * @returns True if the JS has been hydrated already, false otherwise.
58 */
59export function useHydrated(): boolean {
60 return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
62​
63function subscribe() {
64 return () => {
65 // noop
66 }