);
}
```
### Phase 6: URL State Patterns
For state that should be shareable and bookmarkable.
#### Step 6.1: Using nuqs (Recommended)
```bash
npm install nuqs # Note: Targeting nuqs v1.x
```
```typescript
import { useQueryState, parseAsInteger, parseAsStringEnum } from 'nuqs';
export function ProductList() {
const [page, setPage] = useQueryState(
'page',
parseAsInteger.withDefault(1)
);
const [sort, setSort] = useQueryState(
'sort',
parseAsStringEnum(['name', 'price', 'date']).withDefault('name')
);
// URL: /products?page=2&sort=price
// Automatically synced, type-safe, bookmarkable
}
```
#### Step 6.2: Using Next.js searchParams
```typescript
import { useSearchParams, useRouter } from 'next/navigation';
export function ProductList() {
const searchParams = useSearchParams();
const router = useRouter();
const page = Number(searchParams.get('page')) || 1;
const setPage = (newPage: number) => {
const params = new URLSearchParams(searchParams);
params.set('page', String(newPage));
router.push(`?${params.toString()}`);
};
}
```
### Phase 7: Implementation with Precision Tools
Use `precision_write` to create state management files.
```yaml
precision_write:
files:
- path: "src/lib/query-client.ts"
content: |
import { QueryClient } from '@tanstack/react-query';
export const queryClient = new QueryClient({ ... });
- path: "src/stores/ui-store.ts"
content: |
import { create } from 'zustand';
export const useUIStore = create({ ... });
- path: "src/schemas/user-schema.ts"
content: |
import { z } from 'zod';
export const userSchema = z.object({ ... });
verbosity: count_only
```
### Phase 8: Validation
#### Step 8.1: Run Validation Script
Use the validation script to ensure quality.
```bash
bash scripts/validate-state.sh .
```
See `scripts/validate-state.sh` for the complete validation suite.
#### Step 8.2: Type Check
Verify TypeScript compilation.
```yaml
precision_exec:
commands:
- cmd: "npm run typecheck"
expect:
exit_code: 0
verbosity: minimal
```
## Common Patterns
### Pattern 1: Combine TanStack Query + Zustand
```typescript
// Server data with TanStack Query
const { data: user } = useQuery({ queryKey: ['user'], queryFn: getUser });
// UI state with Zustand
const { sidebarOpen, toggleSidebar } = useUIStore();
```
### Pattern 2: Form with Server Mutation
```typescript
const mutation = useMutation({
mutationFn: createUser,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] });
},
});
const onSubmit = (data: UserFormData) => {
mutation.mutate(data);
};
```
### Pattern 3: URL State Driving Data Fetching
```typescript
const [page] = useQueryState('page', parseAsInteger.withDefault(1));
const [search] = useQueryState('search');
const { data } = useQuery({
queryKey: ['products', page, search],
queryFn: () => getProducts({ page, search }),
});
```
## Common Anti-Patterns
**DON'T:**
- Use global state for server data (use TanStack Query)
- Put everything in Zustand (colocate when possible)
- Manage form state manually (use React Hook Form)
- Store UI state in URL params (use Zustand)
- Use Context for frequently changing data (causes re-renders)
- Forget to invalidate cache after mutations
- Skip validation schemas for forms
- Use `any` types in state stores
**DO:**
- Match state type to the right tool
- Colocate state when possible
- Use selectors to prevent re-renders
- Implement optimistic updates for better UX
- Validate all form inputs with Zod
- Use TypeScript for all state definitions
- Invalidate queries after mutations
- Keep query keys consistent
## Quick Reference
**Discovery Phase:**
```yaml
discover: { queries: [state_libraries, data_fetching, forms], verbosity: files_only }
precision_read: { files: ["package.json", example stores], extract: content }
```
**Implementation Phase:**
```yaml
precision_write: { files: [query-client, stores, schemas], verbosity: count_only }
```
**Validation Phase:**
```yaml
precision_exec: { commands: [{ cmd: "npm run typecheck" }], verbosity: minimal }
```
**Post-Implementation:**
```bash
bash scripts/validate-state.sh .
```
For detailed patterns and decision trees, see `references/state-patterns.md`.