Best Practices
1. Choose the Right State Management
| State Type | Use | Example |
|---|---|---|
| Global shared | React Context | Teams, permissions |
| Form data | React Hook Form | All forms |
| Table state | TanStack Table + Context | Data tables |
| Local UI | useState | Modals, toggles |
| Shareable | URL params | Filters, pagination |
2. Context Best Practices
✅ Do:
- Use Context for truly global state
- Provide initial values from Server Components
- Use TypeScript for type safety
- Throw errors if used outside provider
❌ Don't:
- Overuse Context (causes unnecessary re-renders)
- Store frequently changing state in Context
- Use Context for server-only data
3. Form State Best Practices
✅ Do:
- Use React Hook Form for all forms
- Validate with Zod schemas
- Use form context for nested components
- Handle loading and error states
❌ Don't:
- Use controlled inputs without React Hook Form
- Validate in component (use Zod)
- Store form state in Context
4. Table State Best Practices
✅ Do:
- Cache query results
- Sync state with URL
- Use server-side filtering/sorting
- Debounce rapid filter changes
❌ Don't:
- Fetch data on every render
- Store table data in Context
- Use client-side filtering for large datasets
5. Performance Optimization
- ✅ Memoization: Use
useMemoanduseCallbackfor expensive computations - ✅ Debouncing: Debounce search inputs and filters
- ✅ Caching: Cache table query results
- ✅ Lazy loading: Load data only when needed
- ✅ Code splitting: Split large contexts into smaller ones
6. State Updates
- ✅ Immutable updates: Always create new objects/arrays
- ✅ Functional updates: Use functional setState when depending on previous state
- ✅ Batch updates: React batches state updates automatically
- ✅ Error handling: Always handle errors in state updates
Summary
| State Management Solution | Use Case | Location |
|---|---|---|
| React Context | Global/shared state | src/context/ |
| React Hook Form | Form state | src/components/forms/ |
| TanStack Table | Table state | src/components/tables/ |
| useState | Local component state | Throughout components |
| URL Params | Shareable state | Next.js navigation |
Key Takeaways:
- ✅ Context for global state - Teams, permissions, petition data
- ✅ React Hook Form for forms - All form state management
- ✅ TanStack Table for tables - Filtering, sorting, pagination
- ✅ URL params for shareability - Filters, pagination, steps
- ✅ Local state for UI - Modals, toggles, temporary state
The application uses a hybrid approach combining multiple state management strategies, each optimized for its specific use case.