Skip to main content

Optimistic Updates

An optimistic update shows the result of a mutation before the server responds. It assumes the request succeeds, so the interface does not wait for the network.

Optimistic updates add new race conditions. Reactive Data Client handles them for you.

Resources​

To make a resource() optimistic, set optimistic: true.

import { Entity, resource } from '@data-client/rest';

export class Todo extends Entity {
  id = 0;
  userId = 0;
  title = '';
  completed = false;

  static key = 'Todo';
}
export const TodoResource = resource({
  urlPrefix: 'https://jsonplaceholder.typicode.com',
  path: '/todos/:id',
  searchParams: {} as { userId?: string | number } | undefined,
  schema: Todo,
  optimistic: true,
});
Live Preview

All its mutations then use these default optimistic responses:

EndpointOptimistic response
update, getList.push, getList.unshift, getList.assign, getList.remove, getList.moveThe URL params merged with the body (FormData becomes an object)
partialUpdateThe cached entity with the body merged in
deleteThe params, which remove the entity

A create (push/unshift) body usually has no id to compute a pk from. So Data Client creates a random pk.

Mutations on the new object usually fail until the server creates it. So disable other mutations on it until the POST completes. For example, check that the entity has a real id.

Partial updates do not send the entire body. Fields the expected response leaves out keep their cached values, so an Entity only needs its primary key and the changed fields. If the entity is not in the store yet, the update aborts instead of showing an Entity made only of the changed fields. Snapshots read the current store value safely, with no race conditions.

To make only some endpoints optimistic, or to match an unusual API, set getOptimisticResponse() with Resource.extend().

Optimistic Transforms​

Some updates depend on the previous value, such as toggling a boolean or incrementing a counter. This example uses a counter.

import { RestEndpoint } from '@data-client/rest';
import { CountEntity, getCount } from './count';

export const increment = new RestEndpoint({
  path: '/api/count/increment',
  method: 'POST',
  body: undefined,
  name: 'increment',
  schema: CountEntity,
  getOptimisticResponse(snap) {
    const data = snap.get(CountEntity, {});
    if (!data) throw snap.abort;
    return {
      count: data.count + 1,
    };
  },
});
Live Preview

Reactive Data Client handles race conditions from network timing. It tracks when each fetch starts, pairs each response with its optimistic update, and rolls the update back when the request resolves or fails.

Other libraries have these race conditions even without optimistic updates. Optimistic updates make them worse.

Example race condition​

This example requests two increments. The first response arrives after the second.

ClientServerOtherno optimisticOtheroptimisticData Clientoptimistic+111+1220210210122101210121012

Other libraries show 0, 2, then 1 without optimistic updates, and 0, 1, 2, 2, then 1 with them. Both end on the wrong count, with janky updates along the way. Data Client shows 0, 1, then 2, and keeps 2 when the older response arrives last.

Compensating for Server timing variations​

Three timings can vary in an async mutation:

  1. Request timing
  2. Server timing
  3. Response timing

Reactive Data Client handles response timing for you. This is usually enough, because servers usually process requests in the order they arrive. If requests arrive or are saved in a different order, a race condition remains.

To fix it, keep a total order with one clock. Server and client clocks can differ, and optimistic updates happen on the client, so use the client's clock:

  1. Send the request time as updatedAt in the body with getRequestInit().
  2. The server processes requests in updatedAt order, stores updatedAt in the entity, and returns it in every response.
  3. Override shouldReorder to reorder out-of-order responses by updatedAt.

getOptimisticResponse uses snap.fetchedAt. It is the moment the fetch starts, on the same clock as updatedAt (a fraction of a millisecond later when several fetches start in one millisecond).

import { RestEndpoint } from '@data-client/rest';
import { CountEntity } from './count';

export const increment = new RestEndpoint({
  path: '/api/count/increment',
  method: 'POST',
  body: undefined,
  name: 'increment',
  schema: CountEntity,
  getRequestInit() {
    // this is a substitute for super.getRequestInit()
    // since we aren't in a class context
    return RestEndpoint.prototype.getRequestInit.call(this, {
      updatedAt: Date.now(),
    });
  },
  getOptimisticResponse(snap) {
    const data = snap.get(CountEntity, {});
    if (!data) throw snap.abort;
    return {
      count: data.count + 1,
      updatedAt: snap.fetchedAt,
    };
  },
});
Live Preview

Keep clicks responsive on heavy screens​

Like React's useOptimistic(), an optimistic update renders before the browser paints the click. If many components show the changed data, that render can make the click feel slow.

When to use a transition​

First make that render cheaper, with React Compiler or memo() on expensive components. A cheaper render keeps the update instant, while a transition only moves it after the paint. If the click is still slow, call ctrl.fetch(), which applies the optimistic update, inside startTransition() (React 18+).

Skip the transition when:

  • The update re-renders only a few components. The transition then delays the update with no slow render to hide.
  • The control is a controlled input, like TodoItem's checkbox. React resets the input to its last rendered value, so the checkbox flips back until the transition renders (see the startTransition() caveats).

For example, renaming a user re-renders every comment that shows their name:

import { startTransition, type FormEvent } from 'react';
import { useController } from '@data-client/react';
import { UserResource, type User } from './UserResource';

export function RenameUser({ user }: { user: User }) {
const ctrl = useController();
const handleSubmit = (e: FormEvent<HTMLFormElement>) => {
e.preventDefault();
const name = new FormData(e.currentTarget).get('name') as string;
startTransition(() => {
ctrl.fetch(UserResource.partialUpdate, { id: user.id }, { name });
});
};
return (
<form onSubmit={handleSubmit}>
<input name="name" defaultValue={user.name} />
<button type="submit">Rename</button>
</form>
);
}

React renders the optimistic update at transition priority, so the browser paints and handles input first. Wrap the call in braces, as above, so the callback returns nothing. In React 19, a callback that returns the fetch() promise is an async Action, and React holds the optimistic update until the server responds.