useOptimistic·续

return <FollowButton user={user} followAction={followAction} />; }


```js src/FollowButton.js active
import { useOptimistic, startTransition } from 'react';

export default function FollowButton({ user, followAction }) {
  const [optimisticState, updateOptimistic] = useOptimistic(
    { isFollowing: user.isFollowing, followerCount: user.followerCount },
    (current, isFollowing) => ({
      isFollowing,
      followerCount: current.followerCount + (isFollowing ? 1 : -1)
    })
  );

function handleClick() {
    const newFollowState = !optimisticState.isFollowing;
    startTransition(async () => {
      updateOptimistic(newFollowState);
      await followAction(newFollowState);
    });
  }

return (
    &lt;div>
      &lt;p>&lt;strong>{user.name}&lt;/strong>&lt;/p>
      &lt;p>{optimisticState.followerCount} followers&lt;/p>
      &lt;button onClick={handleClick}>
        {optimisticState.isFollowing ? 'Unfollow' : 'Follow'}
      &lt;/button>
    &lt;/div>
  );
}

```js src/actions.js hidden export async function followUser(name) { await new Promise((res) => setTimeout(res, 1000)); }

export async function unfollowUser(name) { await new Promise((res) => setTimeout(res, 1000)); }


The reducer receives the new `isFollowing` value and calculates both the new follow state and the updated follower count in a single update. This ensures the button text and count always stay in sync.

