I am using reactjs
with nextjs
, i am having the following problem.
When the page is loaded I have to set a variable which should tell me if user is using dark mode or not.
I did the following, but I'm not sure if it's correct.
I had to set a value, because if I use window inside useState
without using useEffect
, it gives me problems with nextjs
.
const [darkMode, setDarkMode] = useState(false);
useEffect(() => {
setDarkMode(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)
const modeMe = (e) => {
setDarkMode(!!e.matches);
}
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', modeMe);
return window.matchMedia('(prefers-color-scheme: dark)').removeListener(modeMe);
}, []);
or
const useDeviceMode = () => {
const [darkMode, setDarkMode] = useState(false);
useEffect(() => {
setDarkMode(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)
const modeMe = e => { setDarkMode(!!e.matches); }
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', modeMe);
return window.matchMedia('(prefers-color-scheme: dark)').removeListener(modeMe);
}, []);
return [darkMode, setDarkMode]
}
const [darkMode, setDarkMode] = useDeviceMode();
Can you give me some advice