The State Object: Storing Navigation Data
What you'll learn: How to use the state parameter in pushState() and replaceState() to attach custom data to each history entry.
What is the State Object?
When you call history.pushState() or history.replaceState(), the first parameter is a state object—a piece of data you can attach to that specific point in the browser's navigation history. Think of it like writing a note and stapling it to a page in a book: when you flip back to that page, the note is still there.
This state object travels with the history entry and becomes available again when the user navigates back or forward to it (via the popstate event).
What Data Should You Store?
Store any information needed to reconstruct the page's state at that moment:
history.pushState(
{ pageNumber: 2, filter: 'active', scrollY: 450 },
'',
'/tasks?page=2&filter=active'
);
Common examples include:
- Current page or tab selection
- Filter or sort settings
- Scroll positions
- Modal or sidebar states
Serialization Limits
The state object must be serializable—it gets converted to JSON-like storage. You can use:
- Strings, numbers, booleans
- Objects and arrays
null
You cannot store:
- Functions
- DOM elements
- Complex objects (like
Dateobjects may lose methods)
Most browsers limit state objects to around 640KB to 2MB. Keep them lightweight!
Key Takeaway: The state object lets you attach serializable data to history entries, capturing just enough information to restore your page's state when users navigate back or forward.