You should call navigate() in a React.useEffect(), not when your component is first rendered

Whenever the url changes to /login An error occurs :You should call navigate() in a React.useEffect(), not when your component is first rendered.
The component rendered on /login page is below:


import useGlobalContext from "../GlobalContext"
import { useNavigate } from 'react-router-dom'
const Login = () => {
	const navigate = useNavigate()
	const {isLoggedIn } = useGlobalContext();
	if (isLoggedIn) {
		navigate("/")
	}
	return (
		<div>
			This is login page
		</div>
	)
}

export default Login

OK. Have you tried putting that in a useEffect hook?

I personally haven’t used V6 of react-router yet (other than with remix briefly) so I don’t know the new hooks but as far as I can tell useNavigate is used for imperatively navigating. So not just an if condition redirect. It would have to be triggered by the user (like an onClick or form submit) or I guess using a useEffect. It seems the Navigate component is maybe what you want. If you look at their auth example you can see such a redirect.

Some docs links:

React Router | API Reference

React Router | Main Concepts

React Router | API Reference