How to fix component does not remount when route parameters change with React Router?

Sometimes, we want to fix component does not remount when route parameters change with React Router.

In this article, we’ll look at how to fix component does not remount when route parameters change with React Router.

How to fix component does not remount when route parameters change with React Router?

To fix component does not remount when route parameters change with React Router, we should just watch the route parameter for changes.

For instance, we write

<Route
  render={(props) => <Component {...props} />}
  path="/project/:projectId/"
/>;

to add a route.

Then in our route component, we write

import React, { useEffect } from "react";
const Component = (props) => {
  useEffect(() => {
    props.getData();
  }, [props.match.params.projectId]);

  return (<div>Layout</div>);
}

export default Component;

to watch the props.match.params.projectId property, which has the projectId route parameter value.

If props.match.params.projectId changes, then we call props.getData to get the data again by running the useEffect hook callback again.

Conclusion

To fix component does not remount when route parameters change with React Router, we should just watch the route parameter for changes.