Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When an item is pushed to useState array, it's pushing twice

I have an issue with pushing an item to array inside the useState hook. When I try to push one element, it pushing twice. Code below:

export default function App() {
  const [max, updateMax] = React.useState([]);
  const [mid, updateMid] = React.useState([]);
  const [low, updateLow] = React.useState([]);

  const arr = [
    { letter: "A", number: 100 },
    { letter: "B", number: 80 },
    { letter: "C", number: 60 },
    { letter: "D", number: 40 }
  ];

  useEffect(() => {
    arr.map((element, index, array) => {
      element.number === 100
        ? updateMax((prevState) => [...prevState, element.letter])
        : element.number >= 60
        ? updateMid((prevState) => [...prevState, element.letter])
        : element.number < 60
        ? updateLow((prevState) => [...prevState, element.letter])
        : null;
    });
  }, []);
  console.log(max, mid, low);

  return <div className="App"></div>;
}

In console:

["A", "A"]
["B", "C", "B", "C"]
["D", "D"]

Expected output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

["A"]
["B", "C"]
["D"]

Why it’s behaving like this?

>Solution :

The reason it runs twice is because you’re running your app in Strict Mode.

Since React 18, developers of React decided to make useEffect() run twice when the app uses Strict Mode to help debugging useEffect(). If you get unexpected results from it running twice, it means that your code has some kind of smaller or bigger problem, either lack of proper cleanup code, or a little messy logic.

In your case, useEffect() is not the best fit for what you’re trying to do. Try useMemo() instead.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading