-2

I'm trying to get Event value and then add that value to an new Array, but useState value fires multiple time, any solution?

const [receivedItems, setReceivedItems] = useState([]);
const [newItems, setNewItems] = useState([]);

//Get selected value
const handleSelected = (e) => {
  setReceivedItems(e);
};

useEffect(() => {
  setNewItems((prevState) => [...prevState, receivedItems]);
}, [receivedItems]);

Result in:

// first render // newItem
// second render // 2 newItem
John Franke
  • 1,444
  • 19
  • 23
BlackRain
  • 49
  • 7

1 Answers1

1

The useEffect hook always runs once more in the begining for the initial render. In your case it runs: one - for the initial render, two - for the actual state update.

But: if you see that the useEffect is always called twice and not just for the first render - then it's probably because you have React.StrictMode in your index.js. See this link.

And also change this line:

  setNewItems((prevState) => [...prevState, receivedItems]);

To this:

setNewItems((prevState) => [...prevState, ...receivedItems]);

You need to extract the elements from the receivedItems array in order to add them correctly.

Tehila
  • 917
  • 4
  • 19
  • Thanks, but it's still same – BlackRain Oct 11 '22 at 22:09
  • What do you mean still same? That's how it's supposed to be. For the first time the component loads the `useEffect` will run twice. If you have an issue that it **always** fires twice - then that because of the `` in your index.js, so if you remove it, it won't be called twice for each render **except** the first one. I edited the answer to inculde this note there. – Tehila Oct 11 '22 at 22:15
  • I'm using React Native – BlackRain Oct 11 '22 at 22:26