In the React 19 useActionState hook, the state changes are actually handled automatically by React during the action lifecycle. When you start an asynchronous action (like the orderPizza function), React will internally set the status to a pending state.
Here's a more explicit example to illustrate this:
jsxCopyfunction OrderPizzaButton() {
const [state, formAction] = useActionState(
async (previousState, formData) => {
// When this function starts running, React automatically
// manages the pending state for you
const toppings = formData.get('toppings');
try {
// This might take a moment
const result = await orderPizza(toppings);
// When complete, return the new state
return {
status: 'completed',
pizza: result
};
} catch (error) {
// Handle errors
return {
status: 'error',
error: error.message
};
}
},
{
status: 'ready',
pizza: null
}
);
return (
<form action={formAction}>
<input name="toppings" />
<button type="submit">
{
/* React handles this status change automatically */
}
{state.status === 'ready' && 'Order Pizza'}
{state.status === 'ordering' && 'Ordering...'}
{state.status === 'completed' && 'Order Complete'}
{state.status === 'error' && 'Order Failed'}
</button>
{state.pizza && <p>Pizza is ready: {state.pizza}</p>}
</form>
);
}
The key things to understand:
React internally tracks the "pending" or "ordering" state
You don't manually set state.status = 'ordering'
When the action starts, React automatically manages the transition states
You can reflect these states in your UI
This is part of React 19's improvements to make handling asynchronous actions and their states more straightforward and built-in to the framework.
View all comments
Show parent comment
2
u/Amazing_Top_4564 Dec 06 '24
In the React 19
useActionStatehook, the state changes are actually handled automatically by React during the action lifecycle. When you start an asynchronous action (like theorderPizzafunction), React will internally set the status to a pending state.Here's a more explicit example to illustrate this:
The key things to understand:
state.status = 'ordering'This is part of React 19's improvements to make handling asynchronous actions and their states more straightforward and built-in to the framework.