Optimistic Sort Order
Relevant source files
The following files were used as context for generating this wiki page:
The Optimistic Sort Order feature is a specialized implementation designed to enhance the user experience within Sanity Studio's visual editing environment. Its primary purpose is to provide immediate, smooth visual feedback when a content creator reorders items in a list (such as projects on the homepage or navigation links) before the changes are fully persisted to the Sanity Content Lake.
This system is specifically active during Draft Mode. It intercepts real-time document mutations from the Sanity Studio and applies a temporary "optimistic" state to the frontend list, ensuring that reordering actions feel instantaneous and fluid.
Sources: components/OptimisticSortOrder/index.tsx:11-14, components/OptimisticSortOrder/index.client.tsx:21-25
Architecture and Data Flow
The system employs a hybrid Server/Client component architecture. The server-side component acts as a gatekeeper, ensuring the heavy client-side logic is only loaded when necessary (during editing).
Component Hierarchy
The architecture consists of a wrapper component that conditionally loads a client-side hook-based component.
The diagram above illustrates how the system determines whether to apply optimistic logic based on the application's current mode.
Sources: components/OptimisticSortOrder/index.tsx:16-37, components/OptimisticSortOrder/index.client.tsx:31-45
Implementation Details
| Component | Responsibility | Environment |
|---|---|---|
OptimisticSortOrder (Server) | Checks for id and draftMode().isEnabled. Returns raw children if not editing. | Server |
LazyOptimisticSortOrder | Dynamically imported client component to minimize bundle size for end-users. | Client |
useOptimistic (Hook) | A custom hook from next-sanity/hooks that reduces the document state to a sorted list of keys. | Client |
Sources: components/OptimisticSortOrder/index.tsx:7-35, components/OptimisticSortOrder/index.client.tsx:7-12
Integration and Usage
The OptimisticSortOrder component is integrated into several key areas of the website where list reordering is a common administrative task. It requires a Sanity document id and a path (as a StudioPathLike) to identify which field in the document should be tracked for optimistic updates.
Supported Lists
| Location | Path in Sanity | Description |
|---|---|---|
| Homepage | showcaseProjects | Reorders the list of featured projects. |
| Navbar | menuItems | Reorders top-level navigation links. |
| Timeline | path / milestones | Reorders timeline sections and individual milestones within them. |
Sources: components/HomePage.tsx:39, components/Navbar.tsx:23, components/TimelineSection.tsx:37-52
Sequential Flow of a Reorder Action
When a user drags an item in Sanity Studio, the following sequence occurs:
This flow ensures the UI responds to the "draft" version of the document currently held in the Studio's state.
Sources: components/OptimisticSortOrder/index.client.tsx:31-61, components/HomePage.tsx:40-62
Implementation Logic
The core logic resides in components/OptimisticSortOrder/index.client.tsx. It uses a reducer-like function to process Sanity document actions:
- Validation: It verifies that the incoming action ID matches the component's
idprop to avoid responding to unrelated document edits. - Path Resolution: It uses
@sanity/util/paths'sgetfunction to find the array at the specifiedpath. - Key Extraction: It maps the array of objects to an array of their
_keyvalues. - Bail-out Condition: If the optimistic state has fewer items than the current children (indicating incomplete data), it bails and returns the original children to prevent UI flickering or data loss.
- Re-sorting: It uses a
Mapto cache child elements by theirkeyand iterates through the optimistic key array to return the children in the new order.
Sources: components/OptimisticSortOrder/index.client.tsx:31-59
Schema and Query Support
For the Optimistic Sort Order to function, the GROQ queries must return the _key attribute for items within the arrays being sorted.
// Example from homePageQuery
export const homePageQuery = defineQuery(`
*[_type == "home"][0]{
_id,
showcaseProjects[]{
_key, // Required for reordering identification
...@->{ ... }
}
}
`)
Sources: sanity/lib/queries.ts:5-15, components/OptimisticSortOrder/index.client.tsx:55-58
Conclusion
The Optimistic Sort Order system is a critical utility for providing a native-feeling authoring experience. By leveraging Next.js Draft Mode and Sanity's real-time mutation hooks, it bridges the gap between the administrative Studio and the live frontend, allowing for immediate visual validation of content structural changes.