How to wait for an async action before route transition with React Router?

Estimated read time 2 min read

To wait for an asynchronous action to complete before transitioning to a new route with React Router, you can use the history object to manually navigate to the new route after the action has completed. Here’s an example code snippet that demonstrates how to wait for an async action before route transition with React Router:

import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';

function MyComponent() {
  const [isLoading, setIsLoading] = useState(false);
  const history = useHistory();

  const handleClick = async () => {
    try {
      // Perform async action here
      await fetch('');
      // Navigate to new route after action has completed
    } catch (error) {
    } finally {

  return (
      <button onClick={handleClick} disabled={isLoading}>
        {isLoading ? 'Loading...' : 'Submit'}

export default MyComponent;

In this example, we define a functional component named “MyComponent” that includes a button that triggers an async action when clicked. We use the useState hook to create a state variable for the loading state, and the useHistory hook from React Router to access the history object.

We define a function named handleClick that is called when the button is clicked. This function sets the loading state to true, performs the async action (in this case, a fetch request to a dummy API), and navigates to the new route (/new-route) after the action has completed using the history.push() method. We use a try-catch block to handle errors and a finally block to set the loading state back to false.

In the JSX code, we bind the onClick event to the handleClick function and disable the button when the loading state is true.

By manually navigating to the new route after the async action has completed, we can ensure that the action has finished before transitioning to the new page.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply