Component does not remount when route parameters change
Asked Answered
L

14

124

I'm working on a react application using react-router. I have a project page that has a url as follows:

myapplication.com/project/unique-project-id

When the project component loads, I trigger a data request for that project from the componentDidMount event. I'm now running into an issue where if I switch directly between two projects so only the id changes like this...

myapplication.com/project/982378632
myapplication.com/project/782387223
myapplication.com/project/198731289

componentDidMount is not triggered again so the data is not refreshed. Is there another lifecycle event I should be using to trigger my data request or a different strategy to tackle this issue?

Lowermost answered 28/8, 2015 at 0:16 Comment(2)
Could you post your components code ?Freestyle
Good article might relates to question nikgraf.com/blog/…Postmortem
B
90

If the link is directing to the same route with just a different param, it's not remounting, but instead receiving new props. So, you could use the componentWillReceiveProps(newProps) function and look for newProps.params.projectId.

If you're trying to load data, I would recommend fetching the data on before the router handles the match using static methods on the component. Check out this example. React Router Mega Demo. That way, the component would load the data and automatically update when the route params change without needing to rely on componentWillReceiveProps.

Bipartisan answered 28/8, 2015 at 12:13 Comment(8)
Thank you. I was able to get this working using componentWillReceiveProps. I still don't really understand the React Router Mega Demo data flow. I see the static fetchData defined on some components. How are these statics getting called from the router client side?Lowermost
Great question. Check out the client.js file and the server.js file. During the router's runcycle they call the fetchData.js file and pass the state to it. It's a little confusing at first but then becomes a little clearer.Bipartisan
Coming to this some months later, and being very inexperienced, I am having difficulty updating the examples with the changes to react-router with release of 1.0 - is it still possible now that Router.run has been replaced with render(<Router>{routes}</router>}, el) - can we still do the fetching before the router handles the match?Wellestablished
Yes, you would do it inside the match. I made an example once here: github.com/bradbumbalough/react-0.14-iso-test. Check out the src/server.jsx file.Bipartisan
FYI: "componentWillReceiveProps" considered legacyHexateuch
You should use ComponentDidUpdate with React 16 since componentWillReceiveProps is deprecatedMiddlings
This works but has the problem that you need to add componentWillReceiveProps() or componentDidUpdate() for handling re-renders to every component that is loading data. For example think about a page that has several components that are loading data based on same path parameter.Arliearliene
@PatoLoco that's exactly what I needed - I didn't need to remount or push a new route after all, I just had to check the :parameter value in ComponentDidUpdateMyrt
S
123

If you do need a component remount when route changes, you can pass a unique key to your component's key attribute (the key is associated with your path/route). So every time the route changes, the key will also change which triggers React component to unmount/remount. I got the idea from this answer

Sava answered 25/8, 2016 at 16:33 Comment(5)
Just asking, won't this be affecting the performance of the app?Peruzzi
@AlpitAnand this is a broad question. Re-mounting is definitely slower than re-rendering as it triggers more lifecycle methods. Here I'm just answering how to make remount happen when route changes.Sava
But its not a huge impact ? Whats your advice can we use it safely without much effect ?Peruzzi
@AlpitAnand Your question is too broad and application specific. For some applications, yes, it would be a performance hit, in which case you should watch props changing yourself and update only the elements that should update. For most though, the above is a good solutionArronarrondissement
this does not work, produce render loop infinite with erros, maybe for very light componentes works, it's not my caseVergos
Y
107

Here is my answer, similar to some of the above but with code.

<Route path="/page/:pageid" render={(props) => (
  <Page key={props.match.params.pageid} {...props} />)
} />
Ynez answered 23/3, 2018 at 3:16 Comment(3)
The key here plays the biggest role ,because image that you have Link to in a profile page ,upon click it just redirect to the same route ,but with different parameters ,BUT the component doesnt update ,because React can't find a difference ,because there must be a KEY to compare the old resultFarrell
This is a graet answer - has saved me from componentDidUpdate hell ;)Enochenol
The best answer, because update the comp only when changes :pageid param.Amberjack
B
90

If the link is directing to the same route with just a different param, it's not remounting, but instead receiving new props. So, you could use the componentWillReceiveProps(newProps) function and look for newProps.params.projectId.

If you're trying to load data, I would recommend fetching the data on before the router handles the match using static methods on the component. Check out this example. React Router Mega Demo. That way, the component would load the data and automatically update when the route params change without needing to rely on componentWillReceiveProps.

