M K Sharma
M K Sharma

Reputation: 163

how to clear data of useState when route get changed

I have maintained state by using useState hook in react. I want to clean value that is getting maintain in state when route get changes.

For example - I have 4 routes declared in react based project. which are as below

<Router>
    <Layout>
      <Route exact path="/" component={Home}></Route>
      <Route exact path="/defineFacilities" component={DefineFacilities}></Route>
      **<Route exact path="/createNewModel/:id" component={ModelFormsContainer}></Route>**
      <Route exact path="/viewExistingModels" component={ViewExistingModels}></Route>
      <Route exact path="/importNewModel" component={ImportNewModel}></Route>
    </Layout> 

I have maintained state in ModelFormsContainer component. I want to clean state values when user move to other routes. Currently when I move to other route and back ModelFormsContainer component then I noticed that my state are still available.

Upvotes: 0

Views: 1461

Answers (1)

Drew Reese
Drew Reese

Reputation: 202706

I wasn't able to reproduce the issue you describe, but if you need to do something when the route changes you can listen for changes to the route/location via the history object.

history.listen

Starts listening for location changes and calls the given callback with an Update when it does.

// To start listening for location changes...
let unlisten = history.listen(({ action, location }) => {
  // The current location changed.
});

// Later, when you are done listening for changes...
unlisten();

In the ModelFormsContainer access the passed history prop instantiate a listener when the component mounts, pass it a callback that updates the state.

Example:

useEffect(() => {
  const unlisten = history.listen(() => {
    console.log("route changed!!");
    // apply business logic to set any component state
  });
  console.log("ModelFormsContainer mounted");

  return unlisten;
}, []);

If ModelFormsContainer is a class component then obviously use componentDidMount and componentWillUnmount and save unlisten as a class instance variable, i.e. this.unlisten.

Upvotes: 1

Related Questions