ui: [bug]: Theme Provider creates hydration error in Next.js 15.0.1

Describe the bug

Implementing dark mode, and putting ThemeProvider into the layout is making hydration error in newest version of Next.js (15.0.1).

Screenshot 2024-10-24 at 12 05 15

Affected component/components

ThemeProvider

How to reproduce

  1. Do npm install next-themes
  2. Create ThemeProvider component.
  3. Wrap children in layout file

Codesandbox/StackBlitz link

https://ui.shadcn.com/docs/dark-mode/next

Logs

Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used


-className="dark"
-style={{color-scheme:"dark"}}


### System Info

```bash
Next.js 15.0.1

MacOS, Google Chrome

Before submitting

  • I’ve made research efforts and searched the documentation
  • I’ve searched for existing issues

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 96
  • Comments: 36

Commits related to this issue

Most upvoted comments

Hey, as it is marked on the doc, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

Thank you!

So this is not connected to Next.js 15? It’s still that old problem we had with ThemeProvider?

Here is the real fix :

'use client'

import * as React from 'react'
const NextThemesProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

import { type ThemeProviderProps } from 'next-themes/dist/types'
import dynamic from 'next/dynamic'

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

You have to dynamically import the theme provider from next-theme and you can now remove the suppressHydrationWarning from your <html> tag

Hey, as it is marked on the doc, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}
'use client'

import * as React from 'react'
const NextThemesProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

import { type ThemeProviderProps } from 'next-themes/dist/types'
import dynamic from 'next/dynamic'

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

Thanks! It seems to be the correct solution in general, although I must clarify that something different has worked better for me, understanding that it slows down rendering, in small projects I have not noticed any difference. On the other hand, using dynamic with ssr: false has generated a small flash at the start that I prefer to avoid. I am quite new to this, I am probably making mistakes, so I would like to read them.

"use client";

import * as React from "react";
import { ThemeProvider as NextThemesProvider } from "next-themes";
import { type ThemeProviderProps } from "next-themes/dist/types";
import { useEffect, useState } from "react";

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    setIsLoaded(true);
  }, []);

  if (!isLoaded) {
    return null;
  }

  return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

Hey, as it is marked on the doc, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

Thank you! So this is not connected to Next.js 15? It’s still that old problem we had with ThemeProvider?

Here is the real fix :

'use client'

import * as React from 'react'
const NextThemesProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

import { type ThemeProviderProps } from 'next-themes/dist/types'
import dynamic from 'next/dynamic'

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

You have to dynamically import the theme provider from next-theme and you can now remove the suppressHydrationWarning from your <html> tag

Amazing! That’s exactly what I needed!

Thank you! You’re a true web dev warrior!

The Solution

add this before your theme return code

  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;

it should look like this

"use client"

import { useState, useEffect } from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"

export function ThemeProvider({
  children,
  ...props
}: React.ComponentProps<typeof NextThemesProvider>) {

  // solution start
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) return null;

  // solution end

  //main theme return
  return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}


I think this will help you

This solution is effective in preventing errors during SSR, but it isn’t an “elegant” approach. Dynamically loading the next-themes library can lead to undesired outcomes, such as a “snapshot of the wrong theme” at the start.

That means that there is somewhere an issue, either with next-theme or with NextJs.

Now I think, I preffer having a “snapshot of the wrong theme” instead of suppressing all my hydration warning and troubleshouting during hours because nobody told me that i have put a <div> into an <p> in development mode.

But for the build, you’re right, you could just suppress hydration warnings by using env like :

<html suppressHydrationWarning={process.env.NODE_ENV === 'production'}>
<>{children}</>
</html>

And then in your theme-provider.tsx :

'use client'

import * as React from 'react'
import dynamic from 'next/dynamic'

import { type ThemeProviderProps } from 'next-themes/dist/types'
import { ThemeProvider as StaticProvider } from 'next-themes'
const DynProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	const NextThemeProvider =
		process.env.NODE_ENV === 'production' ? StaticProvider : DynProvider
	return <NextThemeProvider {...props}>{children}</NextThemeProvider>
}

@TheOrcDev @Medaillek This is the real fix with next 15

"use client";
import { useState, useEffect } from "react"
import dynamic from 'next/dynamic'

// import { ThemeProvider } from "next-themes";

const NextThemesProvider = dynamic(
    () => import('next-themes').then((e) => e.ThemeProvider),
    {
        ssr: false,
    }
)

export default function Providers({ children }: { children: React.ReactNode }) {

    const defaultTheme = typeof window !== "undefined" ? localStorage.getItem("theme") || "system" : "system"
    console.log("🚀 ~ Providers ~ defaultTheme:", defaultTheme)

    return (
        <NextThemesProvider
            attribute="class"
            enableSystem={true}
            defaultTheme={defaultTheme}
        >
            {children}
        </NextThemesProvider>
    );
}

Then after u can go ahead and import ur component in layout.tsx and wrap it around the body

app/layout.tsx

import NextThemeProvider from "@/util/next-theme-provider"

  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <link id="theme-link" rel="stylesheet" href="/themes/lara-light-blue/theme.css" />


      </head>
      <body className={`bg-[#FCFCFC] dark:bg-black ${inter.className}`}>

        <TanstackProvider>
          <NextThemeProvider >
            <PrimeReactProvider>
              <PrimeReactThemeSync>
                <ToastProvider>
                  <PrimeReactToastProvider>
                    <AuthProvider>

                      {children}

                    </AuthProvider>
                  </PrimeReactToastProvider>
                </ToastProvider>
              </PrimeReactThemeSync>
            </PrimeReactProvider>
          </NextThemeProvider>
        </TanstackProvider>

      </body>
    </html>
  );

