use-os (use-os)
Detects the user's operating system.
v0.1.0
Usage
import { use-os } from "@/hooks"
1"use client";
2
3import {
4 Card,
5 CardContent,
6 CardDescription,
7 CardFooter,
8 CardHeader,
9 CardTitle,
10} from "@/components/ui/card";
11
12import { OS, useOS } from "@/components/hooks/use-os";
13
14export function UseOSDemo() {
15 const os = useOS();
16
17 console.log(os);
18
19 const osLabel: Record<OS, string> = {
20 [OS.Undetermined]: "Unable to determine the operating system.",
21 [OS.MacOS]: "MacOS",
22 [OS.IOS]: "iOS",
23 [OS.Windows]: "Windows",
24 [OS.Android]: "Android",
25 [OS.Linux]: "Linux",
26 };
27
28 return (
29 <Card className="w-full max-w-md relative">
30 <CardHeader>
31 <CardTitle>useOS</CardTitle>
32 <CardDescription>
33 This hook detects the user's operating system.
34 </CardDescription>
35 </CardHeader>
36 <CardContent className="space-y-4">
37 <p className="text-sm">Operating System detected:</p>
38 <div className="font-bold">{osLabel[os]}</div>
39 </CardContent>
40 <CardFooter className="gap-x-1">
41 <p className="text-sm text-muted-foreground">
42 Value returned from useOS:
43 </p>
44 <p className="text-sm">{os}</p>
45 </CardFooter>
46 </Card>
47 );
48}
49
Install
npx wkkkis-hooks add use-os
Options
Name | Type | Default | Description |
---|---|---|---|
This | — | — | hook does not accept any props. |
Returns — Properties
Name | Type | Default | Description |
---|---|---|---|
The | — | — | hook returns a value from the OS enum, not just a string. You can import and use the OS enum for type safety. |
Detection Logic
- The hook uses the browser's navigator.userAgent to detect the operating system.
- It distinguishes between macOS and iOS by checking for touch support on Mac devices.
- Returns one of: macos , ios , windows , android , linux , or undetermined .
SSR & Initial Value
- On the server, or if window / navigator is not available, the hook returns undetermined .
Enum Return Type
- The hook returns a value from the OS enum, not just a string. You can import and use the OS enum for type safety.
Best Practices & Caveats
- The hook is client-side only; on the server, it cannot detect the OS.
- User agent sniffing is not 100% reliable and may not detect all edge cases or future OSes.
- For best performance, use the hook at the top level of your component and avoid unnecessary re-renders.
Files in this hook
Source | Destination |
---|---|
files/use-os.ts | src/hooks/use-os.ts |