Introduction to the routing library

There are multiple ways to implement routing in React applications, such as by creating custom hooks. However, this approach is time-consuming, as it requires the creation of separate hooks for individual features.

Instead, we can use a feature-rich library, such as react-router, which is recommended by the React team. Top companies like Facebook, Netflix, Microsoft, and Discord all use this library.

What is react-router?

The react-router is a routing library for React. Official documentation describes it as a fully-featured client-side and server-side routing library for React, a JavaScript library for building user interfaces.

We can use react-router on the web, NodeJS, and React Native. It has several advantages:

  • The react-router is mainly used to make single-page applications (SPA). It maintains the behavior and structure of the web application.
  • It allows us to use different browser functionalities such as refresh, back button, and locate objects.
  • It’s easy to use and reduces the amount of code we have to write.
  • It allows for navigation without refreshing the page. Because of this, we can maintain different states in our application.
  • It provides many features like navigation, URL params, and passing props to components.

The following lessons will explore these concepts in more detail.

Do we need to use react-router in all React applications?

We don’t need to use react-router if we develop a simple application or website that only needs minimal navigation and routing.

We can also use react hooks to achieve some basic routing functionalities. However, if we want complex navigation and to display multiple views in a single page application, we should use it in our React applications.

Concept behind react-router

This lesson will dig a little deeper to explore how react-router works. You may skip this section if you already have a strong understanding of the concept.

How does react-router work in the browser?

Before we dive into this topic, let’s make sure we understand some terminology.

Location: Each browser has a location object. We can access it via window.location and document.location. It can be used to get the current URL.

Tip: Open the console in a browser tab and type window.location to get the whole location object.

History: This is the same as window.location. We can also try window.history, which returns a history object, which provides an interface to manipulate browser session history, including pages visited in the tab where the current page is loaded.

History stack: As the user navigates through different parts of the web app, the browser keeps track of each location in a stack called the history stack.

The following slides illustrate this concept.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy