State Management Strategy
Relevant source files
The following files were used as context for generating this wiki page:
The state management strategy in the ELMEC Mobile App v2 is built on a hybrid architecture that combines local component state, global client-side state, and server-side state synchronization. The project utilizes React Context API for domain-specific state (Authentication and Real-time Messaging), Zustand for lightweight global state management, and TanStack Query for managing server-side state and caching. This multi-layered approach ensures high performance, real-time updates, and data consistency across the platform.
Sources: README.md, VALIDACION-COMPLETA.md
Architecture Overview
The application organizes state based on the scope and persistence requirements of the data. High-level architecture involves three primary layers:
- Context-Based Domain State: Used for Auth and Chat modules where real-time subscriptions and provider-consumer patterns are essential.
- Global Store (Zustand): Handles application-wide UI states and simple shared logic, such as calculator sessions.
- Server State (TanStack Query): Manages data fetching, caching, and synchronization with the Supabase backend.
The diagram above illustrates the relationship between various state management layers and the Supabase backend services. Sources: README.md, FIXES-APLICADOS.md
Domain-Specific State: React Context API
The core modules of the application, specifically Authentication and Chat, utilize React Context to provide reactive data to the component tree.
Authentication State
The AuthContext manages the user session, loading states, and authentication status. It integrates directly with Supabase Auth to handle login, logout, and token persistence.
| State Property | Type | Description |
|---|---|---|
user | `User | null` |
session | `Session | null` |
isLoading | boolean | Indicates if the initial session check is in progress. |
isAuthenticated | boolean | Derived state checking if a valid user session exists. |
Sources: contexts/AuthContext.tsx, README.md
Real-time Chat State
The ChatContext is responsible for managing messaging rooms and real-time synchronization. It utilizes Supabase Realtime (Postgres Changes) to push updates to the UI without requiring manual refreshes.
The sequence above details the flow of a message from the UI through the Context provider to the backend and back via Realtime triggers. Sources: REPORTE_CHAT_MODULE.md, contexts/ChatContext.tsx:191-284
Global UI & Tool State: Zustand
The application employs Zustand as a lightweight alternative to Redux for global state that does not require the overhead of a Context Provider for every small change. This is specifically used for modular features like the Calculator.
Calculator Slice
The calculatorSlice manages specific calculation sessions for milling and drilling operations, ensuring that user input is persisted during the session.
| Function/Action | Description |
|---|---|
setCalculation | Updates the current active calculation parameters. |
clearSession | Resets the calculator state. |
persistResults | Saves results to the local store for history tracking. |
Sources: store/calculatorSlice.ts, store/index.ts
Server State Management: TanStack Query
For data-heavy modules like "Requests" (Solicitudes) and "Directory", the app uses TanStack Query. This strategy addresses:
- Caching: Avoiding redundant API calls to Supabase.
- Optimistic Updates: Immediately updating the UI before the server confirms the action (e.g., sending a chat message or creating a request).
- Loading/Error Handing: Standardized states for asynchronous operations.
Sources: README.md, FIXES-APLICADOS.md
Implementation Patterns
Optimistic Updates in Requests
When a user submits a new request, the state management layer performs an optimistic update to provide immediate feedback.
// Example implementation pattern for Requests
console.log('=== INICIANDO CREACIÓN DE SOLICITUD ===');
// Local UI state update (Optimistic)
setSubmitting(true);
// Backend Sync
const { data, error } = await supabase.from('requests').insert(requestData);
// Rollback or Finalize
if (error) {
console.error('Error details:', error);
} else {
// Refresh Server State via TanStack Query invalidation
}
Sources: FIXES-APLICADOS.md:245-280, FIXES-APLICADOS.md:327-353
Real-time Subscription Logic
The ChatContext implements a robust subscription cleanup pattern to prevent memory leaks and redundant listeners.
const setupRealtimeSubscription = (roomId: string) => {
const channel = supabase
.channel(`chat_room_${roomId}`)
.on('postgres_changes', {
event: 'INSERT',
schema: 'public',
table: 'messages',
filter: `chat_room_id=eq.${roomId}`,
}, payload => {
// Process new message
})
.subscribe();
return () => {
supabase.removeChannel(channel);
};
};
Sources: contexts/ChatContext.tsx:191-284, FIXES-APLICADOS.md
Summary
The ELMEC V2 state management strategy is designed for responsiveness and data integrity. By isolating high-frequency real-time updates within Context Providers and using Zustand for specialized UI modules, the application maintains a clean separation of concerns. TanStack Query acts as the primary synchronization layer for standard CRUD operations, ensuring that the local cache remains consistent with the Supabase PostgreSQL database.