Component not re-rendering on array state change – Code Example

Total
0
Shares

Array is referenced through it’s memory location. This location doesn’t change when there is some update over array. A react state takes this location. But since the location doesn’t change so react won’t be able to understand if an array got updated. So, there is no re-rendering on array state change in a component.

Solution with Code Example

Create a copy (not another memory reference) of array and do the necessary update over it. Then use this array on state. Since this is a different array so it’s memory location is different and it will trigger re-render. This will re-render even if you won’t do any update over it.

import React, {useState} from 'react'

export default function ArrayWillReRender(props) {
    const [arr, setArr] = useState([])
    const [totalClicks, setTotalClicks] = useState(0)

    const onButtonClick = () => {
        setTotalClicks(totalClicks + 1)

        const tempArr = [...arr]
        tempArr.push('✔️')

        setArr(tempArr)
    }

    return(
        <div>
            <p>Total Clicks - {totalClicks}</p>
            <p>{arr}</p>
            <p>
                <button onclick={onButtonClick}>Add Click</button>
            </p>
        </div>
    )
}

Output –

Showing re-rendering on array update

Live Demo

Open Live Demo