React Router: Redirect with Higher-Order Component - Robin Wieruch

React Router: Redirect with Higher-Order Component - Robin Wieruch

When using React Router in React, one can use the Navigate component to navigate a user away from a page in case of a certain condition. For example, the following example does not render a list if there is no data, but redirects a user to the home page instead:

In this case the redirect is well placed. However, if there is much logic happening before of the conditional, e.g. by using React Hooks (because they cannot be after a conditional rendering except with this little trick ), then the logic has to execute even though there may be a redirect.

Therefore, you can use a higher-order component (HOC) for the redirect, because when wrapping the component into a HOC, the logic of the HOC would occur before the hooks from the wrapped component:

The HOC implementation could look like the following then:

Higher-Order Components are still useful these days, even though many React developers take them as legacy, because they are from a time when React Class Components where used. Especially when they are used to render conditional JSX. However, if not using any conditional JSX, using a Hook instead of a HOC is often a better design choice in modern React.

Recommended articles