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

Requires 2 clicks when reload on darkMode.value true #80

Open yudyananda opened 3 years ago

yudyananda commented 3 years ago

Hi, i'm using gatsby here. I found out that the toggle didn't work well with <input> onChange. It requires 2 clicks for state changes. This behaviour occurs when we reload the page with darkMode.value true

Here is the component

import * as React from 'react';
import useDarkMode from 'use-dark-mode';

const DarkmodeToggle = () => {

    const { toggle, value } = useDarkMode(false)

    return (
        <div>
            <label>
                <input
                    type="checkbox"
                    checked={value}
                    onChange={toggle}
                />  
            </label>
        </div>
    )
}

export default DarkmodeToggle

anyone here have the same issue?

lukasoppermann commented 3 years ago

I have a similar issue using a normal button to toggle though.

yudyananda commented 3 years ago

@lukasoppermann interesting, in my case button works like a charm. My 2 cents is try to render the button in the client side.

if (typeof window === 'undefined') return null;
markdost commented 3 years ago

Same here when only using a checkbox it does not change back to light mode and have to click twice. With the buttons it works as expected.

        <input
          type="checkbox"
          className="custom-control-input"
          id="darkmodeSwitch"
          onChange={darkMode.toggle}
          checked={darkMode.value}
        />

hmm, I guess I solved it by adding onClick={darkMode.disable}