use-dark-mode
use-dark-mode copied to clipboard
Doesnt work correctly with NextJS
I am trying to use this with Next JS in _app.js but it seems that despite SSR support, there is some issue. Mechanism:
- Fetch from System/Local Storage on first server render (SSR) in _App.js
- "Value" argument from useDarkMode is passed to a theme switcher
- in other components, i use "enable" and "disable" from useDarkMode to switch between light and dark mode
- "Value" doesn't change. Need to refresh page two times or more in order to make it work
No Error in console. It just doesn't change useDarkMode "value" prop no matter how many times i enable() or disable().
- Windows 10
- useDarkMode latest version
- Next JS 10
- Node JS 14.15
do you have a small app that I can try this out on?
do you have a small app that I can try this out on?
@donavon here you go https://github.com/dukesx/css-theme-switcher-sample
useDarkMode
keeps state, so there's no reason to use your own setState
. I changed your code and this works for me:
const { value } = useDarkMode(false, {
classNameDark: 'dark',
});
// const [dark, setDark] = useState(value);
const dark = value;
Also, in your implementation, the value returned from useDarkMode
was only used to set the initial value of useState
, so it would never change.
In nav.js
, you can just to this:
const { toggle } = useDarkMode();
then
{theme == 'dark' ? (
<i class="ri-sun-line ri-xl" onClick={toggle}></i>
) : (
<i class="ri-moon-line ri-xl" onClick={toggle}></i>
)}
No lambda function needed for the onClick
handler. Also, you don't need to call disable
or enable
when toggle
will work in both cases, although there's nothing wrong with explicitly calling each.