0 day streak
javascript / intermediate
Snippet

Enhancing UX with the useOptimistic Hook

The useOptimistic hook allows you to show a different state while an async action (like a Server Action) is underway. This makes the UI feel significantly faster by not waiting for the server response to update the list.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'use client';
import { useOptimistic } from 'react';
function TodoList({ todos }) {
const [optimisticTodos, addOptimisticTodo] = useOptimistic(todos, (state, newTodo) => [...state, { text: newTodo, sending: true }]);
return (
<form action={async (formData) => {
const text = formData.get('text');
addOptimisticTodo(text);
await createTodo(text);
}}>
{optimisticTodos.map(todo => <li key={todo.text}>{todo.text} {todo.sending && '(...)'}</li>)}
</form>
);
}
nextjs
Breakdown
1
const [optimisticTodos, addOptimisticTodo] = useOptimistic(...)
Initializes the optimistic state with the original data and a reducer-like function.
2
addOptimisticTodo(text)
Immediately updates the UI with the temporary state before the server request starts.
3
await createTodo(text)
The actual server request; once finished, the optimistic state is automatically replaced by the real data.