Dark mode bukan cuma toggle warna — ada banyak hal yang perlu diperhatikan agar implementasinya smooth.
Setup next-themes
npm install next-themes
Di root layout:
import { ThemeProvider } from "next-themes";
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
</ThemeProvider>
CSS Variables Approach
:root {
--background: #ffffff;
--foreground: #0a0a0a;
--muted: #6b7280;
}
.dark {
--background: #0a0a0a;
--foreground: #fafafa;
--muted: #9ca3af;
}
Toggle Component
"use client";
import { useTheme } from "next-themes";
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<button onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>
{theme === "dark" ? "☀️" : "🌙"}
</button>
);
}
Gotchas
- Hydration mismatch — Gunakan suppressHydrationWarning di html tag
- Flash of wrong theme — next-themes handles ini dengan script injection
- System preference — enableSystem=true untuk follow OS setting
- Images — Siapkan versi light dan dark untuk logo/ilustrasi
Dark mode yang baik meningkatkan UX dan mengurangi eye strain.