OpenReplay
Navigate back to the homepage
BLOG
Browse Repo
Back

React Router Hooks: Exploring How They Work

Michiel Mulders
April 13th, 2021 · 5 min read

The React Router is not the same as the router that directs networking data — luckily! However, there are a lot of similarities between a networking router and the React Router. The React Router helps us to navigate users to the correct component. For instance, we can use client-side routing to build a single-page application (SPA) that allows navigation between different pages without refreshing the browser.

In other words, the React Router keeps your UI in sync with the URL. It has a simple API with powerful features like lazy code loading, dynamic route matching, and location transition handling built right in.

But, there’s much more to discover. This article will dive into React Router hooks. These hooks allow developers to write much cleaner code as they don’t have to write all the boilerplate code like a class component. We can access several hooks, out of the box, such as useHistory , useLocation, useParams, and useRouteMatch. For example, the useHistory hook gives us access to the history object to handle route changes.

This article will cover the following sections:

  • A basic example of the React Router to get you started
  • Examples of each React Router hook to understand its use

1. Getting Started: Setting Up a React Project

To get started, we need to create a new React app by running the following command in your terminal:

1npx create-react-app react-router-tutorial

This command creates a new project called react-router-tutorial.

Now, let’s modify the App.js file.

1import React, { Fragment } from "react";
2import "./index.css"
3export default function App() {
4 return (
5 <main>
6 <nav>
7 <ul>
8 <li><a href="/">Home</a></li>
9 <li><a href="/about">About</a></li>
10 <li><a href="/shop">Shop</a></li>
11 </ul>
12 </nav>
13 </main>
14 );
15}
16// Home Page
17const Home = () => (
18 <Fragment>
19 <h1>Home</h1>
20 <LoremText />
21 </Fragment>
22);
23// About Page
24const About = () => (
25 <Fragment>
26 <h1>About</h1>
27 <LoremText />
28 </Fragment>
29);
30// Shop Page
31const Shop = () => (
32 <Fragment>
33 <h1>Shop</h1>
34 <LoremText />
35 </Fragment>
36);
37const LoremText = () => (
38 <p>
39 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
40 </p>
41)

Our code defines three different pages Home, About, and Shop. Moreover, we’ve added a <nav> element that takes care of the navigation. If you click on the /about link, we want to navigate to the About page. To do so, we need to add the react-router-dom dependency to our project. Execute the following command in your terminal:

1npm install --save react-router-dom

Now, let’s configure our React Router.

2. Setting Up the React Router

First, we need to import the Router object into our App.js file. Once that is done, we can use the Router object to wrap the entire application as we want routing to be available everywhere in our application.

Note that we’ve also refactored the <a> tags to the <Link> tags React Router offers. First of all, they will save you problems with relative versus absolute paths but more importantly the <Link> tag doesn’t trigger a page refresh while the <a> tag naturally does.

On top of that, we import the Route object to define the mapping between path and component. For instance, the path /shop should load the Shop component.

1import React, { Fragment } from "react";
2import "./index.css"
3import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
4export default function App() {
5 return (
6 <Router>
7 <main>
8 <nav>
9 <ul>
10 <li><Link to="/">Home</Link></li>
11 <li><Link to="/about">About</Link></li>
12 <li><Link to="/shop">Shop</Link></li>
13 </ul>
14 </nav>
15
16 <Switch>
17 <Route exact path="/">
18 <Home />
19 </Route>
20 <Route path="/about">
21 <About />
22 </Route>
23 <Route path="/shop">
24 <Shop />
25 </Route>
26 </Switch>
27 </main>
28 </Router>
29 );
30}
31// Home Page
32const Home = () => (
33 <Fragment>
34 <h1>Home</h1>
35 <LoremText />
36 </Fragment>
37);
38// About Page
39const About = () => (
40 <Fragment>
41 <h1>About</h1>
42 <LoremText />
43 </Fragment>
44);
45// Shop Page
46const Shop = () => (
47 <Fragment>
48 <h1>Shop</h1>
49 <LoremText />
50 </Fragment>
51);
52const LoremText = () => (
53 <p>
54 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
55 </p>
56)

Let’s check if the setup works for you by first building the project:

