Categories
React Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *