Search code examples
javascriptarraysreactjsreact-hooksuse-effect

How to push a new value into the current array using the react hooks?


This is the source code.

import React, { useState } from "react"
import ReactDOM from "react-dom"
import "./styles.css"

function App() {
  const [arr, setArr] = useState([1,2,3]) 
  return (
    <div className="App">     
      <h1>        
        Length:{arr.length}      
      </h1>   
      <h2>
        Values:
        {arr.map(i=>i+',')}
      </h2>

      <button
        onClick={() => {
          arr.push(0)    //my wrong code
          setArr(arr)    //my wrong code
          // setArr(prevValues => [...prevValues, 0])//Alex K's answer
          // setArr(prevArr => [...prevArr, prevArr.length + 1]); //rotemls98's answer
          // setArr([...arr,1])//venkateshwar's answer
          console.log(arr);
        }}
      >
        push
      </button>
    </div>
  );
}

const rootElement = document.getElementById("root")
ReactDOM.render(<App />, rootElement)

What I want to do is to push a new value into the current array and update length and values when I click the push button.
It printed to the console normally, but not change the display.
How to resolve this? enter image description here


Solution

  • react will not rerender if setState return the same state that was before. when you use the push method you mutate the state object. instead create a new array with the new item.

    always update your state in immutable way.

    in your case:

    onClick={() => {
       setArr((prevArr) => ([...prevArr, prevArr.length + 1]));
    }}