Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React does not re-render updated array state

I have a simple array in below and I just change index of elements in array by a handler:

const [items, setItems] = useState([
    { id: 5, val: "Iran" },
    { id: 2, val: "Germany" },
    { id: 3, val: "Brazil" },
    { id: 4, val: "Poland" }
]);

My Handler:

const handlePosition = (old_index, new_index) => {
    if (new_index >= items.length) {
      var k = new_index - items.length + 1;
      while (k--) {
        items.push(undefined);
      }
    }
    items.splice(new_index, 0, items.splice(old_index, 1)[0]);

    setItems(items);

    console.log(items);
};

I try to render the items array as follows:

<ul>
  {items.map((item, index) => (
    <li key={item.id}>
      {item.val}
      <button onClick={() => handlePosition(index, index + 1)}>🡇</button>
      <button onClick={() => handlePosition(index, index - 1)}>🡅</button>
    </li>
  ))}
</ul>

Now, My array changed properly and updates the state but not re-render.

Here is a demo of my project in CodeSandBox: Link

like image 437
Amir Avatar asked May 19 '20 16:05

Amir


People also ask

Why is React not updating on state change?

State updates in React are asynchronous; when an update is requested, there is no guarantee that the updates will be made immediately. The updater functions enqueue changes to the component state, but React may delay the changes, updating several components in a single pass.

Does React re-render if state changes?

React components automatically re-render whenever there is a change in their state or props. A simple update of the state, from anywhere in the code, causes all the User Interface (UI) elements to be re-rendered automatically.

How do you refresh state in React?

import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!

How can I stop re rendering in React everytime state gets updated?

1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.


Video Answer


1 Answers

It's because the instance of the items array is not changing.

Try this:

setItems([...items]);

That copies the array to a new identical array. React will see that it's different and will re-render.

like image 158
user2740650 Avatar answered Oct 18 '22 19:10

user2740650