For anyone who doesn’t want to scroll through all the text above: Here’s what I’ve found and confirmed—among all the solutions, adding suppressHydrationWarning to your HTML tag is the best solution for now!

Solution 1:

As it is marked on the next-themes Github Readme, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

This property only applies one level deep, so it won’t block hydration warnings on other elements.

Solution 2:

Less effective Solution: You need to dynamically import the ThemeProvider from next-theme, which allows you to remove the suppressHydrationWarning from your <html> tag.

'use client'

import * as React from 'react'
const NextThemesProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

import { type ThemeProviderProps } from 'next-themes/dist/types'
import dynamic from 'next/dynamic'

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

This solution effectively prevents errors during SSR but isn’t an “elegant” approach; but dynamically loading the next-themes library can result in undesired outcomes, such as displaying a “snapshot of the wrong theme” initially.

Verdict: It’s best to stick with Solution 1 for now until a proper solution is released.

This solution is effective in preventing errors during SSR, but it isn’t an “elegant” approach. Dynamically loading the next-themes library can lead to undesired outcomes, such as a “snapshot of the wrong theme” at the start.

The Solution

add this before your theme return code

const [mounted, setMounted] = useState(false);

useEffect(() => { setMounted(true); }, []);

if (!mounted) { return <>{children}</>; // Avoid hydration errors by not rendering the theme before mounting }

it should look like this

“use client”

import { useState, useEffect } from “react” import { ThemeProvider as NextThemesProvider } from “next-themes”

export function ThemeProvider({ children, …props }: React.ComponentProps<typeof NextThemesProvider>) {

// solution start const [mounted, setMounted] = useState(false);

useEffect(() => { setMounted(true); }, []);

if (!mounted) { return <>{children}</>; // Avoid hydration errors by not rendering the theme before mounting }

// solution end

//main theme return return <NextThemesProvider {…props}>{children}</NextThemesProvider> }

I think this will help you

This is not the right approach, because you will create two extra renders in local development and same for production.

Still facing with this issue. Any one have better solutions?

suppressHydrationWarning is work but I think this is not a real fix.

adding dynamic logic in themeProvider is also working but make another issue.

😦

just for information:

chakra-ui suggest add suppressHydrationWarning option at html tag in doc.

https://www.chakra-ui.com/docs/get-started/frameworks/next-app

  "dependencies": {
   "class-variance-authority": "^0.7.1",
   "clsx": "^2.1.1",
   "lucide-react": "^0.469.0",
   "next": "15.1.2",
   "next-themes": "^0.4.4",
   "react": "^19.0.0",
   "react-dom": "^19.0.0",
   "tailwind-merge": "^2.5.5",
   "tailwindcss-animate": "^1.0.7"
 },
 "devDependencies": {
   "@eslint/eslintrc": "^3",
   "@types/node": "^20",
   "@types/react": "^19.0.2",
   "@types/react-dom": "^19",
   "eslint": "^9",
   "eslint-config-next": "15.1.2",
   "postcss": "^8",
   "tailwindcss": "^3.4.1",
   "typescript": "^5"
 }
}

Hey, as it is marked on the doc, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

Thank you!

So this is not connected to Next.js 15? It’s still that old problem we had with ThemeProvider?

okay for me there was dependency issue for farmer-motion with next js 15 - react 19

├─┬ framer-motion 11.11.13
│ ├── ✕ unmet peer react@^18.0.0: found 19.0.0-rc-66855b96-20241106
│ └── ✕ unmet peer react-dom@^18.0.0: found 19.0.0-rc-66855b96-20241106
└─┬ next-themes 0.3.0
  ├── ✕ unmet peer react@"^16.8 || ^17 || ^18": found 19.0.0-rc-66855b96-20241106
  └── ✕ unmet peer react-dom@"^16.8 || ^17 || ^18": found 19.0.0-rc-66855b96-20241106 

also weirdly could not find the ThemeProviderProps

import { type ThemeProviderProps } from "next-themes/dist/types";

So, I downgrade "next-themes": "^0.4.3", to "next-themes": "^0.3.0",

no hydration error now !!! happy 😁

A simple fix, no suppressHydrationWarning, no dynamic import.

Disable theme related hydration warnings on purpose for dev and render immediatly for prod.

next-theme-provider.tsx

"use client";

import { ThemeProvider, type ThemeProviderProps } from "next-themes";
import { useEffect, useState } from "react";

const initialRender = process.env.NODE_ENV === "production";

export function NextThemeProvider(props: ThemeProviderProps) {
  const [shouldRender, setShouldRender] = useState(initialRender);
  useEffect(() => {
    if (!initialRender) {
      setShouldRender(true);
    }
  }, []);
  return shouldRender ? <ThemeProvider {...props} /> : props.children;
}

Example usage

<html lang="en">
  <body
    className={`${geistSans.variable} ${geistMono.variable} ${zillaSlab.variable} antialiased`}
  >
    <NextThemeProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
    >
      {children}
    </NextThemeProvider>
  </body>
</html>

Hey, as it is marked on the doc, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

Thank you! So this is not connected to Next.js 15? It’s still that old problem we had with ThemeProvider?

Here is the real fix :

'use client'

import * as React from 'react'
const NextThemesProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

import { type ThemeProviderProps } from 'next-themes/dist/types'
import dynamic from 'next/dynamic'

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

You have to dynamically import the theme provider from next-theme and you can now remove the suppressHydrationWarning from your <html> tag

I was facing this problem too and this works well. Thank you @SyahmiRafsan

But it blinking on reload the page…(

@birarr follow this guide, you probably don’t have the theme-provider file.

Actually, I do have this on my project already. But I was able to fix it now, adding the “suppressHydrationWarning” on my html tag.

Hey, as it is marked on the doc, you should add suppressHydrationWarning on your html tag :

import { ThemeProvider } from "@/components/theme-provider"

export default function RootLayout({ children }: RootLayoutProps) {
  return (
    <>
      <html lang="en" suppressHydrationWarning>
        <head />
        <body>
          <ThemeProvider
            attribute="class"
            defaultTheme="system"
            enableSystem
            disableTransitionOnChange
          >
            {children}
          </ThemeProvider>
        </body>
      </html>
    </>
  )
}

Thank you! So this is not connected to Next.js 15? It’s still that old problem we had with ThemeProvider?

Here is the real fix :

'use client'

import * as React from 'react'
const NextThemesProvider = dynamic(
	() => import('next-themes').then((e) => e.ThemeProvider),
	{
		ssr: false,
	}
)

import { type ThemeProviderProps } from 'next-themes/dist/types'
import dynamic from 'next/dynamic'

export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
	return <NextThemesProvider {...props}>{children}</NextThemesProvider>
}

You have to dynamically import the theme provider from next-theme and you can now remove the suppressHydrationWarning from your <html> tag

It did fix the hydration error for me but it caused this:

--><template
      data-dgst="BAILOUT_TO_CLIENT_SIDE_RENDERING"
      data-msg="Switched to client rendering because the server rendering errored:

Bail out to client-side rendering: next/dynamic"
      data-stck="Switched to client rendering because the server rendering errored:

Error: Bail out to client-side rendering: next/dynamic
    at BailoutToCSR (webpack-internal:///(ssr)/./node_modules/next/dist/shared/lib/lazy-dynamic/dynamic-bailout-to-csr.js:15:15)
    at react-stack-bottom-frame (

Not sure how will this affect the SEO of my page?

The suppressHydrationWarning won’t work for deeper server-client differences like a Theme switcher:

<div className="flex flex-col items-center space-y-2">
  <Label>Theme</Label>
  <RadioGroup
    value={theme}
    onValueChange={setTheme}
    className="flex justify-center gap-4"
  >
    <div className="flex items-center space-x-2">
      <RadioGroupItem value="dark" id="dark" />
      <Label htmlFor="dark">Dark</Label>
    </div>
    <div className="flex items-center space-x-2">
      <RadioGroupItem value="light" id="light" />
      <Label htmlFor="light">Light</Label>
    </div>
  </RadioGroup>
</div>

Disabling ssr will lead to a flash which is not a fix but rather a reshaped issue.

Does anyone know why the current theme is not available when ssr?