history library reference
5 February 2023 (Updated 5 February 2023)
In a nutshell
The history library provides an API managing session history in JavaScript environments. It abstracts away differences between different environments and provides a minimal API for:
- Managing the history stack
- Navigating history
- Persisting state between sessions
The basic usage is like this:
// Create your own history instance.
import { createBrowserHistory } from "history";
let history = createBrowserHistory();
// Alternatively, if you're using hash history import
// the hash history singleton instance.
// import history from 'history/hash';
// Get the current location.
let location = history.location;
// Listen for changes to the current location.
let unlisten = history.listen(({ location, action }) => {
console.log(action, location.pathname, location.state);
});
// Use push to push a new entry onto the history stack.
history.push("/home", { some: "state" });
// Use replace to replace the current entry in the stack.
history.replace("/logged-in");
// Use back/forward to navigate one entry back or forward.
history.back();
// To stop listening, call the function returned from listen().
unlisten();
The history.location
property
The location
object implements a subset of the window.location
interface and has the following properties:
location.pathname
– The path of the URLlocation.search
– The URL query stringlocation.hash
– The URL hash fragmentlocation.state
– Some extra state for this location that doesn’t reside in the URL (could benull
).location.key
– A unique string that uniquely identifies the current location.
Recipes
Listen for changes to the browser history
history.listen(({ action, location }) => {
console.log(
`The current URL is ${location.pathname}${location.search}${location.hash}`
)
console.log(`The last navigation action was ${action}`)
})
Sources
Tagged:
React Router
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment