React 19 Actions and useOptimistic
React 19 introduces Actions and the useOptimistic hook to simplify common patterns like handling form submissions and updating the UI while a request is still in progress.
1. React Actions
An Action is a function that can be used to handle data updates. It manages the lifecycle of the update, including pending states and error handling, automatically.
JavaScript
function UpdateName({ name, updateNameAction }) {
return (
<form action={updateNameAction}>
<input type="text" name="name" defaultValue={name} />
<button type="submit">Update</button>
</form>
);
} 2. useOptimistic Hook
The useOptimistic hook allows you to show a different state while an async action is underway. This is called "optimistic UI" because you assume the action will succeed and update the UI immediately.
JavaScript
import { useOptimistic } from 'react';
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(state, newMessage) => [...state, { text: newMessage, sending: true }]
);
async function formAction(formData) {
const message = formData.get('message');
addOptimisticMessage(message);
await sendMessage(message);
}
return (
<form action={formAction}>
{optimisticMessages.map((m, i) => (
<div key={i}>{m.text} {m.sending && '(Sending...)'}</div>
))}
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
);
} Benefits
- Simplified State Management: No more manually managing `isLoading` and `error` states for forms.
- Improved User Experience: Instant feedback makes the app feel faster.
- Native Integration: Works seamlessly with HTML forms and standard web APIs.
Note: These features require React 19 or higher. They are designed to work well with Server Components and modern data-fetching patterns.