I am trying to Save to Local in React and my app is working, but I cannot deploy it because of this warning. The warning is:
React Hook useEffect has a missing dependency: 'saveLocalTodos'. Either include it or remove the dependency array
And my code is:
// Run once when the app starts
useEffect(() => {
getLocalTodos();
}, []);
// useEffect
useEffect(() => {
// Function
function filterHandler() {
switch (status) {
case `completed`:
setFilteredTodos(todos.filter((todo) => todo.completed === true));
break;
case `uncompleted`:
setFilteredTodos(todos.filter((todo) => todo.completed === false));
break;
default:
setFilteredTodos(todos);
break;
}
}
filterHandler();
saveLocalTodos();
}, [todos, status]);
// Save to Local
const saveLocalTodos = () => {
localStorage.setItem("todos", JSON.stringify(todos));
};
const getLocalTodos = () => {
if (localStorage.getItem("todos") === null) {
localStorage.setItem("todos", JSON.stringify([]));
} else {
let todoLocal = JSON.parse(localStorage.getItem(`todos`));
setTodos(todoLocal);
}
};
Just include your dependency in the dependencies array of
React.useEffect
then.You're using
saveLocalTodos
inside youruseEffect
but not defining it in the dependencies array. Normally, the rule of thumb is to include everything (functions, variables, state, props) which is used inside theuseEffect
to be in the dependencies array. Because your effect depends on them and should reinvoke itself once their value changes.Also, wrap your
saveLocalTodods
withReact.useCallback
because, in every re-render of your component, the function reference changes. Then your effect will be fired for no reason. Puttodos
in the dependencies array inside thesaveLocalTodos
. You want your function to change only when todos change. Otherwise, you will get stale todos.