Passing data via a Link component in Next.js

Last updated on May 21, 2022 A Goodman Loading... Post a comment

This concise article is about passing and retrieving data with Link components in Next.js. We’ll discuss the technique (just a few words) then examine a complete example of applying that technique in practice.


You can pass a data object via a Link component like so:

            pathname: "/some-page",
            query: data, // the data
         <a>Some Text</a> 

To retrieve the passed data, we can use the useRouter hook, like this:

const router = useRouter();
const data = router.query;

For more clarity, see the example below.

The Example

App Preview

The sample Next.js app we are going to build has two routes:

  • /: Home
  • /some-page: SomePage

On the home page, there are a Link and a text input. The Link is used to navigate to SomePage. The user can enter a name (or whatever they want) into the text field. The entered text will be passed to SomePage through the Link.

A short demo is worth more than a thousand words:

The Code

1. Create a brand new Next.js project:

npx create-next-app example

2. Remove all of the default code in pages/index.js and add the following:

// index.js
import Link from "next/link";
import { useState } from "react";

export default function Home() {
  // this data will be passed to /some-page via the Link component
  const [data, setData] = useState({ name: "" });

  return (
    <div style={{ padding: 40 }}>

        {/* This text field is used to create dynamic data */}
          placeholder="Enter a name here"
          onChange={(event) =>

        {/* Here is the Link */}
            pathname: "/some-page",
            query: data, // the data
          <a style={{ color: "blue", textDecoration: "underline" }}>
            Go to SomePage

3. In your /pages directory, create a new file named some-page.js and add the code below:

// some-page.js
import { useRouter } from "next/router";

export default function SomePage() {
  const router = useRouter();
  const query = router.query;
  const name =;

  return (
    <div style={{ padding: 40 }}>
        Name: <span style={{ color: "red" }}>{name}</span>

4. Run the app and go to http://localhost:3000 to check the result:

npm run dev


You’ve learned how to pass data through the Link component and get that data with the useRouter hook. If you’d like to learn more about Next.js and modern React development, take a look a the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

Related Articles