I adapted Rafael Mora's answer to work for the entire location object and also work in the front end of Next.js apps using the useIsMounted
approach, and added typescript types.
hooks/useWindowLocation.ts
import useIsMounted from './useIsMounted'
import { useEffect, useState } from 'react'
const useWindowLocation = (): Location|void => {
const isMounted = useIsMounted()
const [location, setLocation] = useState<Location|void>(isMounted ? window.location : undefined)
useEffect(() => {
if (!isMounted) return
const setWindowLocation = () => {
setLocation(window.location)
}
if (!location) {
setWindowLocation()
}
window.addEventListener('popstate', setWindowLocation)
return () => {
window.removeEventListener('popstate', setWindowLocation)
}
}, [isMounted, location])
return location
}
export default useWindowLocation
hooks/useIsMounted.ts
import { useState, useEffect } from 'react'
const useIsMounted = (): boolean => {
const [isMounted, setIsMounted] = useState(false)
useEffect(() => {
setIsMounted(() => true)
}, [])
return isMounted
}
export default useIsMounted