> [!INFO]
>
> #### Choosing between updaters and reducers 
>
> `useOptimistic` supports two patterns for calculating state based on current state:
>
> **Updater functions** work like [useState updaters](/reference/react/useState#updating-state-based-on-the-previous-state). Pass a function to the setter:
>
```js
const [optimistic, setOptimistic] = useOptimistic(value);
setOptimistic(current => !current);

Reducers separate the update logic from the setter call:

const [optimistic, dispatch] = useOptimistic(value, (current, action) => {
  // Calculate next state based on current and action
});
dispatch(action);

Use updaters for calculations where the setter call naturally describes the update. This is similar to using setState(prev => ...) with useState.

Use reducers when you need to pass data to the update (like which item to add) or when handling multiple types of updates with a single hook.

Why use a reducer?

Reducers are essential when the base state might change while your Transition is pending. If todos changes while your add is pending (for example, another user added a todo), React will re-run your reducer with the new todos to recalculate what to show. This ensures your new todo is added to the latest list, not an outdated copy.

An updater function like setOptimistic(prev => [...prev, newItem]) would only see the state from when the Transition started, missing any updates that happened during the async work.


Optimistically adding to a list

When you need to optimistically add items to a list, use a reducer:

```js src/App.js import { useState, startTransition } from 'react'; import { addTodo } from './actions.js'; import TodoList from './TodoList';

export default function App() { const [todos, setTodos] = useState([ { id: 1, text: 'Learn React' } ]);

async function addTodoAction(newTodo) { const savedTodo = await addTodo(newTodo); startTransition(() => { setTodos(todos => [...todos, savedTodo]); }); }

return <TodoList todos={todos} addTodoAction={addTodoAction} />; }


```js src/TodoList.js active
import { useOptimistic, startTransition } from 'react';

export default function TodoList({ todos, addTodoAction }) {
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(
    todos,
    (currentTodos, newTodo) => [
      ...currentTodos,
      { id: newTodo.id, text: newTodo.text, pending: true }
    ]
  );

function handleAddTodo(text) {
    const newTodo = { id: crypto.randomUUID(), text: text };
    startTransition(async () => {
      addOptimisticTodo(newTodo);
      await addTodoAction(newTodo);
    });
  }

return (
    &lt;div>
      &lt;button onClick={() => handleAddTodo('New todo')}>Add Todo&lt;/button>
      &lt;ul>
        {optimisticTodos.map(todo => (
          &lt;li key={todo.id}>
            {todo.text} {todo.pending && "(Adding...)"}
          &lt;/li>
        ))}
      &lt;/ul>
    &lt;/div>
  );
}

```js src/actions.js hidden export async function addTodo(todo) { await new Promise((res) => setTimeout(res, 1000)); // In a real app, this would save to the server return { ...todo, pending: false }; }


The `reducer` receives the current list of todos and the new todo to add. This is important because if the `todos` prop changes while your add is pending (for example, another user added a todo), React will update your optimistic state by re-running the reducer with the updated list. This ensures your new todo is added to the latest list, not an outdated copy.

> [!NOTE]
>
> Each optimistic item includes a `pending: true` flag so you can show loading state for individual items. When the server responds and the parent updates the canonical `todos` list with the saved item, the optimistic state updates to the confirmed item without the pending flag.
>

---

### Handling multiple `action` types

When you need to handle multiple types of optimistic updates (like adding and removing items), use a reducer pattern with `action` objects.

This shopping cart example shows how to handle add and remove with a single reducer:

```js src/App.js
import { useState, startTransition } from 'react';
import { addToCart, removeFromCart, updateQuantity } from './actions.js';
import ShoppingCart from './ShoppingCart';

export default function App() {
  const [cart, setCart] = useState([]);

const cartActions = {
    async add(item) {
      await addToCart(item);
      startTransition(() => {
        setCart(current => {
          const exists = current.find(i => i.id === item.id);
          if (exists) {
            return current.map(i =>
              i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i
            );
          }
          return [...current, { ...item, quantity: 1 }];
        });
      });
    },
    async remove(id) {
      await removeFromCart(id);
      startTransition(() => {
        setCart(current => current.filter(item => item.id !== id));
      });
    },
    async updateQuantity(id, quantity) {
      await updateQuantity(id, quantity);
      startTransition(() => {
        setCart(current =>
          current.map(item =>
            item.id === id ? { ...item, quantity } : item
          )
        );
      });
    }
  };

return &lt;ShoppingCart cart={cart} cartActions={cartActions} />;
}

```js src/ShoppingCart.js active import { useOptimistic, startTransition } from 'react';

export default function ShoppingCart({ cart, cartActions }) { const [optimisticCart, dispatch] = useOptimistic( cart, (currentCart, action) => { switch (action.type) { case 'add': const exists = currentCart.find(item => item.id === action.item.id); if (exists) { return currentCart.map(item => item.id === action.item.id ? { ...item, quantity: item.quantity + 1, pending: true } : item ); } return [...currentCart, { ...action.item, quantity: 1, pending: true }]; case 'remove': return currentCart.filter(item => item.id !== action.id); case 'update_quantity': return currentCart.map(item => item.id === action.id ? { ...item, quantity: action.quantity, pending: true } : item ); default: return currentCart; } } );

function handleAdd(item) { startTransition(async () => { dispatch({ type: 'add', item }); await cartActions.add(item); }); }

function handleRemove(id) { startTransition(async () => { dispatch({ type: 'remove', id }); await cartActions.remove(id); }); }

function handleUpdateQuantity(id, quantity) { startTransition(async () => { dispatch({ type: 'update_quantity', id, quantity }); await cartActions.updateQuantity(id, quantity); }); }

const total = optimisticCart.reduce( (sum, item) => sum + item.price * item.quantity, 0 );

return ( <div> <h2>Shopping Cart</h2> <div style={{ marginBottom: 16 }}> <button onClick={() => handleAdd({ id: 1, name: 'T-Shirt', price: 25 })}> Add T-Shirt ($25) </button>{' '} <button onClick={() => handleAdd({ id: 2, name: 'Mug', price: 15 })}> Add Mug ($15) </button> </div> {optimisticCart.length === 0 ? ( <p>Your cart is empty</p> ) : ( <ul> {optimisticCart.map(item => ( <li key={item.id}> {item.name} - ${item.price} × {item.quantity} {' '}= ${item.price * item.quantity} <button onClick={() => handleRemove(item.id)} style={{ marginLeft: 8 }} > Remove </button> {item.pending && ' ...'} </li> ))} </ul> )} <p><strong>Total: ${total}</strong></p> </div> ); }


```js src/actions.js hidden
export async function addToCart(item) {
  await new Promise((res) => setTimeout(res, 800));
}

export async function removeFromCart(id) {
  await new Promise((res) => setTimeout(res, 800));
}

export async function updateQuantity(id, quantity) {
  await new Promise((res) => setTimeout(res, 800));
}

The reducer handles three action types (add, remove, update_quantity) and returns the new optimistic state for each. Each action sets a pending: true flag so you can show visual feedback while the Server Function runs.


Optimistic delete with error recovery

When deleting items optimistically, you should handle the case where the Action fails.

This example shows how to display an error message when a delete fails, and the UI automatically rolls back to show the item again.

```js src/App.js import { useState, startTransition } from 'react'; import { deleteItem } from './actions.js'; import ItemList from './ItemList';

export default function App() { const [items, setItems] = useState([ { id: 1, name: 'Learn React' }, { id: 2, name: 'Build an app' }, { id: 3, name: 'Deploy to production' }, ]);

async function deleteAction(id) { await deleteItem(id); startTransition(() => { setItems(current => current.filter(item => item.id !== id)); }); }

return <ItemList items={items} deleteAction={deleteAction} />; }


```js src/ItemList.js active
import { useState, useOptimistic, startTransition } from 'react';

export default function ItemList({ items, deleteAction }) {
  const [error, setError] = useState(null);
  const [optimisticItems, removeItem] = useOptimistic(
    items,
    (currentItems, idToRemove) =>
      currentItems.map(item =>
        item.id === idToRemove
          ? { ...item, deleting: true }
          : item
      )
  );

function handleDelete(id) {
    setError(null);
    startTransition(async () => {
      removeItem(id);
      try {
        await deleteAction(id);
      } catch (e) {
        setError(e.message);
      }
    });
  }

return (
    &lt;div>
      &lt;h2>Your Items&lt;/h2>
      &lt;ul>
        {optimisticItems.map(item => (
          &lt;li
            key={item.id}
            style={{
              opacity: item.deleting ? 0.5 : 1,
              textDecoration: item.deleting ? 'line-through' : 'none',
              transition: 'opacity 0.2s'
            }}
          >
            {item.name}
            &lt;button
              onClick={() => handleDelete(item.id)}
              disabled={item.deleting}
              style={{ marginLeft: 8 }}
            >
              {item.deleting ? 'Deleting...' : 'Delete'}
            &lt;/button>
          &lt;/li>
        ))}
      &lt;/ul>
      {error && (
        &lt;p style={{ color: 'red', padding: 8, background: '#fee' }}>
          {error}
        &lt;/p>
      )}
    &lt;/div>
  );
}

```js src/actions.js hidden export async function deleteItem(id) { await new Promise((res) => setTimeout(res, 1000)); // Item 3 always fails to demonstrate error recovery if (id === 3) { throw new Error('Cannot delete. Permission denied.'); } }


Try deleting 'Deploy to production'. When the delete fails, the item automatically reappears in the list.

---

## Troubleshooting

### I'm getting an error: "An optimistic state update occurred outside a Transition or Action"

You may see this error:

An optimistic state update occurred outside a Transition or Action. To fix, move the update to an Action, or wrap with `startTransition`.

The optimistic setter function must be called inside `startTransition`:

```js
// 🚩 Incorrect: outside a Transition
function handleClick() {
  setOptimistic(newValue);  // Warning!
  // ...
}

// ✅ Correct: inside a Transition
function handleClick() {
  startTransition(async () => {
    setOptimistic(newValue);
    // ...
  });
}

// ✅ Also correct: inside an Action prop
function submitAction(formData) {
  setOptimistic(newValue);
  // ...
}

When you call the setter outside an Action, the optimistic state will briefly appear and then immediately revert back to the original value. This happens because there's no Transition to "hold" the optimistic state while your Action runs.

I'm getting an error: "Cannot update optimistic state while rendering"

You may see this error:

Cannot update optimistic state while rendering.

This error occurs when you call the optimistic setter during the render phase of a component. You can only call it from event handlers, effects, or other callbacks:

// 🚩 Incorrect: calling during render
function MyComponent({ items }) {
  const [isPending, setPending] = useOptimistic(false);

// This runs during render - not allowed!
  setPending(true);

// ...
}

// ✅ Correct: calling inside startTransition
function MyComponent({ items }) {
  const [isPending, setPending] = useOptimistic(false);

function handleClick() {
    startTransition(() => {
      setPending(true);
      // ...
    });
  }

// ...
}

// ✅ Also correct: calling from an Action
function MyComponent({ items }) {
  const [isPending, setPending] = useOptimistic(false);

function action() {
    setPending(true);
    // ...
  }

// ...
}

My optimistic updates show stale values

If your optimistic state seems to be based on old data, consider using an updater function or reducer to calculate the optimistic state relative to the current state.

// May show stale data if state changes during Action
const [optimistic, setOptimistic] = useOptimistic(count);
setOptimistic(5);  // Always sets to 5, even if count changed

// Better: relative updates handle state changes correctly
const [optimistic, adjust] = useOptimistic(count, (current, delta) => current + delta);
adjust(1);  // Always adds 1 to whatever the current count is

See Updating state based on the current state for details.

I don't know if my optimistic update is pending

To know when useOptimistic is pending, you have three options:

  1. Check if optimisticValue === value
const [optimistic, setOptimistic] = useOptimistic(value);
const isPending = optimistic !== value;

If the values are not equal, there's a Transition in progress.

  1. Add a useTransition
const [isPending, startTransition] = useTransition();
const [optimistic, setOptimistic] = useOptimistic(value);

//...
startTransition(() => {
  setOptimistic(state);
})

Since useTransition uses useOptimistic for isPending under the hood, this is equivalent to option 1.

  1. Add a pending flag in your reducer
const [optimistic, addOptimistic] = useOptimistic(
  items,
  (state, newItem) => [...state, { ...newItem, isPending: true }]
);

Since each optimistic item has its own flag, you can show loading state for individual items.


Sitemap

Overview of all docs pages