Reactive utilities

createOptimistic

Edit this page
import { createOptimistic } from "solid-js"
function createOptimistic<T>(
initialValue: T
): [get: () => T, set: (v: T) => T]

createOptimistic has the same surface as createSignal, but its writes are treated as optimistic — values overlay during a transition and automatically revert when the transition settles.

For a conceptual overview of the async model, see Async Reactivity.


Usage

import { createOptimistic, action } from "solid-js"
const [name, setName] = createOptimistic("Alice")
const updateName = action(function* (next) {
setName(next) // optimistic — UI updates immediately
yield api.saveName(next) // async work
})

During the action, name() returns the optimistic value. When the transition settles, the value reverts — regardless of whether the action succeeded or failed.


How rollback works

Optimistic writes are scoped to the transition created by an action. When the transition completes:

  • On success: The optimistic overlay is discarded. If you called refresh() to re-fetch the source data, the fresh server value takes over.
  • On failure: The optimistic overlay is also discarded, reverting the value to its pre-mutation state — automatic rollback with no extra code.
const [count, setCount] = createOptimistic(0)
const increment = action(function* () {
setCount(count() + 1) // optimistic: shows 1 immediately
yield api.increment() // if this fails...
// count() reverts to 0 automatically
})

Behavior outside actions

Outside of an action, createOptimistic behaves like a normal signal — writes are applied directly and do not revert. The optimistic rollback behavior only applies when writes happen inside an action's transition context.


When to use

Use createOptimistic when you need a single reactive value that should show an optimistic update during a mutation:

  • User name edits
  • Toggle states
  • Counter increments
  • Any single-value mutation

For store-level optimistic updates (objects, arrays), use createOptimisticStore instead.

Report an issue with this page