1npm run build`

Next, let’s start the project and open your browser at http://localhost:3000.

1npm run start

You should see the navigation, a title, and the Lorem Ipsum text. Make sure to verify if the navigation works for you.

Home page after executing npm run start

If everything works, let’s explore React Router hooks!

3. Configuring React Router Hooks

Let’s explore how we can use the different React Router hooks.

useHistory The first hook useHistory allows us to access the history object. We can then call methods on the history object like goBack or push. The goBack method allows us to route the user to the previous route in the history stack. For instance, if the user navigates from the Home page to the Shop page and then clicks the button to go back, they’ll be redirected to the Home page again.

On the other hand, we can add new entries to the history stack and make the user navigate to this route by using the push method.

Here’s the final code that implements a “Go Back” button for the About page. Don’t forget to import the useHistory hook from react-router.

1import React, { Fragment } from "react";
2import "./index.css"
3import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
4import { useHistory } from "react-router";
5
6// About Page
7const About = () => {
8 const hist = useHistory();
9 return (
10 <div>
11 <h1>About</h1>
12 <button onClick={() => hist.goBack()}>Go Back</button>
13 <LoremText />
14 </div>
15 );
16};
17export default function App() {
18 return (
19 <Router>
20 <main>
21 <nav>
22 <ul>
23 <li><Link to="/">Home</Link></li>
24 <li><Link to="/about">About</Link></li>
25 <li><Link to="/shop">Shop</Link></li>
26 </ul>
27 </nav>
28 <Switch>
29 <Route exact path="/">
30 <Home />
31 </Route>
32 <Route path="/about">
33 <About />
34 </Route>
35 <Route path="/shop">
36 <Shop />
37 </Route>
38 </Switch>
39 </main>
40 </Router>
41 );
42}
43// Home Page
44const Home = () => (
45 <Fragment>
46 <h1>Home</h1>
47 <LoremText />
48 </Fragment>
49);
50// Shop Page
51const Shop = () => (
52 <Fragment>
53 <h1>Shop</h1>
54 <LoremText />
55 </Fragment>
56);
57const LoremText = () => (
58 <p>
59 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
60 </p>
61)

useParams From the React documentation, we can find the following description for useParams:

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.

It’s a much cleaner way to access URL parameters. To illustrate this, let’s modify the shop page to accept URL parameters and print the received parameter to the screen.

The first thing we did is importing the useParams hook. Next, we have to change the Shop route to accept a URL parameter. By default, we will show the first product ID when clicking the Link tag from the navigation. As you can see, we’ve modified the path for the Shop route to /shop/:id.

1<Router>
2 <main>
3 <nav>
4 <ul>
5 <li><Link to="/">Home</Link></li>
6 <li><Link to="/about">About</Link></li>
7 <li><Link to="/shop/1">Shop</Link></li>
8 </ul>
9 </nav>
10 <Switch>
11 <Route exact path="/">
12 <Home />
13 </Route>
14 <Route path="/about">
15 <About />
16 </Route>
17 <Route path="/shop/:id">
18 <Shop />
19 </Route>
20 </Switch>
21 </main>
22 </Router>

Now, we can access the id parameter via the params object that is returned by the useParams hook.

Also, we’ve added the possibility to navigate to the following product ID using a button with the text Next product. Here, we use the push method exposed by the history object from the previous example to push a new entry to the history stack. If you use the Go Back button, you’ll notice that you are redirected to the previous product IDs. Try it!

1import React, { Fragment } from "react";
2import "./index.css"
3import { BrowserRouter as Router, Route, Link, Switch } from "react-router-dom";
4import { useHistory, useParams } from "react-router";
5
6// About Page
7const About = () => {
8 const hist = useHistory();
9 return (
10 <div>
11 <h1>About</h1>
12 <button onClick={() => hist.goBack()}>Go Back</button>
13 <LoremText />
14 </div>
15 );
16};
17
18const Shop = () => {
19 const params = useParams();
20 const current = params.id;
21 const next = Number(current) + 1;
22 const hist = useHistory();
23 return (
24 <div>
25 <h1>Shop</h1>
26 <p>You requested item with ID: {current}</p>
27 <button onClick={() => hist.goBack()}>Go Back</button>
28 <button onClick={() => hist.push(`/shop/${next}`)}>Next product</button>
29 </div>
30 );
31};
32
33export default function App() {
34 return (
35 <Router>
36 <main>
37 <nav>
38 <ul>
39 <li><Link to="/">Home</Link></li>
40 <li><Link to="/about">About</Link></li>
41 <li><Link to="/shop/1">Shop</Link></li>
42 </ul>
43 </nav>
44 <Switch>
45 <Route exact path="/">
46 <Home />
47 </Route>
48 <Route path="/about">
49 <About />
50 </Route>
51 <Route path="/shop/:id">
52 <Shop />
53 </Route>
54 </Switch>
55 </main>
56 </Router>
57 );
58}
59// Home Page
60const Home = () => (
61 <Fragment>
62 <h1>Home</h1>
63 <LoremText />
64 </Fragment>
65);
66const LoremText = () => (
67 <p>
68 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
69 </p>
70)

That’s it for the useParams React Router hook!

useLocation The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location whenever the URL changes. You can use it, for instance, to trigger a new page view event for a web analytics tool.

Here’s a modified example of the About component that prints the pathname. Every time you visit the About page, the path /about will be printed to the console.

1import { useHistory, useLocation, useParams } from "react-router";
2
3// About Page
4const About = () => {
5 const hist = useHistory();
6 const location = useLocation();
7 // Fictive call to Google Analytics
8 // ga.send(["pageview", location.pathname])
9 console.log(location.pathname);
10 return (
11 <div>
12 <h1>About</h1>
13 <button onClick={() => hist.goBack()}>Go Back</button>
14 <LoremText />
15 </div>
16 );
17};

Furthermore, we can even retrieve the query parameters via the useLocation router hook. The returned location object contains a search field which contains the query string. Now, if you use simple key=value query strings and you do not need to support IE 11, you can use the browser’s built-in URLSearchParams API. This API exposes several methods for verifying if the query string contains a certain key (using has) but we want to retrieve a query parameter using the get function.

Let’s modify the Link for the About page in our router from /about to /about?param=text.

1<Link to="/about?param=text">About</Link>

Now, let’s retrieve the value for the parameter called param using the below code:

1console.log(new URLSearchParams(location.search).get("param")); // result: "text"

The code for the About function looks like this.

1// About Page
2const About = () => {
3 const hist = useHistory();
4 const location = useLocation();
5 // Fictive call to Google Analytics
6 // ga.send(["pageview", location.pathname])
7 console.log(location.pathname);
8 console.log(location.search);
9 console.log(new URLSearchParams(location.search).get("param")); // "text"
10 return (
11 <div>
12 <h1>About</h1>
13 <button onClick={() => hist.goBack()}>Go Back</button>
14 <LoremText />
15 </div>
16 );
17};

useRouteMatch The React Router docs define the useRouteMatch as follows:

The useRouteMatch hook attempts to match the current URL in the same way that a <Route> would. It’s mostly useful for getting access to the match data without actually rendering a <Route>.

In our example, we will use the route match pattern for the Shop page. If the URL doesn’t contain an ID (/shop) then we render all products. Else, if it contains an ID (/shop/:id) we render the specific product. Without the route match hook, we need to use a Switch statement to render both pages. Now, we can check which route matches and render the correct page.

Make sure first to import the useRouteMatch hook. Then we pass the path we want to verify to the useRouteMatch hook: /shop/:id. If the route matches, we render the product page. We can access the product ID via routeMatch.params.id.

1const Shop = () => {
2 const hist = useHistory();
3 const routeMatch = useRouteMatch("/shop/:id");
4
5 // Use match to render the correct page
6 return routeMatch ? (
7 <div>
8 <h1>Shop</h1>
9 <p>You requested item with ID: {routeMatch.params.id}</p>
10 <button onClick={() => hist.goBack()}>Go Back</button>
11 </div>
12 ) : (
13 <div>
14 <h1>Shop</h1>
15 <p>All products</p>
16 <br />
17 <button onClick={() => hist.goBack()}>Go Back</button>
18 </div>
19 );
20};

Now, let’s modify the Router to include an extra link that redirects us to the Shop overview page. Both the /shop and /shop/1 links are connected to the <Shop /> component, without using a Switch statement. A single Route element is sufficient, with a path set to /shop.

1export default function App() {
2 return (
3 <Router>
4 <main>
5 <nav>
6 <ul>
7 <li>
8 <Link to="/">Home</Link>
9 </li>
10 <li>
11 <Link to="/about?param=text">About</Link>
12 </li>
13 <li>
14 <Link to="/shop">Shop</Link>
15 </li>
16 <li>
17 <Link to="/shop/1">Product 1</Link>
18 </li>
19 </ul>
20 </nav>
21
22 <Route path="/shop">
23 <Shop />
24 </Route>
25
26 <Switch>
27 <Route exact path="/">
28 <Home />
29 </Route>
30 <Route path="/about">
31 <About />
32 </Route>
33 </Switch>
34 </main>
35 </Router>
36 );
37}

Observability for Production React Apps

Debugging React apps in production may be challenging and time-consuming. OpenReplay is an open-source session replay stack for developers. It helps you replay everything your users do and shows how your app behaves and renders for every issue. It’s like having your browser’s inspector open while looking over your user’s shoulder.

OpenReplay Frontend Monitoring

OpenReplay helps to quickly get to the root cause by reproducing issues as if they happened in your own browser. It also monitors your frontend performance by capturing key metrics such as page load time, memory consumption and slow network requests as well as Redux actions/state.

Happy debugging, for modern frontend teams - Start monitoring your web app for free.

That’s it!

If you want to learn more about React Router hooks, make sure to check out the code examples in the React Router documentation.

The completed code can be found at CodeSandBox.io.

More articles from OpenReplay Blog

The Ultimate Guide to Fixing JavaScript Performance Problems in Browser DevTools

No one wants a slow site, but not all bytes are created equally

April 13th, 2021 · 11 min read

Top Companies That Have Open Source Products: 10 Companies To Know

Learn about the top companies living off of Open Source product, how are they doing it? Who are they?

April 13th, 2021 · 5 min read
© 2021 OpenReplay Blog
Link to $https://twitter.com/OpenReplayHQLink to $https://github.com/openreplay/openreplayLink to $https://www.linkedin.com/company/18257552