Optimistic UI Updates
Relevant source files
The following files were used as context for generating this wiki page:- apps/web/src/components/calendar/hooks/optimistic-actions.ts
- apps/web/src/components/calendar/hooks/use-optimistic-events.ts
- apps/web/src/components/calendar/flows/update-event/use-update-action.tsx
- apps/web/src/components/calendar/hooks/use-optimistic-mutations.ts
- apps/web/src/components/calendar/flows/create-event/create-queue.ts
The Optimistic UI Update system for the calendar provides users with immediate visual feedback for operations such as creating, updating, and deleting events. Instead of waiting for a server response, the UI is updated instantly as if the operation has already succeeded. This enhances the user experience by making the application feel faster and more responsive.
This system is primarily built using Jotai for state management and integrates with TanStack Query and tRPC for data fetching and mutations. When a user performs an action, an "optimistic action" is dispatched and stored in a global Jotai atom. UI components, like the calendar grid, read from a hook that combines the source-of-truth server data with these pending optimistic actions to render the most up-to-date view.
Architecture Overview
The optimistic update mechanism revolves around a central Jotai atom that stores a list of pending actions. Hooks and components can add actions to this list to trigger an optimistic update. A specialized hook, useOptimisticEvents, is responsible for merging these actions with the actual event data fetched from the server to produce the final list of events displayed to the user.
This diagram shows the high-level data flow from a user action to the final UI update.
Core Concepts
Optimistic Actions
The fundamental unit of the system is the OptimisticAction. It's a data structure that describes a change to be applied to the UI. These actions are stored in an array within a Jotai atom.
Sources: apps/web/src/components/calendar/hooks/optimistic-actions.ts
Action Types
There are four types of optimistic actions, each corresponding to a specific user operation.
| Type | Description | Payload |
|---|---|---|
create | Represents the creation of a new event. | id, type, eventId, event |
update | Represents an update to an existing event. | id, type, eventId, event |
delete | Represents the deletion of an event. | id, type, eventId |
draft | Represents a temporary, unsaved change to an event, often used during drag-and-drop resizing or moving. | type, eventId, event |
Sources: apps/web/src/components/calendar/hooks/optimistic-actions.ts, apps/web/src/components/calendar/flows/update-event/use-update-action.tsx:21-28
A unique optimisticId is generated for each action (except draft) to track it through its lifecycle, from creation to completion when the server confirms the mutation.
// apps/web/src/components/calendar/hooks/optimistic-actions.ts
export const generateOptimisticId = () => `optimistic-${uuidv4()}`;
Sources: apps/web/src/components/calendar/hooks/optimistic-actions.ts
State Management with Jotai
Jotai atoms are used to manage the state of optimistic actions across the application.
This diagram illustrates the relationship between the core atoms.
optimisticActionsAtom: The source-of-truth atom that holds an array of all pendingOptimisticActionobjects.addOptimisticActionAtom: A write-only atom used to add a new action to theoptimisticActionsAtom.removeOptimisticActionAtom: A write-only atom to remove a completed or failed action from the list by itsoptimisticId.removeDraftOptimisticActionsByEventIdAtom: A write-only atom specifically for clearingdraftactions associated with a particular event ID. This is useful when a draft action is finalized into anupdateaction.optimisticActionsByEventIdAtom: A read-only, derived atom that transforms the array of actions into aRecord<string, OptimisticAction>. This provides an efficient lookup where the latest action for any giveneventIdis stored, simplifying the process of applying updates.
Sources: apps/web/src/components/calendar/hooks/optimistic-actions.ts, apps/web/src/components/calendar/flows/update-event/use-update-action.tsx:11-13
Applying Optimistic Updates
The useOptimisticEvents hook is the consumer of the optimistic state. It is responsible for creating the final list of events that gets rendered in the calendar view.
The process is as follows:
- Fetch the canonical list of events from the server using a tRPC query (
trpc.events.list). - Get the latest optimistic actions from the
optimisticActionsByEventIdAtom. - Create a mutable copy of the server events.
- Filter out any server events that have a corresponding pending action.
- Iterate through the optimistic actions and apply them to the event list:
- For
create,update, anddraftactions, convert the event payload into a calendar item and insert it into the list in the correct sorted position. - For
deleteactions, ensure the event is not present in the list (it would have been filtered out in step 4).
- For
- Return the final, merged list of events.
This flow is visualized in the diagram below:
Triggering Optimistic Actions
Actions are triggered by user interactions, which call specialized hooks that handle the logic of adding an optimistic action and initiating the actual server mutation.
Updating an Event
The useUpdateAction hook provides a function to handle event updates. When called, it performs two main tasks:
- Generates a unique
optimisticId. - Adds an
updateaction to theoptimisticActionsAtominside aReact.startTransitionblock to prevent the UI from blocking. - Sends an item to the
UpdateQueueContextactor, which presumably handles the background API call to the server.
The sequence diagram below illustrates this process.
Centralized Mutations with useOptimisticMutations
The useOptimisticMutations hook is expected to centralize the create, update, and delete logic. It likely wraps tRPC mutations and uses the optimistic action atoms to provide immediate UI feedback.
The hook would expose functions like:
createEvent(eventData)updateEvent(eventData)deleteEvent(eventId)
Each of these functions would follow a similar pattern:
- Add the corresponding optimistic action (
create,update,delete) to the Jotai state. - Call the actual tRPC mutation.
- On success (
onSuccess), remove the optimistic action from the Jotai state. - On error (
onError), remove the optimistic action and potentially show an error to the user, effectively rolling back the UI change.
Sources: apps/web/src/components/calendar/hooks/use-optimistic-mutations.ts
Summary
The optimistic UI update system in Analog is a well-defined mechanism that leverages Jotai for reactive state management to decouple the UI from the latency of server communication. By immediately reflecting user-initiated changes and handling the server synchronization in the background, it creates a highly responsive and fluid user experience within the calendar module. The system is robust, handling creation, updates, deletions, and even transient draft states.