DEV Community

Cover image for useLocation Hook in React Router
Alex Anie
Alex Anie

Posted on • Originally published at ocxigin.hashnode.dev

useLocation Hook in React Router

Introduction

Single Page Application takes a different approach when navigating from one page (Component) to another.

This is because unlike Multi-page Applications with multiple HTML files that are uploaded to the server and then accessed later based on a new request from the client side.

Single Page Application has one HTML file that is uploaded to the server and once a request is made, the entire app (html file) is sent to the client. This helps users to navigate directly within the client-side (client-side routing) without sending a new request to the server.

With useLocation hook, we can get access to the pathname, hash, state, key or search relative to a specific component and perform side effects in a web app.

In this blog post, I explained how to implement useLocation hook in React Router and how to return the location object and access the object props relative to the components.

Prerequisites

In other to follow along, you should have a basic understanding of the following:

  1. How to setup a React project

  2. How to install React Router

So with that said, let's dive in.

What is useLocation hook

The useLocation hook in React Router is used to return the current location of a React component. The useLocation returns the current location as an object and comes with props such as

  • pathname

  • state

  • search

  • key

  • hash

These props can be used with useEffect hook to perform side effects such as clicks onScroll or return state parsed to a Link component.

To use useLocation hook, import it from the react-router-dom as indicated below.

 πŸ‘‰ import { useLocation } from 'react-router-dom';
Enter fullscreen mode Exit fullscreen mode

Then create and store the useLocation hook to a location variable as indicated below.

export default function App(){

    πŸ‘‰ const location = useLocation()

    retun(
        <><p>Hello, useLocation</p></>
    )
}
Enter fullscreen mode Exit fullscreen mode

With the location variable, the useLocation props can be accessed. For example

export default function App(){

    const location = useLocation()
    πŸ‘‰    console.log(location)

    retun(
        <><p>Hello, useLocation</p></>
    )
}
Enter fullscreen mode Exit fullscreen mode

This should return the location variable as an object.

Props

The defined location object returns an object that contains the URL segment of the current location. πŸ‘‡

pathname

The pathname property (prop) from the location object is used to return the path name of a given component. The path name is the name that comes after the port number.

                    //pathname 
                         πŸ‘‡
http://localhost:5173/products
                  πŸ‘†
             //port number
Enter fullscreen mode Exit fullscreen mode

From the code sample, the pathname is the forward slash and the products text πŸ‘‰ /products

Access the pathname as follows ;

export default function App(){
            // Dot Notation
            const location = useLocation()
    πŸ‘‰    console.log(location.pathname)

            // Object Destructuring 
      const {pathname} = useLocation()
    πŸ‘‰    console.log(pathname)

    retun(
        <><p>Hello, useLocation</p></>
    )
}
Enter fullscreen mode Exit fullscreen mode
// layouts/Navbar.js

<div className="main">
     {pathname !== "" ? (
         <aside>
           <Link to="#sectionFour" className="product-btn">
             Click Button
                </Link>
           </aside>
     ) : null}
</div>
Enter fullscreen mode Exit fullscreen mode

Here, the pathname returns a button element when the user clicks.

Try the code example on code Codesandbox below

%[https://codesandbox.io/s/uselocation-pathname-xyq46q?file=/src/Layouts/Navbar.js]

state

The state property (prop) from the location object is used to set data on parent components that can be accessed by the children components.

To set state on the parent component, parse the state property and assign it a value as specified below. πŸ‘‡

           <li>
                <NavLink
                  to="/"
              πŸ‘‰  state={`Welcome to the ${
                    pathname.substring(1) !== "" ? "home" : ""
                  } page`}
                >
                  Home
                </NavLink>
              </li>
                                    ...
              <li>
               <NavLink
                  to="products"
                  state={`Welcome to the ${pathname.substring(1)} page`}
                >
                  Products
                </NavLink>
           </li>
Enter fullscreen mode Exit fullscreen mode

Here, the pathname of the specific link the user clicks is returned as a string and we applied the following functions to the state props.

  1. substring(1) This method removes the forward slash from the pathname

  2. the ternary operator checks and returns β€œhome” if the path contains an empty string.

Try the code example on Codesandbox below

%[https://codesandbox.io/s/uselocation-state-h6wrrj?file=/src/Layouts/Navbar.js]

search

The search property (prop) from the location object is used to get the query string in a URL.

For example, take this URL "http://example.com/search?age=20&name=alex";

The query string refers to a portion in the URL starting from the ? character followed by a key (’age’ and β€˜name’ ) and value (’20’ and β€˜alex’) pairs. These keys and value pairs are called parameters and are separated by the & character.

Access the search as follows ;

export default function App(){

            // Dot Notation
            const location = useLocation()
    πŸ‘‰    console.log(location.search)

            // Object Destructuring 
      const {search} = useLocation()
    πŸ‘‰    console.log(search)

    retun(
        <><p>Hello, useLocation</p></>
    )
}
Enter fullscreen mode Exit fullscreen mode

key

The key property (prop) from the location object is used to hold a unique identifier (id) from the current URL.

Access the key as follows ;

export default function App(){

            // Dot Notation
            const location = useLocation()
    πŸ‘‰    console.log(location.key)

            // Object Destructuring 
      const {key} = useLocation()
    πŸ‘‰    console.log(key)

    retun(
        <><p>Hello, useLocation</p></>
    )
}
Enter fullscreen mode Exit fullscreen mode
export default function Navbar() {
  const { pathname, key } = useLocation();

  return (
    <>
         <ul>
              <li>
                <NavLink to="/">Home</NavLink>
              </li>
            ...
              <li>
                <NavLink to="products">Products</NavLink>
              </li>
            </ul>

      {/* Outlet */}
        <Outlet />
        <div className="main">
          {pathname !== "" ? (
            <aside>
              <Link className="product-btn">Click Button</Link>
            </aside>
          ) : null}

          <p>
            the return text is a key: <i className="key">{key}</i>
          </p>
        </div>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, we are returning the key of each component when the navlink is clicked.

Try code example on Codesandbox

%[https://codesandbox.io/s/uselocation-key-3p5vtg?file=/src/Layouts/Navbar.js]

hash

The hash property (prop) from the location object is used to set the current location in the # hash segment of the current URL.

This is useful in cases where you want to navigate between different sections on the same page or navigate to a specific section on another page.

Access the hash as follows ;

export default function App(){

            // Dot Notation
            const location = useLocation()
    πŸ‘‰    console.log(location.hash)

            // Object Destructuring 
      const {hash} = useLocation()
    πŸ‘‰    console.log(hash)

    retun(
        <><p>Hello, useLocation</p></>
    )
}
Enter fullscreen mode Exit fullscreen mode

%[https://codesandbox.io/s/uselocation-hash-zs94kw?file=/src/App.js]

Here, from the example above, we store the list of countries within the page as a hash fragment. So clicking each link navigates to a specific section of the page.

Conclusion

The useLocation hook is used to return the current location of a react component. The useLocation uses the location object to access the key, pathname, state, hash and search of the component.

This is useful for client-side routing and for navigating users within and around different pages in a single-page application.

References

  1. React Router Official Docs

Top comments (0)