I am a newbie in React, and I am working on a dark-mode function. It has a warning and I would like to ask what is the best way to fix it. Thanks
20:21 warning Assignments to the 'theme' variable from inside React Hook useEffect will be lost after each render. To preserve the value over time, store
it in a useRef Hook and keep the mutable value in the '.current' property. Otherwise, you can move this variable directly inside useEffect
import React from "react";
import { RiContrastLine } from 'react-icons/ri';
import { useEffect } from "react";
const DarkMode = () => {
let body = "";
if (typeof document !== "undefined") {
body = document.body;
}
let clickedClass = "clicked";
const lightTheme = "light-mode";
const darkTheme = "dark-mode";
let theme;
useEffect(() => {
if (localStorage) {
theme = localStorage.getItem("theme");
if (theme === darkTheme) {
}
}
if (theme === lightTheme || theme === darkTheme) {
body.classList.add(theme);
} else {
body.classList.add(lightTheme);
}
}, [])
const switchTheme = (e) => {
if (theme === darkTheme) {
body.classList.replace(darkTheme, lightTheme);
localStorage.setItem("theme", "light-mode");
e.target.classList.remove(clickedClass);
theme = lightTheme;
} else {
body.classList.replace(lightTheme, darkTheme);
localStorage.setItem("theme", "dark-mode");
e.target.classList.add(clickedClass);
theme = darkTheme;
}
};
return (
<button className='general-menu-button' type="button" onClick={(e) => switchTheme(e)}>
<RiContrastLine />
</button>
);
};
export default DarkMode;
I have tried to add useRef, but with my limited understanding, it turned out another error.
I would like to know how to resolve the warning
Why not store the theme in state? This will persist the value across rerenders
Import useState at the top of your file:
import { useState } from 'react'
replace
let theme;
with
const [theme, setTheme] = useState(/* initial theme here */)
then replace anytime you assign theme to a setTheme call eg
theme = localStorage.getItem('theme')
// becomes
setTheme(localStorage.getItem('theme'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.