This is a warning that React gives back. By this React wants us to use the setTodoList
and todoList
are the dependencies in the array of the 2nd argument.
useEffect(() => {
if (priority) {
setTodoList(
todoList.slice().sort(function (a, b) {
return a.priority - b.priority; // By priority
})
);
} else {
setTodoList(
todoList.slice().sort(function (a, b) {
return a.title.localeCompare(b.title); // By name
})
);
}
// Watches priority for sortButton, and editing, adding and deleting modes etc.
}, [priority, changing, show, removing,todoList,setTodoList]); // Added todoList and setTodoList as dependencies
However we have to be cautious of not creating an infinite loop
in our Component. Because setTodoList()
will trigger a re-render of the component and again useEffect()
will be invoked. This will keep happening.
And if this happens The solution is to use useCallback()
around setTodoList
to prevent re-creation of the function every time (We may need to format our code a bit as well)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…