State Management
This document explains the state management approach used in the Rhesis frontend application.
State Management Architecture
The Rhesis frontend uses a hybrid state management approach:
- Server Components: Data fetching and state management on the server
- React Context: For global UI state and shared state across components
- Local Component State: For component-specific state
- Server Actions: For mutations and form submissions
- URL State: For preserving state in the URL (e.g., filters, pagination)
This approach minimizes client-side state management while leveraging Next.js App Router features.
Server Components
Server components handle data fetching and initial state:
React Context
For global state, the application uses React Context:
Context Definition
Context Usage
Context Setup
Local Component State
For component-specific state, use React’s built-in hooks:
Server Actions
For mutations and form submissions, use server actions:
Using server actions in a form:
URL State
For preserving state in the URL:
State Management Best Practices
- Minimize Client-Side State: Use server components for data fetching where possible
- Colocate State: Keep state as close as possible to where it’s used
- Use URL for Shareable State: Store filters, pagination, and other shareable state in the URL
- Prefer Server Actions: Use server actions for mutations instead of client-side API calls
- Context for Global State: Use React Context for truly global state like theme, user preferences
- Avoid Prop Drilling: Use context or composition to avoid excessive prop drilling
- Revalidate After Mutations: Use
revalidatePathto refresh data after mutations
Example: Complex State Management
For complex state management needs, combine these approaches: