use-location.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { useCallback, useMemo } from 'react'
  2. import useIsMounted from './use-is-mounted'
  3. import { location } from '@/shared/components/location'
  4. export const useLocation = () => {
  5. const isMounted = useIsMounted()
  6. const assign = useCallback(
  7. (url: string) => {
  8. if (isMounted.current) {
  9. location.assign(url)
  10. }
  11. },
  12. [isMounted]
  13. )
  14. const replace = useCallback(
  15. (url: string) => {
  16. if (isMounted.current) {
  17. location.replace(url)
  18. }
  19. },
  20. [isMounted]
  21. )
  22. const reload = useCallback(() => {
  23. if (isMounted.current) {
  24. location.reload()
  25. }
  26. }, [isMounted])
  27. const setHash = useCallback(
  28. (hash: string) => {
  29. if (isMounted.current) {
  30. location.setHash(hash)
  31. }
  32. },
  33. [isMounted]
  34. )
  35. const toString = useCallback(() => {
  36. if (isMounted.current) {
  37. return location.toString()
  38. }
  39. return ''
  40. }, [isMounted])
  41. return useMemo(
  42. () => ({ assign, replace, reload, setHash, toString }),
  43. [assign, replace, reload, setHash, toString]
  44. )
  45. }