useFetcher
In HTML/HTTP, data mutations and loads are modeled with navigation: <a href>
and <form action>
. Both cause a navigation in the browser. The React Router equivalents are <Link>
and <Form>
.
But sometimes you want to call a loader
outside of navigation, or call an action
(and get the data on the page to revalidate) without changing the URL. Or you need to have multiple mutations in-flight at the same time.
Many interactions with the server aren't navigation events. This hook lets you plug your UI into your actions and loaders without navigating.
This is useful when you need to:
- fetch data not associated with UI routes (popovers, dynamic forms, etc.)
- submit data to actions without navigating (shared components like a newsletter sign ups)
- handle multiple concurrent submissions in a list (typical "todo app" list where you can click multiple buttons and all should be pending at the same time)
- infinite scroll containers
- and more!
If you're building a highly interactive, "app like" user interface, you will useFetcher
often.
import { useFetcher } from "react-router-dom";
function SomeComponent() {
const fetcher = useFetcher();
// call submit or load in a useEffect
React.useEffect(() => {
fetcher.submit(data, options);
fetcher.load(href);
}, [fetcher]);
// build your UI with these properties
fetcher.state;
fetcher.formData;
fetcher.json;
fetcher.text;
fetcher.formMethod;
fetcher.formAction;
fetcher.data;
// render a form that doesn't cause navigation
return <fetcher.Form />;
}
Fetchers have a lot of built-in behavior:
- Automatically handles cancellation on interruptions of the fetch
- When submitting with POST, PUT, PATCH, DELETE, the action is called first
- After the action completes, the data on the page is revalidated to capture any mutations that may have happened, automatically keeping your UI in sync with your server state
- When multiple fetchers are inflight at once, it will
- commit the freshest available data as they each land
- ensure no stale loads override fresher data, no matter which order the responses return
- Handles uncaught errors by rendering the nearest
errorElement
(just like a normal navigation from<Link>
or<Form>
) - Will redirect the app if your action/loader being called returns a redirect (just like a normal navigation from
<Link>
or<Form>
)