← スキル一覧に戻る

nextjs-state-management
by HoangNguyen0403
nextjs-state-managementは、other分野における実用的なスキルです。複雑な課題への対応力を強化し、業務効率と成果の質を改善します。
⭐ 111🍴 40📅 2026年1月23日
SKILL.md
name: Next.js State Management description: Best practices for managing state (Server URL vs Client Hooks). metadata: labels: [nextjs, state, zustand, context] triggers: files: ['/hooks/*.ts', '/store.ts', '**/components/*.tsx'] keywords: [useState, useContext, zustand, redux]
State Management
Priority: P2 (MEDIUM)
Prefer Server State (URL) and Local State over Global Stores.
Principles
- 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:
useSearchParamshook.
- Colocation: Keep state as close to the component as possible. Do not lift state unless necessary to share between siblings.
- Bad:
Appcomponent holdingsearchTermfor aSearchBarnested 5 levels deep. - Good:
SearchBarhas internal state, orMainContentholds it if it needs to pass to siblings.
- Bad:
- 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);
スコア
総合スコア
85/100
リポジトリの品質指標に基づく評価
✓SKILL.md
SKILL.mdファイルが含まれている
+20
✓LICENSE
ライセンスが設定されている
+10
✓説明文
100文字以上の説明がある
+10
✓人気
GitHub Stars 100以上
+5
✓最近の活動
1ヶ月以内に更新
+10
✓フォーク
10回以上フォークされている
+5
✓Issue管理
オープンIssueが50未満
+5
✓言語
プログラミング言語が設定されている
+5
✓タグ
1つ以上のタグが設定されている
+5
レビュー
💬
レビュー機能は近日公開予定です

