DEV Community

Cover image for The .sort() in React improved my understanding of State, Mutation, and Data Flow
Chibuikem Victor Ugwu
Chibuikem Victor Ugwu

Posted on

The .sort() in React improved my understanding of State, Mutation, and Data Flow

I’ve just finished implementing the sort feature for my e-commerce website.

Initially, my sorting logic was scattered everywhere - Inside availability filters and within sort conditions themselves. While it worked, it was messy and hard to maintain. I realized that filtering decides what shows, while sorting decides the order. Sorting should happen once, only after all filters are applied. This separation made the logic easier to reason about and scale.

filteredProducts = filteredProducts.sort(...)

Sometimes it worked. Other times it didn’t.
That inconsistency was the red flag.

sort() mutates the array it’s called on.
In React, mutating an existing array - especially derived state like filteredProducts - can cause unpredictable UI behavior because React cannot detect the change. That’s why sorting would often fail.

It worked after I switched to the spread operator:
[...filteredProducts].sort(...)

[...filteredProducts] creates a new array reference, so .sort() only mutates the copy. React detects the new reference and re-renders correctly.

It is important to remmember:

[...array] is used when reordering data.

{ ...item } is used when updating object properties.

String Sorting
For alphabetical sorting, use localeCompare() - it handles uppercase vs. lowercase properly and produces a predictable order.

A to Z:
a.name.localeCompare(b.name)

Z to A:
b.name.localeCompare(a.name)

Price Sorting
Low to high:

a.price - b.price

b.price - a.price

Sorting by Date in Real E-commerce Apps
My initial data didn’t include dates, so I added them properly.
Dates are typically stored in ISO format:

"2024-11-02T14:30:00Z"

This format is backend-friendly, database-friendly, and JavaScript-friendly.

Most real apps use createdAt (when the product was added) or sometimes updatedAt.

Old to new:
new Date(a.createdAt) - new Date(b.createdAt)

New to old:
new Date(b.createdAt) - new Date(a.createdAt)

By separating filtering and sorting, avoiding direct mutation, and using consistent comparison methods, my sorting feature now works reliably — and my React state updates predictably.

github repo: https://github.com/victorugs-dev/shopco

live demo: https://shopco-store-sigma.vercel.app

Top comments (0)