I just want to use useEffect
for once on page render but it gives me a warning about adding todos
as a parameter to my effect
, if I do that it will run every single time when the todos
state is changing.
how can I solve that?
useEffect(() => {
if (localStorage.getItem("todos") === null) {
localStorage.setItem("todos", JSON.stringify([]));
} else {
let localTodos = localStorage.getItem("todos", JSON.stringify(todos));
console.log(localTodos);
}
}, []);
CodePudding user response:
It is due to use todos in your useEffect code and just a warning that you can ignore it or add it to the dependency and use an if statement
useEffect(() => {
if (your condition to run this code once){
if (localStorage.getItem("todos") === null) {
localStorage.setItem("todos", JSON.stringify([]));
} else {
let localTodos = localStorage.getItem("todos", JSON.stringify(todos));
console.log(localTodos);
}
}
}, [todos]);
CodePudding user response:
You can use a custom useLocalStorage hook. Which works like useState but it will get its initial state from local storage if the provided local storage key exists.
https://usehooks.com/useLocalStorage/
CodePudding user response:
Not all warnings should be ignored but this one can be, so just add that comment in your code and it will remove the warning for that line.
useEffect(() => {
if (localStorage.getItem("todos") === null) {
localStorage.setItem("todos", JSON.stringify([]));
} else {
let localTodos = localStorage.getItem("todos", JSON.stringify(todos));
console.log(localTodos);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);