1

I'm trying to sort my object by their priority, however it get error about dependency that items also should be in dependency array. However if I put it there then it is neverending loop. How can I make error disappear with keeping whole functionality?

useEffect(() => {
  const sortItems = () => {
    const res = items.sort((a, b) => (priority > priority ? 1 : -1));
    setItems(res);
  };
  if (sortedProperty) {
    sortItems();
  }
}, [sortedProperty]);
Ramesh Reddy
  • 9,107
  • 3
  • 12
  • 28
Jacki
  • 471
  • 1
  • 11
  • 20
  • What is `sortedProperty`? Is it a boolean? If so, when is it false? – evolutionxbox May 10 '21 at 13:44
  • @evolutionxbox it is string at the beginning empty one but when i click on sorting i set it to setSortedProperty("priority), later I will probably want to add more sorts – Jacki May 10 '21 at 13:49

1 Answers1

2

The never-ending loop is because adding items to the dependencies will trigger the useEffect whenever items change which happens when setItems is called.

This can be easily solved by using a functional state update:

useEffect(() => {
    const sortItems = (itemsArr) => {
      // maybe these should be a.priority, b.priority   
      return itemsArr.sort((a, b) => (priority > priority ? 1 : -1));
    };

    if (sortedProperty) {
        // updating state by passing a callback
        setItems(previousItems => sortItems(previousItems));
    }
  }, [sortedProperty]);
Ramesh Reddy
  • 9,107
  • 3
  • 12
  • 28
  • What's the difference between setting the items directly and passing in a function? – evolutionxbox May 10 '21 at 14:15
  • @evolutionxbox It is recommended to use functional update when the new state depends on the old state(even when we don't face an infinite loop issue). See this [question](https://stackoverflow.com/questions/57828368/why-react-usestate-with-functional-update-form-is-needed) – Ramesh Reddy May 10 '21 at 14:20