Bipartisan answered 28/8, 2015 at 12:13 Comment(8)
Thank you. I was able to get this working using componentWillReceiveProps. I still don't really understand the React Router Mega Demo data flow. I see the static fetchData defined on some components. How are these statics getting called from the router client side?Lowermost
Great question. Check out the client.js file and the server.js file. During the router's runcycle they call the fetchData.js file and pass the state to it. It's a little confusing at first but then becomes a little clearer.Bipartisan
Coming to this some months later, and being very inexperienced, I am having difficulty updating the examples with the changes to react-router with release of 1.0 - is it still possible now that Router.run has been replaced with render(<Router>{routes}</router>}, el) - can we still do the fetching before the router handles the match?Wellestablished
Yes, you would do it inside the match. I made an example once here: github.com/bradbumbalough/react-0.14-iso-test. Check out the src/server.jsx file.Bipartisan
FYI: "componentWillReceiveProps" considered legacyHexateuch
You should use ComponentDidUpdate with React 16 since componentWillReceiveProps is deprecatedMiddlings
This works but has the problem that you need to add componentWillReceiveProps() or componentDidUpdate() for handling re-renders to every component that is loading data. For example think about a page that has several components that are loading data based on same path parameter.Arliearliene
@PatoLoco that's exactly what I needed - I didn't need to remount or push a new route after all, I just had to check the :parameter value in ComponentDidUpdateMyrt
R
15

You have to be clear, that a route change will not cause a page refresh, you have to handle it yourself.

import theThingsYouNeed from './whereYouFindThem'

export default class Project extends React.Component {

    componentWillMount() {

        this.state = {
            id: this.props.router.params.id
        }

        // fire action to update redux project store
        this.props.dispatch(fetchProject(this.props.router.params.id))
    }

    componentDidUpdate(prevProps, prevState) {
         /**
         * this is the initial render
         * without a previous prop change
         */
        if(prevProps == undefined) {
            return false
        }

        /**
         * new Project in town ?
         */
        if (this.state.id != this.props.router.params.id) {
           this.props.dispatch(fetchProject(this.props.router.params.id))
           this.setState({id: this.props.router.params.id})
        }

    }

    render() { <Project .../> }
}
Revisionist answered 29/3, 2017 at 3:48 Comment(3)
Thanks, this solution works for me. But my eslint setting is complaining about this: github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/… What do you think about this?Doorframe
Yeah that's actually not best practice, sorry about that, after dispatching the the "fetchProject" your reducer will update your props anyways, I just used this to make my point without putting redux into placeRevisionist
Hi chickenchilli, I'm Actually still stuck in this... do you have other suggestions or recommended tutorials? Or I'll stick to your solution for now. Thanks for your help!Doorframe
G
15

If you have:

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

In React 16.8 and above, using hooks, you can do:

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

  return (<div>Layout</div>);
}
export default Component;

In there, you are only triggering a new fetchResource call whenever props.match.params.id changes.

Grown answered 8/3, 2019 at 20:9 Comment(1)
This is the better answer given that most of the other answers rely on the now deprecated and insecure componentWillReceivePropsLidless
O
10

Based on answers by @wei, @Breakpoint25 and @PaulusLimma I made this replacement component for the <Route>. This will remount the page when the URL changes, forcing all the components in the page to be created and mounted again, not just re-rendered. All componentDidMount() and all other startup hooks are executed also on the URL change.

The idea is to change components key property when the URL changes and this forces React to re-mount the component.

You can use it as a drop-in replacement for <Route>, for example like this:

<Router>
  <Switch>
    <RemountingRoute path="/item/:id" exact={true} component={ItemPage} />
    <RemountingRoute path="/stuff/:id" exact={true} component={StuffPage} />
  </Switch>
</Router>

The <RemountingRoute> component is defined like this:

export const RemountingRoute = (props) => {
  const {component, ...other} = props
  const Component = component
  return (
    <Route {...other} render={p => <Component key={p.location.pathname + p.location.search}
                                              history={p.history}
                                              location={p.location}
                                              match={p.match} />}
    />)
}

RemountingRoute.propsType = {
  component: PropTypes.object.isRequired
}

This has been tested with React-Router 4.3.

Oslo answered 6/1, 2019 at 9:45 Comment(0)
E
7

@wei's answer works great, but in some situations I find it better to not set a key of inner component, but route itself. Also, if path to component is static, but you just want component to remount each time user navigates to it (perhaps to make an api-call at componentDidMount()), it is handy to set location.pathname to key of route. With it route and all it's content gets remounted when location changes.

const MainContent = ({location}) => (
    <Switch>
        <Route exact path='/projects' component={Tasks} key={location.pathname}/>
        <Route exact path='/tasks' component={Projects} key={location.pathname}/>
    </Switch>
);

export default withRouter(MainContent)
Esma answered 10/7, 2018 at 11:15 Comment(1)
Adding key directly to <Route /> is more simple fix that also works for react with Typescript without additional codes (as other similar fixes requires some extra work on types).Depurate
D
5

This is how I solved the problem:

This method gets the individual item from the API:

loadConstruction( id ) {
    axios.get('/construction/' + id)
      .then( construction => {
        this.setState({ construction: construction.data })
      })
      .catch( error => {
        console.log('error: ', error);
      })
  }

