A React Router tutorial which teaches you how to perform a Redirect in React Router 7 . The code for this React Router v7 tutorial can be found over here .
We will start off with a minimal React project that uses React Router to navigate a user from one page to another page:
In this function component we have matching Link and Route components from React Router for the / and about/ routes. Furthermore, we have a so-called Index Route loaded with the Home component and a so-called No Match Route loaded with the NoMatch component. Both act as fallback routes. From here, we will explore how to navigate in React Router .
We can perform a declarative redirect by using React Routerâs Navigate component. In the following example, whenever a user navigates to the about page, the Navigate component will perform a redirect declaratively:
If we would want to manage this on a Route level, we could use this alternative solution as well:
As you can see, you can apply the declarative redirect either on route or on component level. Based on a specific condition, the redirect will happen. Letâs explore next how we can perform a programmatic redirect â¦
In contrast to the Navigate component and its declarative redirect, we can perform a programmatic redirect by using React Routerâs useNavigate Hook:
Whenever the component renders, Reactâs useEffect Hook runs and will perform the redirect programmatically. Initiating the redirect when the component renders without any condition is not useful at all, as you can see, but serves as a minimal example. You can head back to my React Router tutorial where a programmatic redirect is used for a actual real world use case.
The best practice for performing a redirect with React Router would be initiating the redirect on the server-side for SEO and performance reasons. However, there are times when you have to fall back to a client-side redirect and therefore have to use React Routerâs Navigation component or useNavigate Hook for a declarative or programmatic redirect.