SJC
SJC

Reputation: 107

How to call a function after a component has been unmounted?

I have a component that will call browserHistory.push(url) at some point, and I need to call a function after the component has been unmounted and the next component has mounted. At the moment, I'm using setTimeout because it seems that unmounting a component fires all the setTimeouts immediately. Is there a better way of doing this?

Upvotes: 1

Views: 3168

Answers (3)

Shraddha Goel
Shraddha Goel

Reputation: 897

You should go through the lifecycle docs of react https://reactjs.org/docs/state-and-lifecycle.html

The main two methods are for your use is componentDidMount. You can call your function inside this method of the next component that renders after pushing the URL. It is obvious that your old component was unmounted at that time.

I can only suggest this approach at this time. Maybe your function has different dependencies which require its call in the old component itself.

Upvotes: 2

Anantha kumar
Anantha kumar

Reputation: 375

You can use your parent component for calling that function, if you do conditional rendering. You can also use componentDidMount in next component as @Hasan said.

Upvotes: 2

Hasan Sh
Hasan Sh

Reputation: 1063

I'm not sure what that function does, but the best is to call it within the componentDidMount in your next component.

Upvotes: 3

Related Questions