Tip: Store sharable state in the URL


Tip: Store sharable state in the URL.

Examples:
Filter
Sort
Search
Page number
Toggles
Record IDs

Why put these things in the URL?
✅I can share the URL.
✅I can bookmark the URL.
✅The code doesn't need to store these values. The URL stores it.
✅Less code = less bugs.

One of the most common bugs I see in React apps is out-of-sync state and race conditions between the URL and useState.

If state is being handled in 2 spots, that's a problem.

The solution? Eliminate useState.

Make the URL the single source of truth.
⚠️ Warning signs:

If I hit refresh, do I lose my results and see something different?

If I bookmark the page, do I see something different later?

Is the app storing sharable values in state, localStorage, session, etc?

If so, the solution is simple: Move state to the URL.

View original on X