App state in URL
When building web applications, managing state is crucial. We often use useState() for local state management, but what if we want to share a specific state through the URL, like in an e-commerce setting? Imagine you want to share a link to a product with a specific color selected. Storing state in the URL can be an effective solution for this.
Traditional useState() Approach
First, let's look at how we might handle this with useState():
"use client";
import { useState } from "react";
export default function Component() {
const [color, setColor] = useState<string>("");
return (
<section>
<div className="flex flex-col">
<span>Color:</span>
<button className="border px-4 py-3" onclick={() => setColor("white")}>
White
</button>
<button className="border px-4 py-3" onclick={() => setColor("black")}>
Black
</button>
</div>
{color && <span>Selected Color: {color}</span>}
</section>
);
}
This code manages the color selection locally within the component. However, it doesn't allow for sharing the state via URL.
Shifting to useSearchParams
Now, let's enhance our approach by using useSearchParams from Next.js to sync the color state with the URL. This enables sharing the state through the page's URL.
"use client";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
export default function Component() {
const [searchParams] = useSearchParams();
const color = searchParams.get("color");
return (
<section>
<div className="flex flex-col">
<span>Color:</span>
<Link href="/?color=white" className="border px-4 py-3">
White
</Link>
<Link href="/?color=black" className="border px-4 py-3">
Black
</Link>
</div>
{color && <span>Selected Color: {color}</span>}
</section>
);
}
In this version, the color is synchronized with the URL. The links (using the Link component) update the URL's color parameter, effectively sharing the selected state.
Conclusion: State Synced with URL
By utilizing useSearchParams, we've successfully linked the component's state with the URL. This approach is particularly useful for e-commerce sites, where you might want to share links to products with specific attributes or settings.