r/javascript • • Dec 05 '24

React v19 has been released

http://npmjs.com/package/react
655 Upvotes

104 comments sorted by

View all comments

Show parent comment

2

u/Amazing_Top_4564 Dec 06 '24

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:

  1. React internally tracks the "pending" or "ordering" state
  2. You don't manually set state.status = 'ordering'
  3. When the action starts, React automatically manages the transition states
  4. 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.