The useLocation hook allows you to access the location object, that contains current URL’s information. This is useful for triggering effects when the URL changes or for extracting parameters from the URL.
How to use the useLocation hook in React
Key takeaways
The
useLocationhook provides a way to access the current URL in a React application, making it easier to respond to navigation changes and maintain state.By utilizing
useLocationin combination with theuseEffecthook, you can conditionally perform actions when the URL changes, such as fetching new data, thus improving the responsiveness of your app.The
useLocationhook allows you to extractpathname,searchparameters, andhashfragments from the URL, enabling you to build dynamic components that adapt to user input and navigation.
The useLocation hook
The useLocation hook in React Router is a function that returns the location object from the current URL. This location object contains the current URL’s pathname, search parameters, hash fragment, and some other information.
The syntax to use the useLocation hook is as follows:
import { useLocation } from 'react-router-dom'; // import the hookconst location = useLocation();
The useLocation hook returns the location object from the current URL, which includes the following:
pathname: A string representing the path of the URL (e.g.,/products).search: A string containing the query parameters (e.g.,?category=bags).hash: A string of the URL's hash fragment (e.g.,#section1).state: An object that can hold additional state information passed via navigation.key: A unique string representing the location. This is useful for forcing components to remount when the location changes.
The location object updates whenever the URL changes, making it useful for triggering side effects or rendering decisions based on the current URL.
Learn more the React Router, by trying this project, Create a Website with Dynamic Routing Using React Router.
Displaying the location object using useLocation
Let's look at a simple example where we set up the useLocation hook and print the location object for different URLs.
Responding to location changes using useLocation hook
Sometimes, you may want your component to perform an action whenever the URL changes because the useLocation object updates whenever the URL changes. We can extract the query parameters from the URL through the useLocation object and make some decisions based on the query parameter. For example, if we have a URL, /products/school/?bags, then location.search will be equal to ?name=bags. We can then conditionally display the products in the "bags" category depending on the result obtained through the useLocation hook.
Implement React Router hooks in a real world application in this project, Build a Stock Market App Using React and Chart.js.
One way to achieve this is by combining the useLocation hook with the useEffect hook. Let’s look at an example below where when users click different product categories, the useEffect hook logs the category changes to the console. The Products component will display the current category, showing that the useLocation hook is effectively capturing URL changes.
Explanation
In the App.js file:
Lines 6–15: We create a component
AppRoutesin which we calluseLocation()to get the currentlocationobject. We then ensure that theRoutescomponent remounts whenever the location changes, which can trigger re-renders in child components if needed by settingkey={location.key}on theRoutescomponent.Lines 17–42: We create a simple navigation menu where each
<Link>component navigates to/productswith a specificcategoryquery parameter. We include theAppRoutescomponent within the mainAppcomponent to handle route rendering.
In the Products.js file:
Line 5: We call
useLocation()to get the currentlocationobject that contains properties likepathname,search,hash,state, andkey.Line 6–7: We create a
URLSearchParamsobject and uselocation.searchto get the query string from the URL (e.g.,?category=bags) and extract thecategoryparameter.Lines 9–13: We define a
useEffecthook and includelocation.keyin the dependency array, which ensures that the hook runs whenever thelocation.keychanges, which happens when the URL changes. For simplicity, we log the new category to the console whenever the URL changes. However, you can perform any side effect here, e.g., fetching data based on the value of thecategoryparameter.
Explore advance usage of React Router in this project, Build an Image Sharing App with MERN Stack.
Advantages of useLocation hook
The
locationobject updates whenever the URL changes, enabling components to respond to navigation events, such as updating state or triggering side effects.When combined with
useEffect, you can perform actions whenever the URL changes, such as fetching data, updating analytics, or resetting the component state.It allows for dynamic rendering of components based on URL data without the need for prop drilling or complex state management.
By reacting to URL changes, you can provide a smoother and more interactive user experience, updating content without full page reloads.
Disadvantages of useLocation hook
Every change in the
locationobject triggers a re-render of components consuming it. This can lead to unnecessary performance bottlenecks, especially in applications with frequent URL updates.Since the
useLocationhook is specific to React Router, it couples your application logic to the library, making migrations to other routing libraries more challenging.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is the purpose of the useLocation hook in React Router?
Why is the key prop important when using useLocation?
Can I use useLocation to listen for URL changes?
Free Resources
- undefined by undefined