programoholic
programoholic

Reputation: 5194

React : Component is getting remounted on route change

I am working on a react app. There is a dashboard page where a list on movies is displayed. When user clicks on any movie , the detail page of the clicked movie is displayed.

There is a button which lets the users go back to the dashboard page on the movie detail page.

When I am clicking the go back button , the dashboard page is getting remounted (state is lost ) and componentDidMount lifecycle method is getting called again.

I don't want the component to be remounted and it should hold the old state. Here is the router config file :

    <Switch>
        <Route exact path="/movies" component={Movies} key="page1"/>
        <Route exact path="/movies/detail/:id" component={MovieDetail} key="page2" />
        <Redirect to="/movies" exact component={Movies} />
    </Switch>

Here is the method getting called on back button. :

goBack = ()=>{
        this.props.history.goBack();
    }

I am using "react-router-dom": "^5.1.2", in my App.

Upvotes: 0

Views: 102

Answers (1)

IT&#39;s Bruise
IT&#39;s Bruise

Reputation: 834

of course the most popular way is store dashboard data in some storage like redux or sessionStorage (for saving data on refresh event) and restore data on componentDidMount

But i can suggest experimental decision to avoid componentDidMount. First of all you need to merge two routes to one path via array

<Switch>
  <Route path={["/movies", "/movies/detail/:id"]} component={Movies} />
  <Redirect to="/movies" exact component={Movies} />
</Switch>

Then you have to update Movies component

const Movies = () => {
  const [counter, setCounter] = useState(0);
  const { id } = useParams();

  const increment = useCallback(() => setCounter(counter + 1), [counter]);

  if (id) {
    return <MovieDetail id={id} />
  }

  return <button onClick={increment}>{counter}</button>
}

As result history.goBack will not affect the localState of Movies component

Upvotes: 1

Related Questions