forked from toss/react-simplikit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseIsClient.ts
More file actions
48 lines (45 loc) · 1.24 KB
/
useIsClient.ts
File metadata and controls
48 lines (45 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { useEffect, useState } from 'react';
/**
* @description
* `useIsClient` is a React hook that returns `true` only in the client-side environment.
* It is primarily used to differentiate between client-side and server-side rendering (SSR).
* The state is set to `true` only after the component is mounted in the client-side environment.
*
* @returns {boolean} Returns `true` in a client-side environment, and `false` otherwise.
*
* @example
* function ClientSideContent() {
* const isClient = useIsClient();
*
* if (!isClient) {
* return <div>Loading...</div>; // Rendered on the server side
* }
*
* return <div>Client-side rendered content</div>; // Rendered on the client side
* }
*
* @example
* function ClientOnlyMap() {
* const isClient = useIsClient();
*
* if (!isClient) return null;
*
* return <div id="map" />;
* }
*
* @example
* function ClientTheme() {
* const isClient = useIsClient();
*
* const theme = isClient ? localStorage.getItem('theme') : 'light';
*
* return <div>Current theme: {theme}</div>;
* }
*/
export function useIsClient() {
const [isClient, setIsClient] = useState(false);
useEffect(function syncClientState() {
setIsClient(true);
}, []);
return isClient;
}