Skip to content
Advertisement

React state does not update accordingly when popping an array

I wrote a simple component in React which is supposed to remove the last element of an array when a button is clicked, but despite console logging the correct value, my React state is not being updated accordingly (when viewing the components with React Developer Tools) and hence the output is not changing. I’m at a loss as to why it won’t update correctly.

const Test = () => {
const [input, setInput] = useState(["c", "a", "t"])

const removeLastElementFromArray = () => {
    setInput(prev => {
        console.log("Previous array was:", prev)
        let t = prev.pop();
        console.log("Array popped, array is now:", prev)
        return prev;
    })
}
return (
    <>
        <button onClick={removeLastElementFromArray}>Click</button>
        {input.map((char, index) => <span key={index}>{char}</span>)}
    </>
)

}

Advertisement

Answer

See the state is not getting updated because arrays are mutable data types and when you pop an element, it is not going to change the address of the array in the memory. Since the array(address) has not changed, react will figure the state hasn’t changed and that’s why a re-render won’t be triggered

Try this code

const App = () => {
  const [input, setInput] = useState(["c", "a", "t"])
  
  const removeLastElementFromArray = () => {
      setInput(prev => {
          console.log("Previous array was:", prev)
          prev.pop();
          let t= [...prev]
          console.log("Array popped, array is now:", prev)
          return t;
      })
  }
  return (
      <>
          <button onClick={removeLastElementFromArray}>Click</button>
          {input.map((char, index) => <span key={index}>{char}</span>)}
      </>
  )
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement