|
| 1 | +--- |
| 2 | +name: onyx |
| 3 | +description: Onyx state management patterns — useOnyx hook, action files, optimistic updates, collections, and offline-first architecture. Use when working with Onyx connections, writing action files, debugging state, or implementing API calls with optimistic data. |
| 4 | +--- |
| 5 | + |
| 6 | +## Core Concepts |
| 7 | + |
| 8 | +Onyx is a **persistent storage solution wrapped in a Pub/Sub library** that enables reactive, offline-first data management — key-value storage with automatic AsyncStorage persistence, reactive subscriptions, and collection management. |
| 9 | + |
| 10 | +For the full API reference (initialization, storage providers, cache eviction, benchmarks, Redux DevTools), see https://github.com/Expensify/react-native-onyx/blob/main/README.md. |
| 11 | + |
| 12 | +## Common Patterns |
| 13 | + |
| 14 | +### Action File Pattern |
| 15 | + |
| 16 | +**IMPORTANT:** Onyx state must only be modified from action files (`src/libs/actions/`). Never call `Onyx.merge`, `Onyx.set`, `Onyx.clear`, or `API.write` directly from a component. |
| 17 | + |
| 18 | +```typescript |
| 19 | +import Onyx from 'react-native-onyx'; |
| 20 | +import ONYXKEYS from '@src/ONYXKEYS'; |
| 21 | + |
| 22 | +function setIsOffline(isNetworkOffline: boolean, reason = '') { |
| 23 | + if (reason) { |
| 24 | + Log.info(`[Network] Client is ${isNetworkOffline ? 'offline' : 'online'} because: ${reason}`); |
| 25 | + } |
| 26 | + Onyx.merge(ONYXKEYS.NETWORK, {isOffline: isNetworkOffline}); |
| 27 | +} |
| 28 | + |
| 29 | +export {setIsOffline}; |
| 30 | +``` |
| 31 | + |
| 32 | +### Optimistic Updates Pattern |
| 33 | + |
| 34 | +Optimistic updates allow users to see changes immediately while the API request is queued. This is fundamental to Expensify's offline-first architecture. |
| 35 | + |
| 36 | +For **which pattern to use** (A / B / C / D) and UX behavior for each, see https://github.com/Expensify/App/blob/main/contributingGuides/philosophies/OFFLINE.md. |
| 37 | + |
| 38 | +#### Understanding the Three Data Sets |
| 39 | + |
| 40 | +**CRITICAL:** Backend response data is automatically applied via Pusher updates or HTTPS responses. You do NOT manually set backend data in `successData`/`failureData` — only UI state cleanup goes there. |
| 41 | + |
| 42 | +1. **optimisticData** (Applied immediately, before the API call) |
| 43 | + - Mirrors what the backend would return on success |
| 44 | + - Gives the user instant feedback without waiting for the server |
| 45 | + - Often includes `pendingAction` to flag the change as in-flight (e.g. greying out a comment while offline) |
| 46 | + - `pendingAction` is cleared once `successData` or `failureData` is applied |
| 47 | + |
| 48 | +2. **successData** (Applied when API succeeds) |
| 49 | + - Used for UI state cleanup: clearing `pendingAction`, setting `isLoading: false` |
| 50 | + - For `add` actions: often not needed (optimisticData already set the right state) |
| 51 | + - For `update`/`delete` actions: include to clear pending state |
| 52 | + |
| 53 | +3. **failureData** (Applied when API fails) |
| 54 | + - Reverts optimisticData changes |
| 55 | + - Clears `pendingAction`. |
| 56 | + - Adds `errors` field for the user to see |
| 57 | + - Always include this to handle unexpected failures |
| 58 | + |
| 59 | +For code examples of each pattern (A/B, loading state, `finallyData`), see [offline-patterns.md](offline-patterns.md). |
| 60 | + |
| 61 | +## Performance Optimization |
| 62 | + |
| 63 | +### 1. Subscribe to Specific Collection Members |
| 64 | + |
| 65 | +```typescript |
| 66 | +// BAD: re-renders on any report change |
| 67 | +const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT); |
| 68 | +const myReport = allReports[`report_${reportID}`]; |
| 69 | + |
| 70 | +// GOOD: re-renders only when this report changes |
| 71 | +const [myReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`); |
| 72 | +``` |
| 73 | + |
| 74 | +### 2. Use Selectors to Narrow Re-renders |
| 75 | + |
| 76 | +```typescript |
| 77 | +const accountIDSelector = (account: Account) => account?.accountID; |
| 78 | +const [accountID] = useOnyx(ONYXKEYS.ACCOUNT, {selector: accountIDSelector}); |
| 79 | +``` |
| 80 | + |
| 81 | +`useOnyx` caches by selector reference — a new function reference on every render bypasses the cache and causes unnecessary re-renders. Prefer pure selectors defined in `src/selectors/` over inline functions. If a selector must be defined inside a component, ensure referential stability: React Compiler handles this automatically, but in components that are not compiled, wrap the selector in `useMemo`. |
| 82 | + |
| 83 | +```typescript |
| 84 | +// BAD: new function reference on every render defeats caching |
| 85 | +const [accountID] = useOnyx(ONYXKEYS.ACCOUNT, {selector: (account) => account?.accountID}); |
| 86 | + |
| 87 | +// GOOD: stable reference defined outside the component |
| 88 | +// src/selectors/accountSelectors.ts |
| 89 | +const selectAccountID = (account: Account) => account?.accountID; |
| 90 | + |
| 91 | +// GOOD: stable reference via useMemo (for non-React-Compiler components) |
| 92 | +const selector = useMemo(() => (account: Account) => account?.accountID, []); |
| 93 | +const [accountID] = useOnyx(ONYXKEYS.ACCOUNT, {selector}); |
| 94 | +``` |
| 95 | + |
| 96 | +For `skipCacheCheck` (large objects) and batch collection update patterns, see https://github.com/Expensify/react-native-onyx/blob/main/README.md. |
| 97 | + |
| 98 | +## Common Pitfalls |
| 99 | + |
| 100 | +### Mixing set and merge on the Same Key |
| 101 | + |
| 102 | +`Onyx.set()` calls are not batched with `Onyx.merge()` calls, which can produce race conditions: |
| 103 | + |
| 104 | +```typescript |
| 105 | +// BAD: merge may execute before set resolves |
| 106 | +Onyx.set(ONYXKEYS.ACCOUNT, null); |
| 107 | +Onyx.merge(ONYXKEYS.ACCOUNT, {validated: true}); |
| 108 | + |
| 109 | +// GOOD: use one operation |
| 110 | +Onyx.set(ONYXKEYS.ACCOUNT, {validated: true}); |
| 111 | +``` |
| 112 | + |
| 113 | +## Common Tasks Quick Reference |
| 114 | + |
| 115 | +```typescript |
| 116 | +// Update a single field |
| 117 | +Onyx.merge(ONYXKEYS.NETWORK, {isOffline: true}); |
| 118 | + |
| 119 | +// Delete data |
| 120 | +Onyx.set(ONYXKEYS.ACCOUNT, null); |
| 121 | + |
| 122 | +// Subscribe in component |
| 123 | +const [data] = useOnyx(ONYXKEYS.SOME_KEY); |
| 124 | + |
| 125 | +// Subscribe with selector |
| 126 | +const [field] = useOnyx(ONYXKEYS.SOME_KEY, {selector: (data) => data?.specificField}); |
| 127 | + |
| 128 | +// Update collection member |
| 129 | +Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {unread: false}); |
| 130 | + |
| 131 | +// Batch update collection |
| 132 | +Onyx.mergeCollection(ONYXKEYS.COLLECTION.REPORT, updates); |
| 133 | + |
| 134 | +// API call with optimistic update |
| 135 | +API.write('SomeCommand', params, {optimisticData, successData, failureData}); |
| 136 | +``` |
| 137 | + |
| 138 | +## Related Files |
| 139 | + |
| 140 | +- https://github.com/Expensify/react-native-onyx/blob/main/README.md - Full Onyx API reference (initialization, merge/set/connect, collections, loading state, cache eviction, Redux DevTools, benchmarks) |
| 141 | +- https://github.com/Expensify/App/blob/main/contributingGuides/philosophies/OFFLINE.md - Full offline UX patterns, decision flowchart, and when to use each pattern (A/B/C/D) |
| 142 | +- [offline-patterns.md](offline-patterns.md) - Code examples for each optimistic update pattern |
| 143 | +- https://github.com/Expensify/App/blob/main/src/ONYXKEYS.ts - All Onyx key definitions |
| 144 | +- https://github.com/Expensify/App/tree/main/src/libs/actions - Action files that update Onyx |
| 145 | +- https://github.com/Expensify/App/blob/main/src/hooks/useOnyx.ts - useOnyx hook implementation |
| 146 | +- https://github.com/Expensify/App/tree/main/src/types/onyx - TypeScript types for Onyx data |
0 commit comments