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