React elements not sorting on state update

Viewed 31

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>
  );
};
2 Answers

Your code is trying to change the state reference, which is forbidden, state should only be changed through the setState function. [...state] will create a new array with a different reference in memory, so state will not change.

  const [state, setState] = useState([1, 3, 2]);
  const handleAdd = () => {
    setState([state[0], state[1], state[2] + 2]);
  };
  const mappedArray = [...state];
  mappedArray.map(x => x * x).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>
  );

UPDATE

As mentioned in answer by Mrudhula Katta, it is better to pass a compare function sort((a, b) => a - b).This will ensure that code is not sorting array alphabetically.

Related