I call this method from componentDidMount, this method will be called just once, when I load this route for the first time:

componentDidMount() {   
    const id = this.props.match.params.id;
    this.loadConstruction( id )
  }

And from componentWillReceiveProps which will be called since the second time we load same route but different ID, and I call the first method to reload the state and then component will load the new item.

componentWillReceiveProps(nextProps) {
    if (nextProps.match.params.id !== this.props.match.params.id) {
      const id = nextProps.match.params.id
      this.loadConstruction( id );
    }
  }
Darwindarwinian answered 20/10, 2018 at 15:6 Comment(2)
This works but has the problem that you need to add componentWillReceiveProps() for handling re-renders to every component that is loading data.Arliearliene
Use componentDidUpdate(prevProps). componentWillUpdate() componentWillReceiveProps() are deprecated.Orthotropic
H
3

React Router v6+

You need to specify a key. In earlier versions of React Router you could do the following:

<Route path="/project/:pid"
       render={(props) => (
           <Page key={props.match.params.pid} {...props} />)}
/>

Since render can't be used with <Route> anymore (starting from React Router v6), one of the simplest solutions is to create an auxiliary component:

const PageProxy = (props) =>
{
  const { pid } = useParams();
  return <Page key={pid} {...props} />;
}

And your <Route> becomes simply:

<Route path="/project/:pid" element={<PageProxy />} />
Hydracid answered 4/2, 2022 at 13:36 Comment(1)
shouldn't it be <Route path="/project/:pid" children={<PageProxy />} /> I can't find documentation on element prop anywhereTrevethick
G
2

You can use the method provided:

useEffect(() => {
  // fetch something
}, [props.match.params.id])

when component is guaranteed to re-render after route change then you can pass props as dependency

Not the best way but good enough to handle what you are looking for according to Kent C Dodds: Consider more what you want to have happened.

Gow answered 6/8, 2020 at 11:52 Comment(0)
E
0

If you are using Class Component, you can use componentDidUpdate

componentDidMount() {
    const { projectId } = this.props.match.params
    this.GetProject(id); // Get the project when Component gets Mounted
 }

componentDidUpdate(prevProps, prevState) {
    const { projectId } = this.props.match.params

    if (prevState.projetct) { //Ensuring This is not the first call to the server
      if(projectId !== prevProps.match.params.projectId ) {
        this.GetProject(projectId); // Get the new Project when project id Change on Url
      }
    }
 }
Eroto answered 13/5, 2020 at 15:36 Comment(1)
Are you sure about that? the ComponentDidUpdate is not and is not going to be deprecated in coming version, can you attach some link? the functions to be deprecated as follows: componentWillMount — UNSAFE_componentWillMount componentWillReceiveProps — UNSAFE_componentWillReceiveProps componentWillUpdate — UNSAFE_componentWillUpdateEroto
E
0

Here is a pretty simple solution: do a location check in componentDidUpdate, and have a getData function that has the data fetching part with setState:

componentDidUpdate (prevProps) {
    if (prevProps.location.key !== this.props.location.key) {
        this.getData();
    }
}


getData = () => {
    CallSomeAsyncronousServiceToFetchData
        .then(
            response => {
                this.setState({whatever: response.data})
            }
        )
}
Extensor answered 4/1, 2021 at 1:48 Comment(0)
I
0

I will try to give the updated answer.

So basically what you want is the Component to get remounted whenever we find a change in params.

Now react-router>6.0 has been released and this answer will be for React Router ^V6

So suppose I have a path

/user/<userId>

Here <userId> will be replaced by the actual userId

So the initialization of this path will be like this

<BrowserRouter>
    <Routes>
        <Route
           path="/user/:userid"
              element={<YourComponent/>}
         />
     </Routes>
</BrowserRouter>

Now in <YourComponent/> receiving end

import { useParams } from "react-router-dom";
import { useEffect } from "react";

export default function YourComponent(){
    const {userid} = useParams();

    useEffect(() => {
        // Some Logic Here
    },[userid])

   return (<Component/>)
}

So this useEffect() will mount itself everytime there is a change in the params (userid in this case)

Thus the outcome is whenever you hit the URL with same params (It is not equal to reloading the page. I mean to navigate to the same URL) the component will not remount itself but there will be remounting whenever there is a change in the params which I think solves your problem.

Incompatible answered 3/2, 2022 at 21:30 Comment(0)
M
-3

react-router is broken because it must remount components on any location change.

I managed to find a fix for this bug though:

https://github.com/ReactTraining/react-router/issues/1982#issuecomment-275346314

In short (see the link above for full info)

<Router createElement={ (component, props) =>
{
  const { location } = props
  const key = `${location.pathname}${location.search}`
  props = { ...props, key }
  return React.createElement(component, props)
} }/>

This will make it remount on any URL change

Modernize answered 25/1, 2017 at 20:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.