Accessing History State with history.state
What you'll learn: How to read the state data stored with the current history entry at any time.
The Core Idea
You've learned how pushState() and replaceState() let you store a state object alongside a history entry. But how do you retrieve that data later? The history.state property gives you instant access to the state object associated with the current history entry—no events required.
Think of history.state as a window into the "note" you left yourself when you saved that page state. Just like checking your pocket for a note you wrote earlier, you can check history.state whenever you need to know what data you stored with the current URL.
When You'd Use It
You might check history.state when:
- Your page first loads to see if there's saved state from a previous navigation
- After handling a
popstateevent (though the event itself also provides the state) - During any function where you need to know the current navigation context
How It Works
The history.state property is read-only and always returns the state object for the current history entry. If no state was set, it returns null.
// After setting state with pushState
history.pushState({ page: 2, filter: 'active' }, '', '/items?page=2');
// Later, anywhere in your code:
const currentState = history.state;
console.log(currentState); // { page: 2, filter: 'active' }
// On initial page load with no state set:
console.log(history.state); // null
You can check history.state synchronously at any moment—you don't need to wait for an event or make a callback.
Key Takeaway: history.state provides immediate, read-only access to the state object stored with the current history entry, returning null if no state exists.