The Effect Chain That Made Live Updates Refetch Bookings
Some of the most expensive bugs in a React application never throw an error. They do not crash the app or leave a red screen behind. They often survive code review because every individual piece looks reasonable. This is the story of one of those bugs.
A Home screen in a production React Native application loaded its data through a chain of seven effects. Each effect waited for state written by the previous one. Opening the screen walked through that chain one render at a time.
Then live updates entered the picture. A notification equivalent to “your guide is running late” changed one widget in the global store. That update had nothing to do with bookings, yet it caused the application to request both booking lists again.
One live alert. Two unnecessary API calls.
Because those requests could overlap, an older response could occasionally beat a newer one back to the store. Most of the time, the screen still looked correct; the visible failures appeared only when request timing or two mounted screens lined up. That was precisely why the problem lasted.
To tell this story without exposing the original product, I will frame Home as part of a booking app for city walks, food tours, boat trips, and other experiences. The production application used React Native, TypeScript, and Zustand. Only the domain and entity names have changed; the architecture and failure sequence are unchanged.
The mobile client talked to a backend-for-frontend that aggregated data from several internal services. Home started with GET /v1/me/home-feed, which returned an ordered collection of widgets already summarized for display.
Bookings were the exception. The same upcoming and past lists were also used by the dedicated Bookings screen, so they came from GET /v1/me/bookings/upcoming and GET /v1/me/bookings/past. Live updates arrived separately through one WebSocket connection at /v1/me/events.
Those events updated the Zustand store directly. The store followed an immutable update model: updating a trip alert created a new widget and therefore a new widgets array instead of mutating the existing object. That is normally a useful property. Here, it exposed a much deeper problem:
- Trip alerts could change while Home was open.
- Bookings signaled that Home needed the separately loaded booking lists.
- Next experience, Tickets, and Wishlist lived in the same widget collection even though their updates had nothing to do with those lists.
All Home orchestration lived inside one custom hook containing seven effects. In simplified form, the architecture looked roughly like this:
function useHomeScreen() {
const homeFeed = useHomeFeedResponse();
const upcomingResponse = useUpcomingBookingsResponse();
const pastResponse = usePastBookingsResponse();
const widgets = useHomeStore((state) => state.widgets);
const upcoming = useHomeStore((state) => state.upcomingBookings);
const past = useHomeStore((state) => state.pastBookings);
const setWidgets = useHomeStore((state) => state.setWidgets);
const setUpcoming = useHomeStore((state) => state.setUpcomingBookings);
const setPast = useHomeStore((state) => state.setPastBookings);
const setHasBookingHistory = useHomeStore(
(state) => state.setHasBookingHistory,
);
const [sections, setSections] = useState<HomeSection[]>([]);
// 1. Load the feed.
useEffect(() => {
fetchHomeFeed();
}, []);
// 2. Copy the response into the store.
useEffect(() => {
if (homeFeed.data) {
setWidgets(homeFeed.data.widgets);
}
}, [homeFeed.data, setWidgets]);
// 3. Bookings widget exists? Fetch two more resources.
useEffect(() => {
const hasBookingsWidget = widgets.some(
(widget) => widget.type === "bookings",
);
if (hasBookingsWidget) {
fetchUpcomingBookings();
fetchPastBookings();
}
}, [widgets]);
// 4. Copy the upcoming bookings response into the store.
useEffect(() => {
if (upcomingResponse.data) {
setUpcoming(upcomingResponse.data);
}
}, [upcomingResponse.data, setUpcoming]);
// 5. Copy the past bookings response into the store.
useEffect(() => {
if (pastResponse.data) {
setPast(pastResponse.data);
}
}, [pastResponse.data, setPast]);
// 6. Derive and store whether the traveler has booking history.
useEffect(() => {
setHasBookingHistory(
upcoming.length === 0 && past.length > 0,
);
}, [upcoming, past, setHasBookingHistory]);
// 7. Build the renderable Home sections from the widgets.
useEffect(() => {
setSections(buildHomeSections(widgets));
}, [widgets]);
return { sections };
}Read from top to bottom, nothing here screams “production incident.” Each effect has one responsibility, dependencies are declared, and state changes are explicit. The problem appears when you stop reading the effects independently and trace the data flow between them.
React's execution model is more precise than a simple sequence of renders and requests. A state update triggers a render, React calculates the next UI, and the commit applies the required changes. Passive effects run after that commit. If an effect, an asynchronous response, or an external store update writes state, that write schedules another update cycle rather than continuing the current render.
The effects had quietly become a pipeline, but not as one synchronous call stack. The first diagram establishes the documented React cycle that each state change could restart:
The Home hook layered application-specific dependencies on top of that cycle. The feed response populated widgets; the presence of a Bookings widget launched two requests; their responses wrote more store state; and those writes fed derived values and section building. The second diagram maps those transitions without implying that the requests completed serially or that React produced a fixed number of renders:
Batching, selector equality, request timing, and development-only Strict Mode behavior could change how many renders and effect runs we observed—and when they occurred. None of those runtime details changed the underlying design flaw: effects were coordinating an application workflow, so each state write could re-enter React's update cycle and give downstream work another chance to run.
The most damaging effect was also one of the smallest:
useEffect(() => {
const hasBookingsWidget = widgets.some(
(widget) => widget.type === "bookings",
);
if (hasBookingsWidget) {
fetchUpcomingBookings();
fetchPastBookings();
}
}, [widgets]);The effect only needed the answer to one question: Does a Bookings widget exist? But it subscribed to the entire widgets collection.
Now imagine a WebSocket message arrives:
{
type: "TRIP_ALERT_UPDATED",
message: "Your guide is running 10 minutes late"
}The store correctly replaces the Trip Alerts widget with an updated copy, producing a new widgets array. The Bookings widget did not change, its existence did not change, and the booking data did not change. But [widgets] changed.
The effect therefore ran again, answered the same question with true, and sent both booking requests again. The seventh effect also saw the new array and rebuilt the Home sections, even though the static Discover section had not changed.
The subscription boundary was much wider than the business dependency.
A second problem was harder to spot. Home stored hasBookingHistory, but the Bookings screen also calculated and stored that value. Worse, the screens disagreed about its meaning.
Home effectively used upcoming.length === 0 && past.length > 0 because it wanted to decide whether to display a “Plan your next experience” prompt.
The Bookings screen used past.length > 0 because it wanted to know whether a Past tab should exist.
Those are not actually two definitions of the same concept. They are two different UI decisions masquerading as one shared piece of state.
Because bottom-tab screens stayed mounted after being visited, both screens could remain alive and observe the same booking lists. For a traveler with upcoming and past bookings, Home could write false while Bookings wrote true.
Whichever effect ran last won. A live update arriving while Home was in the background could therefore change what the Bookings screen rendered.
The value was deterministic from existing state, yet we had stored another mutable copy of it, giving it the opportunity to drift.
Repeated booking fetches introduced another failure mode. Alert A started one upcoming request and one past request. Before that pair had settled, Alert B started another pair for the same resources.
Nothing guaranteed that response A would finish before response B. If request B returned first and request A returned later, the older data could overwrite the newer data. The UI could temporarily move backward in time: a tour rescheduled one minute earlier could show its previous start time until another refresh corrected it.
There was no exception—only stale truth.
Once I reproduced the original hooks inside a small harness and mocked only the network boundary, the architecture became much easier to quantify.
| Scenario | Home renders | Network requests |
|---|---|---|
| Open Home in the isolated harness | 9 | 3 |
| Open Home with the additional startup tab update | 15 | 7 |
| One live trip alert after startup | +6 | +2 |
| Four alerts around one experience | +24 | +8 |
The three legitimate startup requests were easy to explain: one home feed request and two booking requests. The additional work was not.
In the real application, another tab mounted during startup because the tab navigator did not lazy-load its screens. Once that screen finished loading, it updated one of Home's widgets. The update created a new widget list, woke the broad [widgets] dependency, and called the two booking endpoints again.
The live-alert pattern made the multiplier more visible. Travel notifications naturally cluster near the experience itself: a meeting-point confirmation, a reminder, a guide delay, and a start notification. Four live updates meant eight extra booking requests.
These measurements were also a lower bound. The harness counted the Home component itself, not every rendered list item beneath it, and it intentionally omitted unrelated startup writes to the global store.
The production build I measured still used React Native's legacy architecture, including application-specific updates that the isolated harness omitted, produced roughly 13 to 21 Home renders rather than the 9 to 15 observed in the simpler cases. Those numbers describe that build and runtime, not batching behavior in current React Native applications.
The app was paying the most synchronization cost precisely when the traveler was most likely to be using it.
The eventual fix was not another dependency-array adjustment. Five effects disappeared, and three architectural rules replaced them.
hasBookingHistory was neither server state nor user input. It did not originate outside the application. It was a fact we could answer from pastBookings.
So it became a selector:
const selectHasBookingHistory = (state: HomeStore) =>
state.pastBookings.length > 0;Both screens could now agree on what booking history meant, while Home's actual UI rule remained separate:
const hasBookingHistory = useHomeStore(
selectHasBookingHistory,
);
const upcomingBookings = useHomeStore(
(state) => state.upcomingBookings,
);
const shouldShowPlanNextExperience =
hasBookingHistory && upcomingBookings.length === 0;The distinction matters: hasBookingHistory describes the data, while shouldShowPlanNextExperience describes Home's presentation decision.
The Bookings screen can use the same history selector without inheriting Home's UI rule. The Home sections followed the same principle: they were a deterministic transformation of widgets plus static Discover shortcuts, so they no longer needed their own state.
const widgets = useHomeStore((state) => state.widgets);
const sections = useMemo<HomeSection[]>(
() => [
{
title: "For you",
data: widgets,
},
{
title: "Discover",
data: DISCOVER_SHORTCUTS,
},
],
[widgets],
);No effect copies them into local state, and no extra render is required to make the derived value visible. There is simply less state to synchronize.
The old implementation separated starting a request from storing its result, turning one business operation into several reactive transitions. Instead, the store action owned the complete operation, including which invocation was allowed to commit its result:
export const useHomeStore = create<HomeStore>()((set) => {
// Private concurrency state for this store instance.
let latestBookingsRequest: symbol | null = null;
return {
widgets: [],
upcomingBookings: [],
pastBookings: [],
loadHomeFeed: async () => {
const feed = await api.get<HomeFeed>("/v1/me/home-feed");
set({
widgets: feed.widgets,
});
},
loadBookings: async () => {
const requestToken = Symbol("bookings-request");
latestBookingsRequest = requestToken;
const [upcoming, past] = await Promise.all([
api.get<Booking[]>("/v1/me/bookings/upcoming"),
api.get<Booking[]>("/v1/me/bookings/past"),
]);
// A newer invocation already replaced this token.
if (latestBookingsRequest !== requestToken) {
return;
}
set({
upcomingBookings: upcoming,
pastBookings: past,
});
},
};
});Upcoming and past bookings represent one logical refresh from the screen's perspective, so they are fetched together and committed together.
The request token lives in the closure created for this store instance. Component renders do not recreate the store or its closure, so the token survives for the store's lifetime rather than the lifetime of any screen.
Every invocation captures its own unique token, while the shared binding always points to the newest invocation. Creating a different store instance also creates a different binding, and the request marker never becomes persisted or subscribable application state.
The example omits loading, retry, and error state to keep the ordering rule visible. Promise.all also makes an intentional tradeoff: if either request fails, neither list is committed as the new snapshot. A product that can safely show one list without the other could handle the results independently while preserving the same newest-request guard.
The request token also establishes a simple invariant:
Only the result of the newest booking refresh may update the store.
A slower, older response can still finish, but it cannot overwrite newer data. An AbortController or a server-state library can provide stronger cancellation behavior when appropriate; the particular mechanism matters less than making request ordering intentional.
The original effect depended on widgets, but the business dependency was only the existence of one widget. That became its own selector:
const selectHasBookingsWidget = (state: HomeStore) =>
state.widgets.some(
(widget) => widget.type === "bookings",
);Home then subscribed directly to that boolean:
function useHomeScreen() {
const loadHomeFeed = useHomeStore(
(state) => state.loadHomeFeed,
);
const loadBookings = useHomeStore(
(state) => state.loadBookings,
);
const hasBookingsWidget = useHomeStore(
selectHasBookingsWidget,
);
useEffect(() => {
void loadHomeFeed();
}, [loadHomeFeed]);
useEffect(() => {
if (hasBookingsWidget) {
void loadBookings();
}
}, [hasBookingsWidget, loadBookings]);
}The void prefix makes it explicit that these effects intentionally discard the Promise returned by each action instead of awaiting it. It does not catch a rejected Promise; the production actions still need to expose errors through store state or handle them internally.
Those are the two effects that survived. Each corresponds to a real synchronization event: Home mounts, so it synchronizes with the home-feed API; the Bookings widget becomes available, so Home synchronizes with the booking APIs.
Now consider the same live alert. The Trip Alerts widget is replaced, the widgets array gets a new reference, and Zustand evaluates the selector again. But the selected value is still true: the Bookings widget existed before the alert and still exists afterward. From this subscriber's point of view, nothing changed, so no booking fetch follows. That was the boundary we wanted all along.
The outcome was much less interesting than the original implementation, and that was a good thing. Two effects remained. Live alerts stopped touching booking endpoints, the two screens stopped competing over derived state, and older requests could no longer overwrite newer ones.
At the network boundary, the result was concrete. Opening Home still made the three intentional requests: one for the feed and two for the booking lists. A live trip alert went from two unrelated booking requests to zero extra requests, so the four-alert scenario went from eight extra requests to zero. I did not claim a post-refactor render total without rerunning the harness against the specific React Native runtime, where batching behavior can change the result.
The pipeline was gone.
The useful lesson was not “global stores are bad” or “effects are bad.” Most of the surrounding architecture was worth keeping: the backend-for-frontend still provided a useful mobile-specific aggregation boundary, and a single WebSocket connection still made sense for user-specific live events.
The state model was also sound. Immutable widget updates kept transitions predictable, the booking lists remained shared because Home and Bookings consumed the same server data, and Zustand remained a lightweight fit for that client state.
None of those pieces caused the failure by itself. Immutable updates made the broad subscription observable, the WebSocket supplied enough updates to expose it, and the global store gave duplicated derived state somewhere to drift. React effects had simply been asked to coordinate work that belonged elsewhere. The connections were the problem.
The biggest lesson I took from this bug is that dependency arrays are part of your application's architecture. Each dependency defines when synchronization work may repeat, so subscribing an effect to an object, collection, or global state carries real weight when that effect performs I/O.
The useful design question is not only “Which variables does this callback reference?” It is “What business fact should make this operation happen again?” For the booking request, that fact was not “the widget array changed.” It was “a Bookings widget became available.” The two coincided during the initial load, then diverged as soon as live updates entered the system.
hasBookingHistory exposed a related smell. When two screens keep rewriting the same deterministic flag, I now question the flag before either screen. Here, hasBookingHistory and shouldShowPlanNextExperience represented different UI decisions that had been collapsed into one mutable boolean. Naming each decision by its intent removed the false shared lifecycle.
The principle extends beyond React Native. Storing derived values, chaining effects, and subscribing to an entire object for one yes-or-no answer all create synchronization surfaces. One extra surface may cost only a render; several can produce duplicate traffic, request races, conflicting state, and behavior determined by whichever mounted screen runs last.
Timing becomes behavior.
When I review effect-heavy React code now, I start with a quick diagnostic that requires almost no tooling: open the network inspector, trigger one live update, and watch what else gets fetched. If a notification about a guide delay causes booking history, preferences, or unrelated resources to reload, the live event itself may not be the problem. Something downstream is probably listening too broadly.
From there, these are the questions I ask:
- Can this value be computed from state we already own? Prefer deriving it rather than storing another synchronized copy.
- Are two effects handing state to each other? Consider moving the workflow into the operation that owns the data.
- Does an effect depend on a collection when it only needs one fact about that collection? Subscribe to the fact.
- Is the same derived concept being written from multiple places? Give the concept one definition, then let each screen derive its own presentation decisions.
- Can multiple requests for the same resource overlap? Define what “latest” means before the race happens.
The original hook was easy to defend in code review. One effect fetched data. Another copied it. Another derived a flag. Another prepared a list. Seven small responsibilities. Nothing looked reckless.
The problem only appeared when I stopped looking at seven effects and started looking at one system. A “guide running late” alert entered the store at one end and two unrelated booking requests came out the other. Somewhere in between, a boolean could be rewritten by whichever mounted tab happened to run last, while overlapping requests competed to decide which version of reality the user would see.
No line of code contained that story. The architecture did.
That changed how I think about effects. I still use them when a component genuinely needs to synchronize with something outside React: a WebSocket, a native API, a timer, or a request triggered by a meaningful lifecycle event. What I no longer ask them to do is escort data from one state container to the next.
Once effects become a pipeline, every state transition becomes another stop.
Sometimes the most expensive bug in the app is a perfectly valid effect.
It is simply running exactly when you told it to.
- React — You Might Not Need an Effect
- React — Removing Effect Dependencies
- Zustand — Prevent Rerenders with
useShallow - Zustand — Immutable State and Merging
- MDN — Closures and Preserved Lexical State
- MDN —
Promise.all()Fulfillment and Rejection Behavior - MDN — The
voidOperator - React Native — About the New Architecture
- TanStack Query v5 — Dependent Queries