When updating an array using react state, the value changes but it does not re-sort the react elements that are mapped from it. In this code snippet, the initial state is [1, 3, 2], then mapped to another array, then sorted and displayed like [1, 4, 9]. When I add 2 to the last element of the array, the list value changes to [1, 16, 9] in the list but the sorting does not change. Can someone please explain why it behaves like this?
const TestObject = () => {
const [state, setState] = React.useState([1, 3, 2]);
const handleAdd = () => {
setState([state[0], state[1], state[2] + 2]);
};
const mappedArray = state.map((x) => x * x);
mappedArray.sort();
return (
<div>
<p>State: {JSON.stringify(state)}</p>
<button onClick={handleAdd}>Add</button>
<h4>Sorted:</h4>
<ul>
{mappedArray.map((x, idx) => (
<li key={idx}>{x}</li>
))}
</ul>
</div>
);
};