1
votes

I have a page state, and when it get updated I wanted to add new items to another state, in this case a list state.

In the example below I used page as a dependency in the useEffect, but couldn't use list, since it would cause a infinite loop.

  const [list, setList] = useState([1, 2, 3, 4]);
  const [page, setPage] = useState(1);

  useEffect(() => {
    const newList = ["a", "b", "c", "d"];
    setList(list.concat(newList));
  }, [page]);

Even though, this is working, it triggers the exhaustive-deps lint rule. I read about the rule and understand that it is a bad idea to leave the dependency array without all used values, and I don't really want to just disable this rule.

What would be the correct approach to update list when page is updated in this case?

1

1 Answers

2
votes

You should use the callback version of the setList

  const [list, setList] = useState([1, 2, 3, 4]);
  const [page, setPage] = useState(1);

  useEffect(() => {
    const newList = ["a", "b", "c", "d"];
    setList(currentList => currentList.concat(newList));
  }, [page]);