Skip to main content

React router: Using State in the Link

React Router’s Link component is a fundamental part of navigating between components in a React application. One of its powerful features is the ability to pass state from one component to another.

The state is a property that’s part of the object you can provide to the to prop of the Link component. It is particularly useful if you want to send data from the current view to one the Link directs you to, without using common techniques such as setting URL parameters or using libraries, such as Redux.

Passing Data with State

You can pass state via the Link component by making use of a prop named state. Here’s an example:

import { Link } from 'react-router-dom';

const myData = {
name: 'Some thing',
price: 123
}

<Link to="/some-where" state={myData}>Link Text</Link>

In this example, we’re passing an object myData as state to the route /some-where.

Retrieving Data from State

To get the data passed via the Link component, we use the useLocation hook. Here’s how you can do it:

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

const location = useLocation();
const data = location.state;
console.log(data);

In this example, we’re retrieving the state passed to the current location and logging it to the console.