AuthContext.js

import { createContext, useContext, useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'

export const AuthContext = createContext(null)

export const useAuthContext = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const context = useContext(AuthContext)

  if (context === undefined) {
    throw Error('useAuthContext must only be used within AuthContext')
  }

  useEffect(() => {
    if (!context.authData) {
      const { pathname } = location
      if (!['/login', '/'].includes(pathname)) {
        navigate('/', { replace: true })
      }
    }
  }, [])

  return context
}