搜索

PythonReactSEOPDF
GitHub Skill

nextjs-state-management

Best practices for managing state (Server URL vs Client Hooks).

HoangNguyen0403☆ 143 仓库 Stars48 仓库 Forks

安装与使用

请根据来源仓库和你的 AI 工具说明安装此技能。先阅读技能文件和依赖要求,再添加到工作流。

查看来源 ↗使用指南

技能说明

State Management

Priority: P2 (MEDIUM)

Prefer Server State (URL) and Local State over Global Stores.

Principles

  1. URL as Source of Truth: For any state that should be shareable or persistent (Search queries, Filters, Pagination, Tabs), use the URL Search Params.
    • Why: Keeps state syncable across refreshes and shareable links.
    • Tool: useSearchParams hook.
  2. Colocation: Keep state as close to the component as possible. Do not lift state unless necessary to share between siblings.
    • Bad: App component holding searchTerm for a SearchBar nested 5 levels deep.
    • Good: SearchBar has internal state, or MainContent holds it if it needs to pass to siblings.
  3. No Global Store Default: Avoid Redux/Zustand for simple apps. Be skeptical of adding a library.
    • Use Cases for Global Store: Complex interactors like a Music Player (persists across navigation), Shopping Cart (shared everywhere).

Patterns

1. Granular State (Best Practice)

Don't store large objects. Subscribe only to what you need to prevent unnecessary re-renders.

// BAD: Re-renders on any change to 'user'
const [user, setUser] = useState({ name: '', stats: {}, friends: [] });

// GOOD: Independent states
const [name, setName] = useState('');
const [stats, setStats] = useState({});
2. URL-Driven State (Search/Filter)
// Client Component
'use client';
import { useSearchParams, useRouter, usePathname } from 'next/navigation';

export function Search() {
  const searchParams = useSearchParams();
  const { replace } = useRouter();
  const pathname = usePathname();

  function handleSearch(term: string) {
    const params = new URLSearchParams(searchParams);
    if (term) params.set('q', term);
    else params.delete('q');

    // Updates URL -> Server Component re-renders with new params
    replace(`${pathname}?${params.toString()}`);
  }
}
3. Server State (TanStack Query / SWR)

If you need "Live" data on the client (e.g., polling stock prices, chat), do not implement useEffect fetch manually. Use a library.

// Automated caching, deduplication, and revalidation
const { data, error } = useSWR('/api/user', fetcher);

使用示例

查看来源仓库中的使用示例与配置说明。

查看来源 ↗

来源历史

收录时间
2026-01-20
索引更新时间
2026-01-26
Branch
main

收录与同步日期属于本站记录。源码修改历史请查看来源仓库。

GitHub ↗

chat Comments (0)

chat_bubble_outline

No comments yet. Be the first to share your thoughts!