useSubmit

This hook is simply a re-export of React Router’s useSubmit.

Returns the function that may be used to submit a <form> (or some raw FormData) to the server using the same process that <Form> uses internally onSubmit. If you’re familiar with React Router’s useNavigate, you can think about this as the same thing but for <Form> instead of <Link>.

This is useful whenever you need to programmatically submit a form. For example, you may wish to save a user preferences form whenever any field changes.

  1. import type { ActionArgs } from "@remix-run/node"; // or cloudflare/deno
  2. import { json } from "@remix-run/node"; // or cloudflare/deno
  3. import { useSubmit, useNavigation } from "@remix-run/react";
  4. export async function loader() {
  5. return json(await getUserPreferences());
  6. }
  7. export async function action({ request }: ActionArgs) {
  8. await updatePreferences(await request.formData());
  9. return redirect("/prefs");
  10. }
  11. function UserPreferences() {
  12. const submit = useSubmit();
  13. const navigation = useNavigation();
  14. function handleChange(event) {
  15. submit(event.currentTarget, { replace: true });
  16. }
  17. return (
  18. <Form method="post" onChange={handleChange}>
  19. <label>
  20. <input type="checkbox" name="darkMode" value="on" />{" "}
  21. Dark Mode
  22. </label>
  23. {navigation.state === "submitting" ? (
  24. <p>Saving...</p>
  25. ) : null}
  26. </Form>
  27. );
  28. }

This can also be useful if you’d like to automatically sign someone out of your website after a period of inactivity. In this case, we’ve defined inactivity as the user hasn’t navigated to any other pages after 5 minutes.

  1. import { useSubmit, useNavigation } from "@remix-run/react";
  2. import { useEffect } from "react";
  3. function AdminPage() {
  4. useSessionTimeout();
  5. return <div>{/* ... */}</div>;
  6. }
  7. function useSessionTimeout() {
  8. const submit = useSubmit();
  9. const navigation = useNavigation();
  10. useEffect(() => {
  11. const timer = setTimeout(() => {
  12. submit(null, { method: "post", action: "/logout" });
  13. }, 5 * 60_000);
  14. return () => clearTimeout(timer);
  15. }, [submit, navigation]);
  16. }

For more information and usage, please refer to the React Router useSubmit docs.