useActionState – A New Hook in React
React 19 introduces several new features, including useActionState, which simplifies handling asynchronous operations, especially within forms.
What is useActionState?
useActionState is a hook that updates a component’s state based on form action results. It is particularly useful for dynamically changing state in response to server data after form submission.
How Does It Work?
- Hook Declaration:
useActionState takes an asynchronous function and an initial state. This function is called with every form submission. const [state, formAction] = useActionState(async (prevState, formData) => { return { ...prevState, ...formData }; }, initialState);
- Usage in Component: The hook returns the current state and a new action for the form or button.
return ( <form action={formAction}> {/* Form elements */} </form> );
Example Usage
Consider a simple user form collecting a name and age, adding this data to a user list:
import { useActionState } from "react";
const UserForm = () => {
const [state, formAction] = useActionState(async (prevState, formData) => {
const name = formData.get("name");
const age = formData.get("age");
if (prevState.users.some(user => user.name === name)) {
return { ...prevState, error: "User already exists" };
}
return { users: [...prevState.users, { name, age }], error: null };
}, { users: [], error: null });
return (
<form action={formAction}>
<input type="text" name="name" placeholder="Name" />
<input type="text" name="age" placeholder="Age" />
<button type="submit">Add User</button>
{state.error && <div className="error">{state.error}</div>}
<ul>
{state.users.map(user => (
<li key={user.name}>{user.name} - {user.age}</li>
))}
</ul>
</form>
);
};
Benefits of Using useActionState
- Simplified State Management: Automates state updates based on action results.
- Interactive Forms: Forms become dynamic and responsive to action results without complex state management.
- Integration with React Server Components: Displays server action results before client-side JavaScript loads.
Summary
useActionState is a powerful tool in React 19, streamlining asynchronous operations management, especially for forms. For more details, visit the official React documentation.
Dodaj komentarz