useHistory
A custom hook for managing browser history navigation.
Add hook
Create a file use-history.ts
and copy & paste the code from useHistory.
Hook
import { useState, useEffect } from 'react'
export const useHistory = () => {
const [currentPosition, setCurrentPosition] = useState(history.length)
useEffect(() => {
const handlePopstate = () => {
setCurrentPosition(history.length)
}
window.addEventListener('popstate', handlePopstate)
return () => {
window.removeEventListener('popstate', handlePopstate)
}
}, [])
const back = () => {
if (currentPosition > 1) {
history.back()
setCurrentPosition(currentPosition - 1)
}
}
const forward = () => {
if (currentPosition < history.length) {
history.forward()
setCurrentPosition(currentPosition + 1)
}
}
const go = (step: number) => {
history.go(step)
setCurrentPosition(currentPosition + step)
}
const push = (path: string) => {
history.pushState(null, '', path)
setCurrentPosition(currentPosition + 1)
}
const replace = (path: string) => {
history.replaceState(null, '', path)
}
return { back, forward, go, push, replace, currentPosition, numberOfPages: history.length }
}
Usage
import React from 'react';
import { useHistory } from './hooks/use-history';
function App() {
const { back, forward, go, push, replace, currentPosition, numberOfPages } = useHistory();
return (
<div>
<h1>History Navigation Example</h1>
<p>Current Position: {currentPosition}</p>
<p>Number of Pages in History: {numberOfPages}</p>
<button onClick={back}>Go Back</button>
<button onClick={forward}>Go Forward</button>
<button onClick={() => go(-2)}>Go Back 2 Steps</button>
<button onClick={() => go(2)}>Go Forward 2 Steps</button>
<button onClick={() => push('/new-page')}>Push New Page</button>
<button onClick={() => replace('/replacement-page')}>Replace Current Page</button>
</div>
);
}
export default App;
API
Returns
Name | Description |
---|---|
back(): void | Navigates to the previous page in the session history. |
forward(): void | Navigates to the next page in the session history. |
go(step: number): void | Navigates to a specific page in the session history, relative to the current page. |
push(path: string): void | Pushes a new entry onto the session history stack with the specified URL. |
replace(path: string): void | Replaces the current entry in the session history with the specified URL. |
currentPosition | A number representing the current position in the session history. |
numberOfPages | A number representing the total number of pages in the session history. |