Skip to main content

Using useLocation to send data between pages

Published 4 min readMarkdown

Introduction

UseLocation is a react-router-dom hook that can identify exactly where the user is in the app, based on the URL. It's a tool that can make your app "self-aware."

Main use cases:

1 - Toggle visibility of certain components according to the parameters passed in the URL:

Using useLocation, we can make multiple decisions in the code. This is often used when dealing with forms divided into steps, for example, so that when the user clicks a button to advance, one component disappears while another appears, even if they are on the same main page. At the same time, the URL also changes, for example: from baseurl.com/signup/step1 to baseurl.com/signup/step2.

2 - Dynamically style components:

useLocation can be used to indicate when a specific component should have a different style than the others. A classic example of using the hook for this purpose is in a navigation menu: with useLocation, we can know which page the user is on and, with that information, we can apply a different style to the active page link in the navigation bar.

3 - Send data between pages without appearing in the URL:

This functionality is what we'll explore in more detail in this article. useLocation allows you to pass information from one page to another through the "state" property. It's a great way to pass information without cluttering the destination URL with parameters and without exposing potentially sensitive data.

Sintaxe

To use useLocation correctly, we need to add the following codes to the target page:

import { useLocation } from "react-router-dom";

export function myComponent(){
    const location = useLocation()
    console.log(location.pathname) // retorna a URL em que o componente é renderizado.
}

UseLocation returns an object containing the following properties:

  • pathname: The URL path (e.g., /users/123).

  • search: Search parameters: Everything after ? (e.g., ?name=John&age=30).

  • hash: The hash fragments identified in the URL by # (e.g., #section-overview).

  • state: An object containing the state data passed when navigating to the current page (e.g., using navigate('/some-path', { state: { data: 'some data' } })).

  • key: A unique string that identifies the user's location on the page. React uses this internally to manage caching and history.

Difference between useLocation and useParams

  • useLocation → Returns a complete object containing all information related to a given URL, including information such as state and key, which are not visible in the URL.

  • useParams → Returns an object containing only the dynamic segments of a URL, that is, those segments defined in the route followed by ":".

Using use Location to pass information from one page to another

To do this, the most common way is to use useLocation in conjunction with useNavigate.

It basically works like this:

On the source page, we have information we want to transfer via state to the target page, so we use useNavigate to navigate the user to the target page when they click a button. When calling useNavigate, we pass the target page's URL as a parameter, as well as an object called state, containing the information we want to transfer.

Then, in the target page's code, we call useLocation and extract the contents of its state property, thus accessing the information that was passed. See the following example for a better understanding.

Practical example of using state in useLocation

In this example, we have a list containing information about different plants and also a page to display the details of each plant. This data is extracted from a file called plants.ts, in the data folder, but can also come from an API, for example.

First, we define two routes for this application:

/ → shows the list of plants

/plant-details → shows the detailed information for a specific plant

The PlantsList component (in the / route) displays a list containing the names of these plants and, next to each item, a button to view the crop details.

Clicking the button calls the useNavigate hook, directing the user to the /plant-details route and passing, through the state, the information for the specific selected plant from plants.ts.

In the plant-details route, the PlantDetails component is rendered, displaying a table containing all the information for the selected plant.

No comments yet. Be the first to comment.