Beginner LevelReact JS & React 19
How does the new useActionState hook in React 19 handle form submissions and pending states?
❓ Interview Prompt: Explain React 19 `useActionState`, handling form actions, pending states (`isPending`), and optimistic state updates.
React 19 introduces 'useActionState' (replacing 'useFormState'), a native hook designed to streamline form actions and async state mutations:
Syntax:
'const [state, formAction, isPending] = useActionState(fn, initialState);'
Features:
•
Automatically tracks 'isPending' status while async form submission runs.
•
Automatically captures returned state or error objects from Server Actions / Async Actions.
Code Implementation Example
jsx
import { useActionState } from 'react';
async function updateNameAction(previousState, formData) {
const name = formData.get('name');
const res = await api.updateUser({ name });
return res.success ? { name } : { error: 'Failed to update' };
}
function ProfileForm() {
const [state, formAction, isPending] = useActionState(updateNameAction, { name: 'Alice' });
return (
<form action={formAction}>
<input name="name" defaultValue={state.name} />
<button type="submit" disabled={isPending}>
{isPending ? 'Saving...' : 'Save'}
</button>
{state.error && <p className="error">{state.error}</p>}
</form>
);
}💡Managing form submission and pending states in React 19 with useActionState.
🎯 Interview Key Takeaway
useActionState in React 19 simplifies form action handlers by providing state and pending status out-of-the-box.
#React 19#useActionState#Forms#Actions#Beginner
Back to all React JS & React 19 Questions→