Skip to content

Instantly share code, notes, and snippets.

@ms10596
Last active May 9, 2023 12:55
Show Gist options
  • Save ms10596/8cc23ed9f220adea41fd4bcfd7840cf7 to your computer and use it in GitHub Desktop.
Save ms10596/8cc23ed9f220adea41fd4bcfd7840cf7 to your computer and use it in GitHub Desktop.
useBackForward is a react hook for navigating back and forward. The hook returns two functions for navigation and two boolean variables that detect if there's an available back and forward in order to have a better user experience.
import { useEffect, useState } from 'react';
import { useLocation, useNavigate, useNavigationType } from 'react-router';
export default () => {
const navigationType = useNavigationType();
const location = useLocation();
const navigate = useNavigate();
const [currentIndex, setCurrentIndex] = useState(0);
const [routesLength, setRoutesLength] = useState(0);
const goBack = () => {
setCurrentIndex(currentIndex - 1);
navigate(-1);
};
const goForward = () => {
setCurrentIndex(currentIndex + 1);
navigate(1);
};
useEffect(() => {
if (navigationType === 'PUSH') {
let newLength = routesLength + 1;
setRoutesLength(newLength);
setCurrentIndex(newLength);
}
}, [location, navigationType]);
return {
canBack: currentIndex > 0,
canForward: currentIndex < routesLength,
goForward,
goBack,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment