How to change a state when a Route is changing using NextJS App Directory with usePathname

Jonas K
2 min readMar 17, 2023

--

NextJS App directory (which is in Beta when this article was written) is a topic that you as React developer, couldn’t have missed hearing out.

Now the components are by default server-side components, there are some changes and some new hooks to learn.

In this article, we will make a client-side component, and even here, there is new stuff to add because it is server-side components by default.

In this example, we will work with our navigation.

This is a very classic example. On a laptop, we have our classic top navigation bar, but in mobile size, we are using a burger icon.

When this burger icon is clicked, it will open a dialog with all the links included. When a link is clicked, the route will change — but the dialog is still open 🤯

This is a very short example where the dialog is still visible after the route has changed.

"use client";

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

function Burger(): JSX.Element {
const [isOpen, setOpen] = useState(false);

return (
<>
<button onClick={() => setOpen(!isOpen)}>Menu</button>
{isOpen && (
<div className="dialog">
<Link href="/subpage">Subpage</Link>
</div>
)}
</>
)
}

When you click on the link “Subpage” the route will change correctly, but the state will still be open. How do we fix that?

By using the new hook usePathname

"use client";

import { useState, useEffect } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"

function Burger(): JSX.Element {
const [isOpen, setOpen] = useState(false);
const pathname = usePathname();
useEffect(() => (isOpen ? setOpen(false) : void null), [pathname])

...
}

To use a hook, the component has to be on the client side — this is done by placing “use client” at the top.

Before NextJS App Directory, you would have been using useRouter()

And then get the router pathname from here. This is not an option anymore and has been optimized with its very own hook.

Read more about usePathname in NextJS docs here

--

--

Jonas K
Jonas K

Written by Jonas K

Building stuff on the world wide web. Hi👋

Responses (1)