keepcalculator

06 Numbers and Powers

Mutation Succeeded UI Stale Trace Data Source

Card No. 06·77422 · Updated · Standard formula, shown below

When a mutation succeeds but the UI still shows stale data, the data source feeding the UI is not being refreshed or invalidated after the mutation completes. The fix is to trace the data flow from the mutation result to the UI state, identify where the cache or local state is not updated, and then invalidate or refetch that source.

Background: Why UI Staleness Happens After a Mutation

In modern web applications, a mutation (like creating, updating, or deleting a record) changes data on the server. The UI, however, typically displays data from a local source: a client-side cache (e.g., React Query, Apollo Client, SWR), a global state store (Redux, Zustand), or a component’s local state. When the mutation succeeds, the server sends back a response, but the UI does not automatically know that the displayed data is now outdated. Unless the client explicitly invalidates or updates the cached data, the UI continues to show the old snapshot.

This is a common issue in applications using GraphQL or REST APIs with client-side caching. The root cause is usually a missing cache invalidation step, an incorrect query key, or a component that is not subscribed to the updated data source.

How the Data Flow Works (and Where It Breaks)

To trace the data source, you need to map the journey of the data from the server to the UI. A typical flow looks like this:

  1. Mutation triggers: User submits a form or clicks a button, calling a mutation function (e.g., createUser).
  2. Server responds: The API returns a success response, often with the updated or created object.
  3. Cache update (optional): The client may update its cache with the response data (e.g., via onSuccess callback or a cache write).
  4. UI reads from cache/state: The component reads data from the cache or state via a hook (e.g., useQuery, useSelector).
  5. Staleness occurs: If step 3 is skipped or the query key doesn’t match, the component still reads the old cache entry.

Common breakpoints:

  • Missing invalidation: The mutation does not invalidate the query that the UI reads from.
  • Wrong query key: The mutation invalidates a different key than the one the component uses.
  • Local state not updated: The mutation result is not dispatched to the global store or setState.
  • Component not re-rendering: The component may be memoized or not subscribed to the data source change.

How to Trace the Exact Data Source

To pinpoint where the staleness originates, follow these steps:

  1. Inspect the network tab: Confirm the mutation succeeded (HTTP 200/201) and note the response body.
  2. Check the cache: Use the devtools of your data-fetching library (React Query, Apollo) to see if the cache entry for the relevant query was updated after the mutation.
  3. Examine the query key: Look at the component that displays the data and note the exact query key it uses. Then check what key the mutation invalidates.
  4. Look for a refetch: See if the mutation triggers a refetch of the query (e.g., refetchQueries or invalidateQueries).
  5. Check local state: If using Redux or Zustand, verify that the mutation dispatches an action to update the state slice that the component reads.

For example, in React Query, a mutation that creates a user should call queryClient.invalidateQueries(['users']) to mark the users list as stale. If the component uses useQuery(['users']), it will refetch. If the component uses useQuery(['people']), it won’t.

Common Problems and Their Fixes

Here are the most frequent causes and how to resolve them:

  • Query key mismatch: Ensure the mutation invalidates the exact same key (including variables) that the query uses. For instance, a query with ['user', id] must be invalidated with ['user', id], not just ['user'].
  • Cache not updated optimistically: If you want instant UI feedback, use optimistic updates. In React Query, you can set onMutate to update the cache optimistically and then rollback on error.
  • StaleTime too high: If staleTime is set to a large value (e.g., 5 minutes), the query won’t refetch even after invalidation until that time passes. Lower it or use refetchOnMount/refetchOnWindowFocus.
  • Component not re-rendering: If the component is wrapped in React.memo and the props don’t change, it may not re-render even if the cache updates. Ensure the component is subscribed to the query/state.
  • Multiple data sources: Sometimes a component reads from a local state that is initialized from a query but never synced back. Use the query cache as the single source of truth.

Comparing Approaches: Cache Invalidation vs. Direct Update

There are two main strategies to keep the UI fresh after a mutation:

  • Cache invalidation (refetch): Mark the query as stale and let it refetch from the server. This is simple and ensures data consistency, but it adds a network round-trip and may show a loading state.
  • Direct cache update (write): Manually update the cache with the mutation response. This is faster (no refetch) but requires you to know the exact shape of the cached data and handle list insertions/removals correctly.

For most cases, cache invalidation is preferred because it avoids duplication of logic and reduces the risk of cache/state divergence. Direct updates are useful for high-frequency interactions where refetching would be too slow.

Best Practices for Preventing Stale UI

To avoid this issue in the future, follow these guidelines:

  • Use a single data-fetching library (React Query, SWR, Apollo) and rely on its cache as the source of truth.
  • Define query keys consistently using a helper function or constants to avoid typos.
  • Invalidate queries in the onSuccess callback of the mutation, or use a global invalidation strategy.
  • Set a reasonable staleTime (e.g., 30 seconds) to balance freshness and performance.
  • Use optimistic updates for a responsive UI, but always rollback on error.
  • Test with the devtools to verify that the cache is updated after mutations.

Frequently Asked Questions

Why does the UI update after a page refresh but not after a mutation?

Because a full page refresh re-fetches all data from the server, bypassing the stale cache. After a mutation, the client cache still holds the old data unless you invalidate or update it. The mutation only changes the server state; the client cache is separate.

How do I know if the mutation actually succeeded?

Check the network tab for the mutation request. A 2xx status code means success. Also, look at the mutation function’s promise – it should resolve without throwing. If the mutation returns an error, the UI staleness is a separate issue.

What is the difference between invalidateQueries and refetchQueries?

invalidateQueries marks the query as stale and triggers a refetch only if the query is currently being observed. refetchQueries forces a refetch of the specified queries regardless of whether they are active. Use invalidateQueries for most cases, as it respects the cache’s staleness logic.

Can I update the cache manually without refetching?

Yes, you can use queryClient.setQueryData to directly write the mutation response into the cache. This is useful for optimistic updates or when you want to avoid a loading state. However, you must ensure the data structure matches exactly what the query expects.

Why does the UI update in one component but not another?

This usually means the two components use different query keys or different data sources. For example, one component might read from the cache while another reads from local state. Check the keys and the hooks used in each component.

Is this a problem with GraphQL or REST?

It can happen with both. GraphQL clients like Apollo have a normalized cache that requires explicit updates or refetches. REST clients like React Query use a simple key-value cache. The core issue is the same: the client cache is not automatically synchronized with the server after a mutation.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →