Navigating Different Routes

The Link component

Once we’ve divided the application into different routes, we would also like to link between these URLs. While we could easily use regular HTML anchors such as <a href="...">...</a>, this is not recommended. Each time such an anchor is used, we trigger a “hard” page refresh in the browser. The page would be left completely and would be loaded again.

In practice, we would ask for an HTML document that would load CSS and the JavaScript containing our React application from the server again (unless it is in the browser cache). Doing this would mean that everything is re-initialized based on each new URL. Any state that previously might have been set globally would be reset.

Single-page applications should not follow this pattern, and any HTML, CSS, and JavaScript should only be loaded from the server once. The global state should be persisted once we navigate through the routes, and only those parts of the page that actually change should re-render.

To facilitate said behavior, React Router supports a Link component. We can import it from the react-router-dom package, which also comes with a to prop. The Link component roughly equates to the regular href attribute on an HTML anchor element. We can use it like this:

Get hands-on with 1400+ tech skills courses.