React state update is not re-rendering the UI

The state change didn’t re-render the UI in react. Initially, we were setting the state with an array. Afterward, we tried to update the state and were expecting to re-render the UI. It didn’t re-render the UI as expected.

Following is the code:

function App() {
    let laptopBrand = ['Mac', ' Dell'];
    const [data, setData] = useState(laptopBrand);


    useEffect(() => {
        laptopBrand.push(' HP');
        let majorBrands = laptopBrand;
        setData(majorBrands);
    }, []);

    console.log(data);
    return (
    <Fragment>
        <div className="App">
            <header className="App-header">
                <h1>State update didnot re-render UI</h1>
                {data.toString()}
            </header>
        </div>
    </Fragment>
  );
}

The solution

In JavaScript, the arrays are reference values. So when we try to copy it using equal (=) it will only copy the reference to the original array.

To react state, nothing has changed if we try to copy an array and update the state. To solve this we need to create a new array from the original array. Following is the functional code:

function App() {
    let laptopBrand = ['Mac', ' Dell'];
    const [data, setData] = useState(laptopBrand);


    useEffect(() => {
        laptopBrand.push(' HP');
        setData(laptopBrand.slice());
    }, []);

    console.log(data);
    return (
    <Fragment>
        <div className="App">
            <header className="App-header">
                <h1>State update did not re-render UI</h1>
                {data.toString()}
            </header>
        </div>
    </Fragment>
  );
}

Another solution

function App() {
    let laptopBrand = ['Mac', ' Dell'];
    const [data, setData] = useState(laptopBrand);


    useEffect(() => {
        laptopBrand.push(' HP');
        setData([...laptopBrand]);
    }, []);

    console.log(data);
    return (
    <Fragment>
        <div className="App">
            <header className="App-header">
                <h1>State update did not re-render UI</h1>
                {data.toString()}
            </header>
        </div>
    </Fragment>
  );
}