Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirilkirkov/10eac1717347f921cdd37ff4b913bbfd to your computer and use it in GitHub Desktop.
Save kirilkirkov/10eac1717347f921cdd37ff4b913bbfd to your computer and use it in GitHub Desktop.
Handling Asynchronous State Updates in React: The Functional Form of setState

Do you know that if you call setIndexes([...indexes, index]); too fast.. one after another time.. its possible only to update the array, but not to increment it?

The problem you're facing may be due to the asynchronous nature of the setState function in React. When using the useState hook, the setState function doesn't update the state immediately, but during the next render of the component.

Your logic for adding values to the setIndexes array can looks correct but.. However, when you use setIndexes([...indexes, index]), you're actually accessing the previous value of uploadedFiles, which may not be updated yet.

To solve this issue, you can use the functional form of setState, where you take the previous value of the indexes array and add the new value to it. Here's an example:

setIndexes((prevIndexes) => [...prevIndexes, index]);

By using the functional form of setState, you ensure that you're taking the current previous value of the indexes array and adding the new value to it. This guarantees that you'll have a correctly updated array with the added value.

Make sure that the index variable is properly defined and contains a numerical value that you want to add to the array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment