nextjs-state-management
Installation
SKILL.md
State Management
Priority: P2 (MEDIUM)
Implementation Guidelines
- URL State: Use the URL as the Single Source of Truth for shareable/persistent state. URL params: shareable across reloads and links. Access via
useSearchParams()and update withuseRouter(). Pattern:const params = new URLSearchParams(searchParams); params.set('q', term); useRouter().replace(...). - Server State: Use SWR or TanStack Query (React Query) for caching and fetching server data. Avoid syncing server data manually into
useState. - Client State: Use Zustand (
create<CartState>()((set) => ({ ... }))) — use only in 'use client' components — or Jotai for complex, high-frequency UI state. Avoid Prop Drilling by leveraging Context API only for low-frequency data. - Lifting State: Colocate state as close as possible to the component. Only lift to the parent when state is shared between siblings.
- Next.js 15+ Integration: Ensure state updates in Client Components don't conflict with server-side rendering logic. Manage optimistic updates with the
useOptimistichook. - State Hydration: Be careful when initializing state from
localStoragein Client Components to avoid Hydration Errors. Wrap inuseEffector use amountedflag.
2. URL-Driven State (Search/Filter)
Use useSearchParams + useRouter to update URL params. See URL State Pattern.