-
-
Notifications
You must be signed in to change notification settings - Fork 423
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
useDarkMode resets #512
Comments
|
Same thing here. Did a few tests, my guess is that the function in I think this there's a specific case that is not treated: when no value is set on local storage, I'm not sure what's the best way to fix this problem, since it seems to be related to other hooks and the way they handle the default values. |
Hi all, thanks for the bug report, feel free to open a PR, I will check it in priority |
Just created #557 The change in And that should fix the |
Ah, been finding this too. The chosen option is lost on a refresh as localStorage is reset. That explains why! |
I have tripped on this issue too. Fixed by copying the hook and commenting out import {
useIsomorphicLayoutEffect,
useLocalStorage,
useMediaQuery,
} from 'usehooks-ts'
const COLOR_SCHEME_QUERY = '(prefers-color-scheme: dark)'
const LOCAL_STORAGE_KEY = 'usehooks-ts-dark-mode'
type DarkModeOptions = {
defaultValue?: boolean
localStorageKey?: string
initializeWithValue?: boolean
}
type DarkModeReturn = {
isDarkMode: boolean
toggle: () => void
enable: () => void
disable: () => void
set: (value: boolean) => void
}
export function useDarkMode(options: DarkModeOptions = {}): DarkModeReturn {
const {
defaultValue,
localStorageKey = LOCAL_STORAGE_KEY,
initializeWithValue = true,
} = options
const isDarkOS = useMediaQuery(COLOR_SCHEME_QUERY, {
initializeWithValue,
defaultValue,
})
const [isDarkMode, setDarkMode] = useLocalStorage<boolean>(
localStorageKey,
defaultValue ?? isDarkOS ?? false,
{ initializeWithValue },
)
// FIX: https://github.com/juliencrn/usehooks-ts/issues/512
// Update darkMode if os prefers changes
// useIsomorphicLayoutEffect(() => {
// if (isDarkOS !== isDarkMode) {
// setDarkMode(isDarkOS)
// }
// }, [isDarkOS])
return {
isDarkMode,
toggle: () => {
setDarkMode(prev => !prev)
},
enable: () => {
setDarkMode(true)
},
disable: () => {
setDarkMode(false)
},
set: value => {
setDarkMode(value)
},
}
} |
Describe the bug
This is causing the
isDarkMode
to reset to the OS setting on every refresh. For some reason it works on production though.To Reproduce
Use it in local dev with next.js where the OS is set to dark mode.
Expected behavior
I expect my choice to be persisted.
Additional context
No response
The text was updated successfully, but these errors were encountered: