Sometimes, we want to redirect in React Router v6.
In this article, we’ll look at how to redirect in React Router v6.
How to redirect in React Router v6?
To redirect in React Router v6, we can use the navigate function.
For instance, we write
import { useNavigate } from "react-router-dom";
const Comp = () => {
const navigate = useNavigate();
useEffect(() => {
if (loggedIn) {
return navigate("/");
}
}, [loggedIn]);
//...
};
to call the useNavigate function to return the navigate function.
Then we call navigate with the URL we want to navigate to.
Conclusion
To redirect in React Router v6, we can use the navigate function.
One reply on “How to redirect in React Router v6?”
Very good, one of the missing dependency is the navigate in the useEffect, all in all. am Greatful