惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - Franky
T
Tailwind CSS Blog
Microsoft Azure Blog
Microsoft Azure Blog
The Cloudflare Blog
博客园 - 叶小钗
N
Netflix TechBlog - Medium
罗磊的独立博客
量子位
MyScale Blog
MyScale Blog
A
About on SuperTechFans
Blog — PlanetScale
Blog — PlanetScale
V
Visual Studio Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI
B
Blog
腾讯CDC
爱范儿
爱范儿
Recent Announcements
Recent Announcements
有赞技术团队
有赞技术团队
F
Fortinet All Blogs
雷峰网
雷峰网
G
Google Developers Blog
Google DeepMind News
Google DeepMind News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Stop Trapping React State: Sync Your Filters to the URL 🔗
Prajapati Pa · 2026-05-04 · via DEV Community

The "Unsharable" Dashboard Problem

Imagine this common B2B SaaS scenario: An executive opens your analytics dashboard. They spend three minutes configuring the data—they filter the status to "Active," set the date range to "Last 30 Days," sort the table by "Highest Revenue," and navigate to Page 4. They copy the URL and Slack it to their team lead.

The team lead clicks the link, but instead of seeing Page 4 of the Active High-Revenue clients, they just see the default, unfiltered dashboard. The context is completely lost. Why? Because the original developer trapped all of those filters inside React's useState hooks. When the page reloaded for the team lead, that local state vanished.

The Solution: The URL is the Single Source of Truth

To architect enterprise-grade frontend experiences at Smart Tech Devs, we follow a strict rule: If a piece of state changes what data is displayed on the screen, it must live in the URL.

By syncing our filters, sorting, and pagination to URL Search Parameters (Query Strings), we achieve deep-linkable, shareable, and refresh-proof dashboards.

Architecting URL State in Next.js (App Router)

Instead of using setFilter(), we manipulate the browser's history API using Next.js hooks. Here is how we build a filter dropdown that safely updates the URL.


// app/components/StatusFilter.tsx
"use client";

import { useRouter, usePathname, useSearchParams } from 'next/navigation';

export default function StatusFilter() {
    const router = useRouter();
    const pathname = usePathname();
    const searchParams = useSearchParams();

    // Read the CURRENT state directly from the URL, defaulting to 'all'
    const currentStatus = searchParams.get('status') || 'all';

    const handleFilterChange = (newStatus: string) => {
        // 1. Create a fresh URLSearchParams object based on current URL
        const params = new URLSearchParams(searchParams.toString());

        // 2. Set the new parameter (or delete it if resetting)
        if (newStatus === 'all') {
            params.delete('status');
        } else {
            params.set('status', newStatus);
        }

        // 3. Reset pagination to page 1 whenever a filter changes!
        params.delete('page');

        // 4. Update the URL without triggering a full page reload
        router.push(`${pathname}?${params.toString()}`);
    };

    return (
        <select 
            value={currentStatus} 
            onChange={(e) => handleFilterChange(e.target.value)}
            className="filter-dropdown"
        >
            <option value="all">All Statuses</option>
            <option value="active">Active Only</option>
            <option value="archived">Archived</option>
        </select>
    );
}

Consuming the URL State in a Server Component

Because the state now lives in the URL, our Next.js Server Components can read it instantly on the initial request. This means we fetch the perfectly filtered data on the server, resulting in zero loading spinners and incredible SEO.


// app/dashboard/page.tsx
import { fetchClients } from '@/lib/db';
import StatusFilter from './components/StatusFilter';

// Next.js automatically passes searchParams to page components
export default async function DashboardPage({ searchParams }: { searchParams: { status?: string } }) {
    
    const currentStatus = searchParams.status || 'all';
    
    // Fetch directly from the DB using the URL state
    const clients = await fetchClients({ status: currentStatus });

    return (
        <main>
            <div className="toolbar">
                <h1>Client Roster</h1>
                <StatusFilter />
            </div>
            
            <ClientTable data={clients} />
        </main>
    );
}

Conclusion

Local state (useState) should be reserved for transient UI elements like opening a modal or typing in a text field. For everything else—filters, tabs, search queries, and pagination—the URL must be your single source of truth. It is the defining line between a hobby project and a professional, collaborative SaaS platform.