next-themes icon indicating copy to clipboard operation
next-themes copied to clipboard

docs: :memo: Add simpler and more usefull exmaple for Avoid Hydration Mismatch using useThemeSwitcher custom hook

Open SeyyedKhandon opened this issue 1 year ago • 6 comments

useThemeSwitcher

The easiest way without LayoutShift problem is simply aplying it with a custom hook like this example:

import { useState, useEffect } from 'react'
import { useTheme } from 'next-themes'

const useThemeSwitcher = () => {
  const [mode, setMode] = useState("");
  const { theme, setTheme } = useTheme();

  useEffect(() => {
    setMode(theme);
  }, [theme]);

  return [mode, setTheme];
};

const ThemeSwitcher = () => {
  const [theme, setTheme] = useThemeSwitcher();
  return (
    <select value={theme} onChange={e => setTheme(e.target.value)}>
      <option value="system">System</option>
      <option value="dark">Dark</option>
      <option value="light">Light</option>
    </select>
  )
}
export default ThemeSwitcher

SeyyedKhandon avatar Apr 04 '23 11:04 SeyyedKhandon

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-themes-basic ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 4, 2023 11:02am
next-themes-tailwind ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 4, 2023 11:02am

vercel[bot] avatar Apr 04 '23 11:04 vercel[bot]

Hope this gets merged, the hydration problem needs a simple solution.

dinogomez avatar May 29 '23 08:05 dinogomez

hydration This custom hook did not solve the hydration error here... NextJS 13.4.9, Next-Themes 0.2.1, Tailwind 3.3.2

ttsoares avatar Jul 07 '23 18:07 ttsoares

hydration This custom hook did not solve the hydration error here... NextJS 13.4.9, Next-Themes 0.2.1, Tailwind 3.3.2

can you provide a reperex?( reproducible example)

SeyyedKhandon avatar Jul 07 '23 19:07 SeyyedKhandon

Sure. There is a piece of the system in a tar. demo_themes.zip

ttsoares avatar Jul 08 '23 00:07 ttsoares

Sure. There is a piece of the system in a tar. demo_themes.zip

Thank you, It would be very good if you could share with a codesandbox instead of zip file, so that we dont need to npm i and unrealted issues

SeyyedKhandon avatar Jul 08 '23 18:07 SeyyedKhandon

I am not sure when this was added, but there now is an example very similar to this already in the readme. Thanks anyways for your effort :)

trm217 avatar May 09 '24 15:05 trm217