#loading state for forms
1 messages · Page 1 of 1 (latest)
Hi @timid sundial. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To add a loading state for forms in a server component in Next.js, you have a few options:
-
Use the
loading.jsfile convention:
You can create aloading.jsfile in the same directory as your page component. This will automatically show a loading state while the form is being submitted and the new page is loading. Here's an example:// app/customize-posters/loading.tsx export default function Loading() { return <p>Loading...</p> }This approach provides an instant loading state for the entire route segment Loading UI and Streaming (https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming).
-
Use the
<Form>component from Next.js:
Next.js provides a<Form>component that extends the HTML<form>element to provide prefetching of loading UI and client-side navigation on submission. Here's how you can use it:import Form from 'next/form' export default function Page() { return ( <Form action="/customize-posters"> {/* Form fields */} <button type="submit">Submit</button> </Form> ) }You can then create a client component for the submit button that uses the
useFormStatushook to show a loading state:'use client' import { useFormStatus } from 'react-dom' export function SubmitButton() { const { pending } = useFormStatus() return ( <button type="submit" disabled={pending}> {pending ? 'Submitting...' : 'Submit'} </button> ) }This approach provides a more granular loading state for the form submission <Form> (https://nextjs.org/docs/app/api-reference/components/form#examples).
-
Use React Suspense:
You can wrap your form or specific parts of your UI in a Suspense boundary to show a loading state while data is being fetched or the form is being processed:import { Suspense } from 'react' import { FormComponent } from './components' export default function Page() { return ( <Suspense fallback={<p>Loading form...</p>}> <FormComponent /> </Suspense> ) }This approach allows you to show loading states for specific parts of your UI Server Components (https://nextjs.org/docs/app/building-your-application/rendering/server-components#streaming).