'React Native - UseEffect Constantly Updates

I am using useEffect to get the total jigsaw pieces from my async storage to be displayed on the home page. I use async storage to get the number of jigsaws stored in the storage then for each jigsaw, i add the total amount of jigsaw pieces. I do this within useEffect as the total amount of jigsaw pieces may change depending on if the user adds more jigsaw to their collection. However, when i use useEffect, my total amount of jigsaw pieces constantly updates and never stops.

Code:

let [totalPieces, setTotalPieces] = useState(0);
  const [numJigsaw, setNumJigsaw] = useState([]);
  const getNumOfJigsaw = async () => {
    try {
      setNumJigsaw(await AsyncStorage.getAllKeys());
    } catch (e) {}
    return numJigsaw;
  };
  const getAllJigsaw = async () => {
    let jigsaws = await getNumOfJigsaw();
    for (let z = 0; z < jigsaws.length; z++) {
      let currentJigsaw = JSON.parse(await AsyncStorage.getItem(jigsaws[z]));
      setTotalPieces(totalPieces+ parseFloat(currentJigsaw.pieces));
    }
  };
  useEffect(() => {
    getAllJigsaw();
  }, [totalPieces]);

I believe the issue is because totalPieces is dependant? Im not entirely sure though.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source