useActionState — A New Hook in React 🎉
Random

Random @random_ti

About: I'm a self-taught Web developer who is always learning and creating cool Project stuffs.

Location:
India
Joined:
Oct 25, 2023

useActionState — A New Hook in React 🎉

Publish Date: Jul 2 '24
210 26

Hello Developers 👋,

It’s me your friend Md Taqui Imam, and today I’m going to explain a new and exciting hook in React called useActionState.

Follow me in Github⭐

What is useActionState?

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

It’s like a smart helper that remembers things for us and can change them when we submit a form.

Checkout Official Documentation🚀

Important Note: Right now, useActionState is only available in React’s Canary and experimental channels. To get the most out of it, you’ll need to use a framework that supports React Server Components.

How to use useActionState?

To use this hook, we first need to import it from React:

import { useActionState } from 'react';
Then, we can use it in our component like this:



const [state, formAction, isPending] = useActionState(actionFunction, initialState);


Enter fullscreen mode Exit fullscreen mode

Here’s what each part means:

‘state’ is our current form state
‘formAction’ is a new action we’ll use in our form
‘actionFunction’ is the function that runs when the form is submitted
‘initialState’ is the starting value of our state

When to use useActionState:

Use this hook when you want to update state based on form submissions, especially if you’re using Server Components and want quicker responses.

Example:

Let’s make a simple counter form using useActionState:



import { useActionState } from "react";

async function increment(previousState, formData) {
  return previousState + 1;
}

function StatefulForm() {
  const [state, formAction] = useActionState(increment, 0);
  return (
    <form>
      {state}
      <button formAction={formAction}>Increment</button>
    </form>
  );
}


Enter fullscreen mode Exit fullscreen mode

In this example, every time we click the button, our count goes up by one. The useActionState hook takes care of updating the state when the form is submitted.

For More Detail and example checkout this video 👇

That’s it 😅

Remember, the best way to learn is by doing.

So when useActionState becomes more widely available, give it a try in your projects and see how it can improve your forms!

Alert ⚠️

Don't forget to checkout my new article 🫡

nextjs

Click Here👋

...

Happy coding!


github

twitter

portfolio

buymeacoffee

Comments 26 total

  • Devluc
    DevlucJul 2, 2024

    Great article Taqui. I enjoyed learning from it

    • Random
      RandomJul 2, 2024

      Thanks Lucian 👏

  • gopal keshri hb
    gopal keshri hbJul 2, 2024
    get your code
    
    Enter fullscreen mode Exit fullscreen mode
  • Syed Muhammad Ali Raza
    Syed Muhammad Ali RazaJul 2, 2024

    Thanks for Sharing

    • Random
      RandomJul 2, 2024

      Happy to hear you liked it 🥰

  • Phoenix
    PhoenixJul 2, 2024

    what is the major difference between this and useTransition????

  • Muhammad Hasanudin
    Muhammad HasanudinJul 3, 2024

    nice share 😃👍🏻

    • Random
      RandomJul 3, 2024

      Happy to hear that you liked it 😊

  • Adesoji1
    Adesoji1Jul 3, 2024

    What's the difference between useactionstate and use effect

    • Random
      RandomJul 3, 2024

      Both useActionState and useEffect are hooks in React, but they serve different purposes and are used in different scenarios

      • JoelBonetR 🥇
        JoelBonetR 🥇Jul 3, 2024

        Just like salt and mackerel. They both are edible "things" used in different scenarios 😅

        What I really meant is...

        AI generated response

        that we should get back the "get a life" trend but with people that use AI for everything while trying to hide it. Stop it. It's sad. If that wasn't enough its even more easy to spot AI generated text than it is to spot SEO directed content written by humans.

        • Amrin
          AmrinJul 3, 2024

          😂😂 too good

    • Digvijay25182316
      Digvijay25182316Jul 4, 2024

      useActionState : For Form Mutations.
      useEffect : lifecycle hook to control components state

  • Justyn Clark
    Justyn ClarkJul 3, 2024

    Funny how everything is trying to catch up to Remix.run / React Router 7.

    This is old news 😂

  • Mummy Miracle
    Mummy MiracleJul 3, 2024

    After giving about 3000 job opportunities world wide , our agency is still giving out Jobs and Business loans worldwide.

    if you need a job or financial aid kindly contact us now via email : shalomagency247@outlook.com

    Thanks.

  • Sebastian Fritsch
    Sebastian FritschJul 3, 2024

    It is definitely nice to use server actions and useActionState, but I still like more control over validation and still prefer Formik + Yup combo. To be honest, the end user doesn't care at the end and cannot tell the difference 👨🏼‍💻

    • Random
      RandomJul 3, 2024

      Thanks for you suggestions 🫡

  • José Pablo Ramírez Vargas
    José Pablo Ramírez VargasJul 3, 2024

    So React keeps on piling up things on top of things. Poor React devs, having to keep up with this hot mess.

  • АнонимJul 4, 2024

    [deleted]

  • Shaogat Alam
    Shaogat AlamJul 8, 2024

    Interesting topic! Everything is explained articulately and clearly. For your project, consider checking out this free npm package: select-paginated.

  • Vaggelis Magonezos
    Vaggelis MagonezosAug 30, 2024

    I cant get the message from useActionState to return the server action value, see example

    server file :

    "use server";
    const someServerAction = async (prevState,formData) => {
      try {
        return "success";
      } catch (error) {
        return "error";
      }
    };
    
    Enter fullscreen mode Exit fullscreen mode

    client file :

    "use client"
    const SomeClientComponent = () => {
      const [message, formAction, isPending] = useActionState(
        someServerAction,
        "initial"
      );
    
      console.log(message)
    
    // i get the initial string as defined in the hook, but after form submission, the message becomes undefined where it should log "success" - what am i missing ??
    
      return (
        <form
          action={formAction}
          className="space-y-6"
        >
    
    ..rest is irrelevant
    
    Enter fullscreen mode Exit fullscreen mode
Add comment