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.
Key takeaways
The useLocation
hook 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 useLocation
in combination with the useEffect
hook, you can conditionally perform actions when the URL changes, such as fetching new data, thus improving the responsiveness of your app.
The useLocation
hook allows you to extract pathname
, search
parameters, and hash
fragments from the URL, enabling you to build dynamic components that adapt to user input and navigation.
useLocation
hookThe 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.
useLocation
Let's look at a simple example where we set up the useLocation
hook and print the location object for different URLs.
useLocation
hookSometimes, 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.
In the App.js
file:
Lines 6–15: We create a component AppRoutes
in which we call useLocation()
to get the current location
object. We then ensure that the Routes
component remounts whenever the location changes, which can trigger re-renders in child components if needed by setting key={location.key}
on the Routes
component.
Lines 17–42: We create a simple navigation menu where each <Link>
component navigates to /products
with a specific category
query parameter. We include the AppRoutes
component within the main App
component to handle route rendering.
In the Products.js
file:
Line 5: We call useLocation()
to get the current location
object that contains properties like pathname
, search
, hash
, state
, and key
.
Line 6–7: We create a URLSearchParams
object and use location.search
to get the query string from the URL (e.g., ?category=bags
) and extract the category
parameter.
Lines 9–13: We define a useEffect
hook and include location.key
in the dependency array, which ensures that the hook runs whenever the location.key
changes, 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 the category
parameter.
Explore advance usage of React Router in this project, Build an Image Sharing App with MERN Stack.
useLocation
hookThe location
object 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.
useLocation
hookEvery change in the location
object triggers a re-render of components consuming it. This can lead to unnecessary performance bottlenecks, especially in applications with frequent URL updates.
Since the useLocation
hook is specific to React Router, it couples your application logic to the library, making migrations to other routing libraries more challenging.
Haven’t found what you were looking for? Contact Us
Free Resources