use-dark-mode icon indicating copy to clipboard operation
use-dark-mode copied to clipboard

Doesnt work correctly with NextJS

Open dukesx opened this issue 4 years ago • 4 comments

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

dukesx avatar Dec 15 '20 16:12 dukesx

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

donavon avatar Dec 18 '20 12:12 donavon

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

dukesx avatar Dec 18 '20 13:12 dukesx

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 avatar Dec 18 '20 13:12 donavon

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.

donavon avatar Dec 18 '20 14:12 donavon