donavon / use-dark-mode

A custom React Hook to help you implement a "dark mode" component.
MIT License
1.28k stars 100 forks source link

Doesnt work correctly with NextJS #66

Open dukesx opened 3 years ago

dukesx commented 3 years ago

I am trying to use this with Next JS in _app.js but it seems that despite SSR support, there is some issue. Mechanism:

No Error in console. It just doesn't change useDarkMode "value" prop no matter how many times i enable() or disable().

donavon commented 3 years ago

do you have a small app that I can try this out on?

dukesx commented 3 years ago

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

donavon commented 3 years ago

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.

donavon commented 3 years ago

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.