Your main problem is the sort
function here. See, sort
is an in-place operation, and object types in javascript are stored as references. So in your code you:
useState
to create newArticles
(newArticles
is a reference)sorted
as newArticles.sort(...)
, this is the same reference that points at newArticles
since sort
is in-place.setNewArticles
on sorted
which is just the same reference with newArticles
. React sees the same value and does not see a reason to re-render.One option to fix this is to copy the object first send set newArticles
to this newly created object like this:
function sortVotes() {
const sorted = [...newArticles].sort((a, b) => a.upvotes - b.upvotes);
setNewArticles(sorted);
}
Important note: trying to mutate state variables directly is a bad practice and can cause bugs. Please avoid that.