🍏 iOS / Mac OSInstall iOS 27 today — there’s no reason to wait(12.09.2026 um 15:00 Uhr)
🔧 AI Nachrichten How I’m using Codex and ChatGPT on my Mac(01.09.2026 um 00:00 Uhr)
🕵️ SicherheitslückenProFTPD mod_sql post-authentication SQLi RCE(06.09.2026 um 18:21 Uhr)
🕵️ Sicherheitslücken[remote] CVE-2026-42167 - ProFTPD mod_sql post-authentication SQLi - RCE(25.08.2026 um 02:00 Uhr)
🕵️ Sicherheitslücken[webapps] C-MOR 6.0104 - Cross-Site Scripting (XSS)(31.08.2026 um 02:00 Uhr)
🕵️ Sicherheitslücken[webapps] CubeCart 6.7.4 - Stored XSS(31.08.2026 um 02:00 Uhr)
🍏 iOS / Mac OSInstall iOS 27 today — there’s no reason to wait(12.09.2026 um 15:00 Uhr)
🔧 AI Nachrichten How I’m using Codex and ChatGPT on my Mac(01.09.2026 um 00:00 Uhr)
🕵️ SicherheitslückenProFTPD mod_sql post-authentication SQLi RCE(06.09.2026 um 18:21 Uhr)
🕵️ Sicherheitslücken[remote] CVE-2026-42167 - ProFTPD mod_sql post-authentication SQLi - RCE(25.08.2026 um 02:00 Uhr)
🕵️ Sicherheitslücken[webapps] C-MOR 6.0104 - Cross-Site Scripting (XSS)(31.08.2026 um 02:00 Uhr)
🕵️ Sicherheitslücken[webapps] CubeCart 6.7.4 - Stored XSS(31.08.2026 um 02:00 Uhr)

🔧 Programmierung 🕛 vor 3 Monaten 4 Min Lesezeit
0

How to Implement Dark/Light Mode with No Flickers in Next.js

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Implementing a dark mode toggle in Next.js seems straightforward until you run into UI flickers, React hydration mismatch errors, or styling conflicts.



Instead of implementing this manually and fighting with local storage and system preferences, we will use a popular npm package called next-themes. We will also cover how to avoid common performance traps and how to configure this for the newest Tailwind CSS v4.



Let’s dive in!






Step 1: Install next-themes



First, we need to add the package to our project. You can use pnpm or npm:



Bash




CODE
pnpm add next-themes
# or
npm install next-themes









Step 2: Create the Theme Provider



Since Next.js App Router components are Server Components by default, we need a Client Component to handle our theme state.



Create a provider.tsx file in your ./app folder:



TypeScript




CODE
// app/provider.tsx
"use client";
import { ThemeProvider } from "next-themes";
export default function NextThemeProvider({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
{children}
</ThemeProvider>
);
}









Step 3: Wrap Your Layout



Next, modify your layout.tsx file by importing NextThemeProvider and wrapping your children with it.




Crucial Fix: Becausenext-themes dynamically updates the<html> tag on the client side, it will trigger a React Hydration Mismatch error. You must addsuppressHydrationWarning to your<html> tag to safely prevent this error.




TypeScript




CODE
// app/layout.tsx
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import NextThemeProvider from "./provider";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
suppressHydrationWarning // <-- This is required!
>
<body className="min-h-full flex flex-col">
<NextThemeProvider>{children}</NextThemeProvider>
</body>
</html>
);
}









Step 4: Configure Tailwind CSS (The v3 vs v4 Gotcha)



How you configure Tailwind depends on the version you are using.






Get Ahmed Rabee’s stories in your inbox



Join Medium for free to get updates from this writer.



Subscribe



Subscribe



Remember me for faster sign in



If you are using Tailwind v3: You must tell Tailwind to use class-based dark mode by adding darkMode: "class" to your tailwind.config.ts:



TypeScript




CODE
import { Config } from "tailwindcss";
const config: Config = {
darkMode: "class", // <-- Add this
content: [\
"./app/**/*.{js,jsx,ts,tsx}",\
// ...\
],
// ...
};
export default config;






If you are using Tailwind v4 (The Modern Way): Tailwind v4 ignores the config file by default. If you don’t explicitly tell it to look for the .dark class, your text colors won't change because Tailwind will stubbornly track your OS system preferences instead of your toggle button!



To fix this, open your app/globals.css and add a @custom-variant directive right below the Tailwind import:



CSS




CODE
/* app/globals.css */
@import "tailwindcss";
/* Force Tailwind v4 to use next-themes class-based dark mode */
@custom-variant dark (&:where(.dark, .dark *));









Step 5: The “Effect-Free” Theme Switcher



To toggle the theme, we destructure the useTheme hook.



Many developers use a useState and useEffect hook here to delay rendering the button until the client loads (the "mounted" pattern). Do not do this. Calling state synchronously in an effect causes a cascading render that hurts performance.



Instead, we can render both the “Light” and “Dark” labels statically and use Tailwind’s block dark:hidden classes to instantly show the correct one. This results in perfect hydration and zero flickers!



Create a ToggleThemeBtn.tsx in your components folder:



TypeScript




CODE
// components/ToggleThemeBtn.tsx
"use client";
import { useTheme } from "next-themes";
export function ToggleThemeBtn() {
const { resolvedTheme, setTheme } = useTheme();
return (
<button
onClick={() => setTheme(resolvedTheme === "dark" ? "light" : "dark")}
className="px-4 py-2 bg-gray-200 dark:bg-gray-800 text-black dark:text-white rounded-md transition-colors"
>
{/* This spans shows ONLY in light mode */}
<span className="block dark:hidden">Switch to Dark Mode</span>

{/* This spans shows ONLY in dark mode */}
<span className="hidden dark:block">Switch to Light Mode</span>
</button>
);
}









Conclusion



By relying on CSS to handle the UI swapping and ensuring we use the correct suppressHydrationWarning and Tailwind v4 directives, we've created a lightning-fast, flicker-free dark mode toggle.



No cascading React renders, no hydration errors, just a seamless user experience!

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
Debian 11 Long Term Support reaches end-of-life
1 Quelle
Updated Debian 13: 13.7 released
1 Quelle
USN-8741-1: Flatpak vulnerabilities
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to Implement Dark/Light Mode with No Flickers in Next.js

Thematisch verwandte Begriffe: Implement, DarkLight, Mode, with · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...