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
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.
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.
import React from 'react'; function App() { function refreshPage() { window. location. reload(false); } return ( <div> <button onClick={refreshPage}>Click to reload!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With