next의 router
에는 back()
이라는 함수가 있어서 이전 페이지로 이동시킬 수 있다.
문제는 유저가 만약 해당 페이지를 처음으로 접근하게 되면 이전 페이지가 없어서 돌아갈 수가 없다는 것..
next에서 간단한 custom hook으로 previous url을 접근할 수 있어서 간략하게 적어본다.
아이디어는 간단하다.
context로 이전에 접근한 url들을 history로 저장해두겠다는 것. 만약 이 history가 비어있거나, 요소가 한 개라면 해당 페이지로 유저가 처음 접근하게 되었다는 것이므로, /
으로 돌려주면 된다.
const context = createContext(null);
const ContextProvider = ({children}) => {
const router = useRouter();
const {asPath} = router;
const [history, setHistory] = useState();
useEffect(() => {
setHistory(prev => [...prev, asPath])
} ,[asPath])
return (
<context.provider vale={history}>
{children}
</context.provider>
)
}
url의 변화 (asPath)의 변화에 따라 history state가 변한다
이렇게해서 _app
에서 page를 감싸주기만 하면 된다.