Open History to see the last commit
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
17}
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>
38}
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/**
61 * @internal
62 * callers whose output does not depend on hydration can keep the
63 * same snapshot on both sides, avoiding an unnecessary post-hydration render.
64 */
65export function useHydrated(enabled: boolean): boolean
66/** @internal */
67export function useHydrated(enabled = true): boolean {
68 return React.useSyncExternalStore(
69 subscribe,
70 getSnapshot,
71 enabled ? getServerSnapshot : getSnapshot,
72 )
73}
74β
75function subscribe() {
76 return () => {
77 // noop
78 }
79}