useLocation Hook in React Router
Tags: react, reactrouter, uselocation, hook
Published: 2023-09-27 14:38:58


# 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](https://react.dev/reference/react/useEffect) hook to perform side effects such as clicks onScroll or return state parsed to a [Link](https://ocxigin.hashnode.dev/link-component-in-react-router) component.

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

```jsx
 👉 import { useLocation } from 'react-router-dom';
```

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

```jsx
export default function App(){

	👉 const location = useLocation()

	retun(
		<><p>Hello, useLocation</p></>
	)
}
```

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

```jsx
export default function App(){

    const location = useLocation()
	👉 	console.log(location)

	retun(
		<><p>Hello, useLocation</p></>
	)
}
```

This should return the `location` variable as an object.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1695819842197/315c420b-0481-47e1-a57f-a00161a4376c.png align="center")

# 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.

```jsx
				    //pathname 
                         👇
http://localhost:5173/products
				  👆
			 //port number
```

From the code sample, the `pathname` is the forward slash and the products text 👉 `/products`

Access the `pathname` as follows ;

```jsx
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></>
	)
}
```

```jsx
// layouts/Navbar.js

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

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. 👇

```jsx
           <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>
```

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 ;

```jsx
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></>
	)
}
```

## 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 ;

```jsx
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></>
	)
}
```

```jsx
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>
    </>
  );
}
```

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 ;

```jsx
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></>
	)
}
```

%[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](https://reactrouter.com/en/main/hooks/use-location)