Telerik blogs

React Router is a routing library for React apps. It uses React hooks, such as useNavigate(), useParams() and useLocation(), to allow developers to access routing information and perform navigation within their components. In this article, we’ll explain how these hooks can be used.

React Router is a routing library specifically designed for use in React applications. It is a popular choice among the React community due to its flexibility and robust feature set.

With React Router, developers can easily build complex, multi-faceted applications with multiple components that span multiple views and URLs. In addition, React Router provides a range of features that make it easy to handle things like route matching, navigation and the management of application state.

The latest versions of React Router leverage React Hooks heavily to help access router state information and help perform navigation. In this article, we’ll see how using hooks plays an important role with React Router by discussing how the three more commonly used React hooks can be used:

  • useNavigate()
  • useParams()
  • useLocation()

Before we begin, we’ll first spend a few seconds discussing what routing is within the context of web applications.

What is Routing?

Routing refers to the process of directing users to the appropriate content or pages within a web application. In a web application, routing is typically accomplished through the use of URLs and HTTP requests.

When a user navigates to a specific URL within the application, the routing system determines which content or page should be displayed based on the URL. This helps to create a seamless user experience by allowing users to easily access and navigate through the various pages and features of the application. Routing is an essential component of modern web applications and is often implemented using specialized libraries or frameworks such as React Router.

Let’s see some examples of how React Router provides some useful utilities/functions (i.e., hooks) to handle routing in our React components.

useNavigate() Hook

The useNavigate() hook can help trigger a navigation event from within a component. In other words, the useNavigate() hook allows you to programmatically navigate to a different URL within a functional component.

The useNavigate() hook can be used to retrieve the navigate() function that can be called to trigger a navigation event. Here’s an example of the useNavigate() hook being used to redirect a user to another path after a button is clicked within a component.

const Home = () => {
  // get the navigate function from useNavigate()
  const navigate = useNavigate();

  const navigateToNewPage = () => {
    // use the navigate function to navigate to /new-page
    navigate("/new-page");
  };

  return (
    <button onClick={() => navigateToNewPage()}>
      Navigate to /new-page route
    </button>
  );
};

In the above example, when clicking the button, the user is programmatically navigated to the /new-page route.

Clicking the /new-page route button opens a screen showing You've been taken to the new page!

Note: As of the latest version of React Router, the React Router docs encourages the use of another utility function, labeled redirect(), to also help in programmatic navigation.

useParams() Hook

The useParams() hook can be used to access the URL parameters of a Route.

In web applications, URL parameters are often the part of the URL that references the specific information/resource that is to be fetched when the page is to be rendered. As an example, in the Progress Telerik web app, the route of telerik.com/blogs/author/:userId helps direct us to the profile page of a certain user where the dynamic URL parameter is the userId of the route. If we were to navigate to telerik.com/blogs/author/hassan-djirdeh, we’ll see my profile page be shown.

Hassan Djirdeh's author profile page on the Progress Telerik website

How is the above happening? This is because the page fetches information based on the value of the dynamic userId parameter!

The useParams() hook makes it easy to access the parameters of a URL. Assume we had a parent component that uses React Router’s <Route /> component to render a component labeled <Home />. This <Home /> component is rendered under the pathname of /:id where id is a dynamic URL parameter.

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/:id">
          <Home />
        </Route>
      </Switch>
    </Router>
  );
};

In the <Home /> component, we can use the useParams() hook to destruct the value of the id parameter that is to be provided.

const Home = () => {
  // destruct the URL parameter from useParams()
  const { id } = useParams();

  // use the parameter
  return <div>The value of the id URL parameter is {id}</div>;
};

If we were to have the params of our URL be /hassan-djirdeh, the <Home /> component will be rendered and the id param value will be equal to hassan-djirdeh.

Page says 'The id URL parameter is hassan-djirdeh'

With the id parameter available to us in the <Home /> component, we could make a network request to an API, provide the value of the id parameter it expects, and fetch the data we would want to then render in the component.

useLocation Hook

The location object, within the context of React Router, provides information about the current URL at any moment in time. Here’s a component that uses the useLocation() hook to retrieve and access information within the location object.

const Home = () => {
  // get the location object from useLocation()
  const location = useLocation();

  // access values within the location object
  return (
    <div>
      <p>Current Pathname: {location.pathname}</p>
      <p>Current Search: {location.search}</p>
      <p>Current Hash: {location.hash}</p>
    </div>
  );
};

In the above, we’re able to access the pathname, search and hash values of the URL’s location in the component markup. If we use the below URL as an example:

https://www.example.com/?key1=value1&key2=value2#section1

The location object will be populated as follows:

location = {
  pathname: "/",
  search: "?key1=value1&key2=value2",
  hash: "#section1",
};

And since our component renders these values, our component markup will look like the following:

Page lists: Current Pathname: /, Current Search: ?key1=value1&key2=value2, Current Hash: #section1

  • pathname refers to the URL path being visited. / indicates the path in the index path.
  • search refers to the search query parameters used in the URL. Above, the search query parameters are ?key1=value1&key2=value2.
  • hash refers to any hash values appended to the URL. In the above example, #section1 is the hash value.

Accessing these values in our component, with the help of the useLocation() hook, can be useful when we perhaps want to use certain values in our URL to fetch data, display the current URL in our component, or even perform certain side effects whenever the current URL location changes (e.g., fire tracking events).

Wrap-up

React Router’s useNavigate(), useParams() and useLocation() hooks provide useful capabilities for accessing routing-related functionality in our React components, including navigating to different routes, accessing route parameters, and accessing the location object.

Though these are some of the main hooks one may use in their React app, React Router provides many other hooks that provide other functionalities as well. We’ll talk about some of them in an upcoming article!


About the Author

Hassan Djirdeh

Hassan is a senior frontend engineer and has helped build large production applications at-scale at organizations like Doordash, Instacart and Shopify. Hassan is also a published author and course instructor where he’s helped thousands of students learn in-depth frontend engineering skills like React, Vue, TypeScript, and GraphQL.

Related Posts

Comments

Comments are disabled in preview mode.