How to fetch data or update state when a route changes in React Router

Short answer

Use React's componentDidUpdate method.

Long answer

componentDidUpdate is the right place to make some API requests, or update the state of a component depending on the url route.

In this method, you can compare the previous location and the new location and if they don't match, perform a certain operation.

Code example

class MyComponent extends React.Component {

    componentDidUpdate(prevProps, prevState, snapshot) {

        if (this.props.location !== prevProps.location) {
            // do something ...
            // this.setState
        }
    }
}

In this example, the if condition runs when either the path or the search paramter changes.

Compare location.pathname if you want to do something only when the path changes.

And compare location.search if you want to do something only when the search (query string) changes.

Coda

I was working on a side project when I encountered this problem. I couldn't find a straight-forward solution even after searching for hours. Most of the solutions were outdated.

This post is my effor to make it a little easier for people to find a working solution.