useactionstate a new hook in react

useActionState A NEW HOOK IN REACT

useActionState – A new hook in React JS

In this article, we will explain the use case of a new and very useful hook in React JS called useActionState.

What is useActionState ?

useActionState is a newly introduced React hook that will help developers to manage the form state. UseActionState will allow to update the state based on the result of a form action.

It’s a useful form state helper that memorizes things for us and can change them when we submit a form.

Checkout useActionState official documentation

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.

How to use useActionState?

To use useActionState, we have to import useActionState from React package as we have done below

import { useActionState } from "react";

Then we can use it in our project component wherever it is required

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

useActionState returns an array with two items

  • state: it is a current form state
  • formAction: it’s an action callback function that will be binded with the form submit event

useActionState takes two arguments

  • actionFunction: it’s a function that runs while user submit the function and return new form state
  • intialState: It’s a initial form state

When to use useActionState?

We should use this hooks useActionState when we have a use case to update the state on form submission

Example

Let’s implement a simple counter example using ‘useActionState a new hook in React’

import { useActionState } from "react";

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

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

Conclusion

We have covered the use case of this new hook useActionState in this article.
When useActionState will be available in stable version and then we should give it a try in your projects and see how it can help us to improve your forms!

Leave a Comment

Your email address will not be published. Required fields are marked *