Perfect Next.js dark mode in 2 lines of code. Support System preference and any other theme with no flashing | BestofReactjs

PHOTO EMBED

Wed Jun 08 2022 18:22:55 GMT+0000 (Coordinated Universal Time)

Saved by @itsbrex #hyrdation #mismatch #tailwind #darkmode #dark #mode #fix

import { useTheme } from 'next-themes'

const ThemeChanger = () => {
  const [mounted, setMounted] = useState(false)
  const { theme, setTheme } = useTheme()

  // When mounted on client, now we can show the UI
  useEffect(() => setMounted(true), [])

  if (!mounted) return null

  return (
    <div>
      The current theme is: {theme}
      <button onClick={() => setTheme('light')}>Light Mode</button>
      <button onClick={() => setTheme('dark')}>Dark Mode</button>
    </div>
  )
}
content_copyCOPY

https://bestofreactjs.com/repo/pacocoursey-next-themes-react-nextjs-extensions#disable-transitions-on-theme-change