Solution

To update an array in the state in react js, each time you have to initiate a new array with previous array data then the array will update correctly and render component.

To create a new array with previous data we will use an array with a spread operator. like this [...arr]

Spread operator

The Spread operator have lot’s of benfits but we are using Spread operator to assign previous array data in new array without their referance.

Snippet

In this snippet, we will see short example to create array form previous data.

const arr = ["aGuideHub", "SortoutCode"];

const arr1 = [...arr]

arr1.push("ReactJsSnippet");

console.log(arr); // (3) ['aGuideHub', 'SortoutCode', 'ReactJsSnippet']

Example

In this example, we will create an array state with some data and add update array state in useEffect hook, and show the array value in the UI.

Let’s start coding…

App.js

import React, { useEffect, useState } from "react";
export default function App() {
  const [domainsList, setDomainsList] = useState(["aGuideHub", "SortoutCode"]);

  useEffect(() => {
    let arr = [...domainsList];

    arr.push("ReactJsSnippet");

    setDomainsList(arr);
  }, []);

  return (
    <div className="App">
      <h1>{`Print the Array`}</h1>
      <p>{JSON.stringify(domainsList)}</p>
    </div>
  );
}

Output

update, array

codesandbox