How to use the useSubmit hook in the React Router
The useSubmit hook is part of the react-router-dom package that executes a request when a triggered submit() function is returned. It employs Submit Dispatcher for handling requests and utilizes the Cache to manage the data’s overall state effectively.
How does it work?
It uses the same process that <Form> uses internally that is used to submit a <Form> to the server (or some raw FormData), which is returned by a function.
Internally, communication with core systems is achieved through event emitters. Numerous helper hooks are returned, like onSubmitSuccess, onSubmitError, onSubmitFinished, and others, to aid in managing the request flow and lifecycle. This approach prevents overwhelming the base hook with callback logic, improving code readability, reducing code complexity, and promoting more organized code.
When do we use useSubmit ?
The useSubmit hook is used whenever we need to submit a form programmatically. For example, there are instances where we might want to save a user preferences form each time any field is modified.
This can also be useful if we wish to implement an automatic sign-out feature for users who have been inactive on the website for a particular duration. In this scenario, we define inactivity as the user not navigating to other pages for 5 minutes.
Note: This feature only works using a data router; see Picking a Router for further information.
Example
Here’s an example implementation of a useSubmit hook where we are saving the form data as soon as the user changes the input:
Explanation
In the App.js file:
Line 1: The necessary dependencies are imported:
useSubmitandFormfrom the"react-router-dom"package.Line 3: This line declares a function component called
SearchFieldthat will be exported as the default export of the module.Line 4: This line declares a variable called
submitand assigns the value returned from theuseSubmithook to it. It indicates that theuseSubmithook is being utilized in this component.Line 5: The
returnkeyword signals the start of the JSX (JavaScript XML) content that will be rendered by this component.Lines 6–11: These lines represents the opening of a
Formcomponent. It’s likely a custom component or one provided by a UI library that encapsulates form-related functionalities.Here an
onChangeevent handler for theFormcomponent is submitted. It is triggered whenever the form's content changes.When the form content changes,
console.log("Form changed:", event.currentTarget);logs a message to the console, indicating that the form has changed. It also logs theevent.currentTargetwhich is a reference to the form element.submit(event.currentTarget);calls thesubmitfunction that was assigned to thesubmitvariable. It passes theevent.currentTargetas an argument to thesubmitfunction, presumably to handle the form submission or further processing.
Lines 12–19: These lines contains an HTML input element of type
textwith thenameattribute set tosearchwhich allows users to input text. It includes anonChangeevent handler that logs a message to the console whenever the input value changes. This allows developers to monitor user input in real time. Additionally, there is abuttonelement with the type attribute set tosubmitwhich typically triggers form submission. However, to fully function, this input and button should be within a form element.
In the index.js file:
Lines 1–9: Import Statements:
The import statements that bring in specific functions and components from the
react-router-domlibrary. These includecreateBrowserRouter,createRoutesFromElements,Route, andRouterProvider. Additionally, it importsReactandReactDOMfrom their respective modules, as well as the mainAppcomponent from./App.
Lines 11–16: This sets up the routing configuration. It creates a router using
createBrowserRouterand defines a single route usingcreateRoutesFromElements. The route is associated with the path/and points to theAppcomponent. This means that when the application URL matches/, theAppcomponent will be rendered.
In the package.json file:
To use the React Router we need to add the dependency "react-router-dom":"^6.13.0". As the useSubmit hook was introduced in React Router v6.4.0, which was released on March 10, 2022.
Note: We need to be using React >= 16.8 in order to use any of the React-Router hooks!
Conclusion
Overall, the useSubmit hook provides a reusable way to handle form submission in React Router. It encapsulates the logic for form submission and navigation, making it easier to manage and maintain form functionality in your React applications.
Free Resources