useActionState hook in react 19

m3cv1no

Majd Hemud

Posted on July 27, 2024

useActionState hook in react 19

React 19 is finally here! Bringing new features and APIs to the frontend world and for all React lovers. To create smoother, faster, and more efficient React apps.

In this Article we will talk about useActionState hook in React 19 😁

Note: The useActionState hook is currently only available in React’s Canary and experimental channels. Learn more about release channels here. In addition, you need to use a framework that supports React Server Components to get the full benefit of useActionState.

The useActionState hook

This is a new React hook that helps us update state based on the result of a form action.

In addition, the useActionState hook offers benefits such as:

  1. Simplified state management: Automatically updates state based on action results, and reducing boilerplate code.
  2. Enhanced user experience: Provides loading indicators and error handling for smoother interactions.
  3. Improved performance: Optimizes state updates and works seamlessly with React Server Components.

Example

import { useActionState } from 'react';

async function updateName(name) {
    await new Promise((resolve) => setTimeout(resolve, 4000));
    return name;
}

export default function UpdateNameForm() {
    const [name, updateNameAction, isPending] = useActionState(
        async (previousName, formData) => {
            const newName = await updateName(formData.get('name'));
            return result;
        },
        '',
    );
    return (
        <form action={updateNameAction}>
            Current Name is {name}
            <input name='name' />
            <button type='submit' disabled={isPending}>
                {isPending ? 'Updating...' : 'Update'}
            </button>
        </form>
    );
}
Enter fullscreen mode Exit fullscreen mode

In the example above:

  • First we imported the useActionState hook from the React library.

  • We defined an asynchronous function called updateName to update the name. It takes a name parameter. Inside the function we added a promise to simulate a delay of 4 seconds before resolving the promise. After that it returns the new name.

  • As well we defined a functional component named UpdateNameForm. Inside the component we used the useActionState hook to manage the component's state.

The useActionState hook returns an array with three values:

  1. name: The current name.

  2. updateNameAction: A function to trigger the form action and the subsequent state update.

  3. isPending: Is a boolean flag indicating whether the action is in progress.

  • The useActionState hook takes three arguments:
  1. fn: An asynchronous function that handles the form submission logic.

  2. initialState: The value you want the state to be initially. It can be any serializable value. This argument is ignored after the action is first invoked.

  3. optional permalink: Is a string representing a unique URL associated with the form. It's primarily used in progressive enhancement scenarios.

For example with Server-Side Rendering (SSR). If the JavaScript bundle hasn't loaded yet when a user submits the form, React will redirect the user to the specified permalink URL instead of the current page.

  • So for the first parameter in the useActionState hook. We added an asynchronous function and it takes two parameters:
  1. previousName: It's the previous state for the name.

  2. formData: Which includes the submitted data from the form.

  • And after we added the asynchronous function as a first parameter in the useActionState hook. Within this function we get the new name from the formData and update the name through the updateName function.

  • For the second parameter we added an empty string to be the initialState for the name.

  • And finally it returns the new name to update the state for the name.

📝 Things to Keep in Mind

  • Experimental Feature: useActionState is currently an experimental feature and its behavior might change in future React versions. Use it with caution and be prepared for potential API changes.

  • React Server Components (RSC): To fully leverage the benefits of useActionState, it's recommended to use it with React Server Components. This combination can significantly improve performance.

  • Error Handling: While useActionState simplifies state management, you'll still need to handle errors gracefully within your action function. Consider using try-catch blocks or returning error objects.

  • Optimistic Updates: You might want to implement optimistic updates to provide a better user experience. This involves updating the UI immediately after a form submission and then correcting it if necessary.

Conclusion

I hope you enjoyed reading the article. If you have any questions, thoughts, or just want to say hello, I'd be thrilled to hear from you. Here's how you can reach out:

Drop me an Email: majd.hemud@gmail.com

Follow me 🥰

Explore My Portfolio

If you want to see more of my work, don't forget to check out my portfolio website! There, you'll find a curated collection of my projects, creative endeavors, and a deeper dive into my skills and passions 🔥.

Whether you're looking for design inspiration, curious about my past projects, or just want to connect, my portfolio is the place to be.

Until next time peace ✌️🥰.

💖 💪 🙅 🚩
m3cv1no
Majd Hemud

Posted on July 27, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related