pacocoursey / next-themes

Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing
https://next-themes-example.vercel.app/
MIT License
5.01k stars 179 forks source link

[Bug]: Refreshing the page will reset it to light #299

Closed Pszz closed 2 months ago

Pszz commented 3 months ago

What happened?

When I setTheme toggle, LocalStorage successfully becomes dark. But when I refresh the page, it is reset to light

image image


- component.tsx

```tsx
'use client'
import { useTheme } from 'next-themes'
import { Switch } from '@nextui-org/react'
import React from 'react'

export function DarkMode() {
  const { setTheme, theme } = useTheme()
  return (
    <Switch
      size="sm"
      aria-label="Dark Mode"
      defaultSelected={theme === 'dark'}
      onValueChange={(isSelected) => {
        setTheme(isSelected ? 'dark' : 'light')
      }}
    />
  )
}

Version

"next-themes": "^0.3.0",

What browsers are you seeing the problem on?

Chrome

matagaralph commented 3 months ago

Can help reproduce this so i can help or at least figure out the issue. You can share the repository if possible.

Pszz commented 2 months ago

I know the problem. I use AtomWithStorage localStorage. When Atom defaults to Light, it does not get the correct content for the first time and returns the default value. As a result, even though I changed the theme to Dark and successfully stored it in the localStorage. After I refreshed the page, it still returned the default value of Light.