惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
Docker
酷 壳 – CoolShell
酷 壳 – CoolShell
宝玉的分享
宝玉的分享
Martin Fowler
Martin Fowler
美团技术团队
量子位
M
MIT News - Artificial intelligence
Apple Machine Learning Research
Apple Machine Learning Research
阮一峰的网络日志
阮一峰的网络日志
博客园 - 叶小钗
博客园 - 三生石上(FineUI控件)
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
小众软件
小众软件
博客园 - 司徒正美
罗磊的独立博客
云风的 BLOG
云风的 BLOG
B
Blog RSS Feed
博客园 - 聂微东

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Implement Dark/Light Mode with No Flickers in Next.js
Ahmed Rabee · 2026-05-27 · via DEV Community

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

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

Enter fullscreen mode Exit fullscreen mode

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

// 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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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

// 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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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

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

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

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

Enter fullscreen mode Exit fullscreen mode

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

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

Enter fullscreen mode Exit fullscreen mode

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

// 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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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!