React Router useLocation hook – Tutorial and Examples

Last updated on December 26, 2020 The Plumber Loading... Post a comment

It’s 2021 and React Router is the most popular library for routing and navigation in React. At its heart, React Router is a state container for the current location, or URL. It keeps track of the location and renders different routes as it changes, and it also gives you tools to update the location using links and the history API.

With the release of React Router 5.1, there are some useful hooks that you can use in React applications. In this article, we will take a look at the useLocation hook and walk through a few examples of using it.

Note: To use the useLocation hook, you need React 16.8+ and react-router-dom 5.1+.

What is the useLocation hook

The useLocation hook is a function that returns the location object that contains information about the current URL. Whenever the URL changes, a new location object will be returned.

Location object properties:

  • hash: the anchor part (#)
  • pathname: the path name
  • search: the query string part
  • state
  • key

Example code:

import React from 'react';
import { useLocation } from 'react-router-dom';

const Example = props => {
  const location = useLocation();
  console.log(location);

  // ...
};

When use the useLocation hook

The useLocation hook is useful in many cases when you want to trigger a function based on a change of the URL. In general, it is used in conjunction with the useEffect hook provided by React.

For example, your React app is taller than the height of the screen (100 vh) and you want to scroll to the top of the page every time the user switches the route. To archive this purpose, you can do like this:

// App.js
import React, { useEffect } from 'react';
import {
  BrowserRouter as Router,
  Route,
  Switch,
  Link,
  useLocation,
} from 'react-router-dom';

// Create a custom hook that uses both useLocation and useEffect
const useScrollToTop = () => {
  const location = useLocation();
  useEffect(() => {
    window.scrollTo({ top: 0 });
   // scroll to the top of the browser window when changing route
   // the window object is a normal DOM object and is safe to use in React.
  }, [location]);
};

// This is corresponding to "/" route
const Home = (props) => {
  useScrollToTop();
  return (
    <>
      <h1>Home</h1>
      <hr />
      <p style={{ marginTop: '150vh' }}>
        <Link to="/contact">Go to contact page</Link>
      </p>
    </>
  );
};

// This is corresponding to "/contact" route
const Contact = (props) => {
  useScrollToTop();
  return (
    <>
      <h1>Contact</h1>
      <hr />
      <p style={{ marginTop: '150vh' }}>
        <Link to="/">Go to homepage</Link>
      </p>
    </>
  );
};
 
// The root component
const App = () => {
  return (
    <div style={{ padding: 50 }}>
      <Router>
        <Switch>
          <Route path="/" exact>
            <Home />
          </Route>

          <Route path="/contact" exact>
            <Contact />
          </Route>
        </Switch>
      </Router>
    </div>
  );
};

export default App;

Output:

Conclusion

This article explored the React Router useLocation hook and when it is appropriate to use in a React application. If you’d like to learn more about React and React Native, check out our React topic page and React Native topic page for additional example projects and resources.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles