Edit: The next version is 13.3.0
I have a state calledlocalArray
that I want to update only to a specific index, so I thought of creating a time variable to modify the array and update the state with the time value, the problem is, this state is not updated until It doesn't update until another status update or a quick refresh, I don't know why this happens
Here is a minimal reproducible example:
import { useState } from 'react' function Test() { const [someState, setSomeState] = useState(""); const [localArray, setLocalArray] = useState(["","","",""]) const handleArrayChanges = ( { target: { name, value } } ) => { let newArray = localArray; newArray[Number(name)] = value; setLocalArray(newArray); } return () } export default TestArray state
As you can see, after the array state is updated, the first element should be displayed on the paragraph, but it is not displayed until the cis case is explained
React is built on the assumption that state is immutable. You are mutating an existing array, not creating a new one, so after setting the state, React compares the before and after states, finds that they are the same array, and therefore thinks nothing has changed. So it won't re-render.
Instead, create a copy of the array and modify it: