useOptimistic

useOptimistic is a React Hook that lets you optimistically update the UI.

const [optimisticState, setOptimistic] = useOptimistic(value, reducer?);

Reference

useOptimistic(value, reducer?)

Call useOptimistic at the top level of your component to create optimistic state for a value.

import { useOptimistic } from 'react';

function MyComponent({name, todos}) {
const [optimisticAge, setOptimisticAge] = useOptimistic(28);
const [optimisticName, setOptimisticName] = useOptimistic(name);
const [optimisticTodos, setOptimisticTodos] = useOptimistic(todos, todoReducer);
// ...
}

See more examples below.

Parameters

  • value: The value returned when there are no pending Actions.
  • optional reducer(currentState, action): The reducer function that specifies how the optimistic state gets updated. It must be pure, should take the current state and reducer action arguments, and should return the next optimistic state.

Returns

useOptimistic returns an array with exactly two values:

  1. optimisticState: The current optimistic state. It is equal to value unless an Action is pending, in which case it is equal to the state returned by reducer (or the value passed to the set function if no reducer was provided).
  2. The set function that lets you update the optimistic state to a different value inside an Action.

set functions, like setOptimistic(optimisticState)

The set function returned by useOptimistic lets you update the state for the duration of an Action. You can pass the next state directly, or a function that calculates it from the previous state:

const [optimisticLike, setOptimisticLike] = useOptimistic(false);
const [optimisticSubs, setOptimisticSubs] = useOptimistic(subs);

function handleClick() {
startTransition(async () => {
setOptimisticLike(true);
setOptimisticSubs(a => a + 1);
await saveChanges();
});