0

I'm creating a react application that displays a list of elements on the screen. I created function that lets the user sort the elements by their name.

const [schools, setSchools] = useState([{title: element1}, {title: element2}, ...]);

  const sortSchools = (key, value) => {
      setSchools(schools.sort(compareValues(key, value)));
      console.log(schools);
  }

The function is working properly, changing the schools' state; I can see that from the console, but the elements are not re-rendering.

I think this is because React doesn't re-render components when the value hasn't changed, but can't figure out a way to re-render the elements since the order changed.

Carlos G
  • 367
  • 1
  • 5
  • 15

2 Answers2

3

You need to pass a new instance to setScholls for the component to re-render, try this :

const sortSchools = (key, value) => {
  setSchools([...schools.sort(compareValues(key, value))]);
  console.log(schools);
}
Taki
  • 16,417
  • 3
  • 24
  • 44
0

I found the answer here: UI not re-rendering on state update using React Hooks and form submission

Which is also the same as the answer that Taki provided.

Carlos G
  • 367
  • 1
  • 5
  • 15