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

ClientOnly.tsx

68 lines1.7 KB

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
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 */
31export function ClientOnly({ children, fallback = null }: ClientOnlyProps) {
32 return useHydrated() ? (
33 <React.Fragment>{children}</React.Fragment>
34 ) : (
35 <React.Fragment>{fallback}</React.Fragment>
36 )
38​
39/**
40 * Return a boolean indicating if the JS has been hydrated already.
41 * When doing Server-Side Rendering, the result will always be false.
42 * When doing Client-Side Rendering, the result will always be false on the
43 * first render and true from then on. Even if a new component renders it will
44 * always start with true.
45 *
46 * @example
47 * ```tsx
48 * // Disable a button that needs JS to work.
49 * let hydrated = useHydrated()
50 * return (
51 * <button type="button" disabled={!hydrated} onClick={doSomethingCustom}>
52 * Click me
53 * </button>
54 * )
55 * ```
56 * @returns True if the JS has been hydrated already, false otherwise.
57 */
58function useHydrated(): boolean {
59 return React.useSyncExternalStore(
60 subscribe,
61 () => true,
62 () => false,
63 )
65​
66function subscribe() {
67 return () => {}