InterviewHubPRO
Section Overview
Q321

Question 321 of 445

Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

72%
React & Modern Frontend (445 Qs)•Part 10: Modern React 18, React 19 & Next.js Patterns (317 - 353)

What are useFormState and useFormStatus hooks?

These hooks simplify form handling with Server Actions in React 19.

useFormState

Manages form state and handles server responses:

jsx
'use client'
import { useFormState } from 'react-dom';
import { loginAction } from './actions';

export default function LoginForm() {
const [state, formAction] = useFormState(loginAction, {
  errors: {},
  message: ''
});

return (
  <form action={formAction}>
    <input name="email" type="email" />
    {state.errors.email && <p>{state.errors.email}</p>}
    
    <input name="password" type="password" />
    {state.errors.password && <p>{state.errors.password}</p>}
    
    <button type="submit">Login</button>
    {state.message && <p>{state.message}</p>}
  </form>
);
}

useFormStatus

Get the pending state of parent form:

jsx
'use client'
import { useFormStatus } from 'react-dom';

function SubmitButton() {
const { pending, data, method, action } = useFormStatus();

return (
  <button type="submit" disabled={pending}>
    {pending ? 'Submitting...' : 'Submit'}
  </button>
);
}

// Must be used in a child component of <form>
export default function MyForm() {
return (
  <form action={serverAction}>
    <input name="email" />
    <SubmitButton />
  </form>
);
}

Combining Both

jsx
'use client'
import { useFormState, useFormStatus } from 'react-dom';

function SubmitButton() {
const { pending } = useFormStatus();
return (
  <button disabled={pending}>
    {pending ? '⏳ Saving...' : '💾 Save'}
  </button>
);
}

export default function EditProfile() {
const [state, formAction] = useFormState(updateProfile, null);

return (
  <form action={formAction}>
    <input name="name" defaultValue={user.name} />
    <input name="bio" defaultValue={user.bio} />
    <SubmitButton />
    {state?.success && <p>✅ Profile updated!</p>}
    {state?.error && <p>❌ {state.error}</p>}
  </form>
);
}

Key Points

  • useFormState: For managing server responses and errors
  • useFormStatus: For UI feedback during submission
  • useFormStatus must be used in a child component of the form
  • Works seamlessly with Server Actions