Home > Back-end >  How lifecycle methods in react Js are working with the variable unsubfromAuth?
How lifecycle methods in react Js are working with the variable unsubfromAuth?

Time:04-17

class App extends Component{
constructor(){
super() 
this.state = {
  currentuser : null
}}
  
unsubfromAuth = null

componentDidMount(){

this.unsubfromAuth =  auth.onAuthStateChanged((user) => {
  this.setState({currentuser : user})
  console.log(user)
})
  }
 componentWillUnmount() {
    this.unsubfromAuth()
  }
render(){
  return (
    <div className="App">
      <Router>
      <Header currentUser={this.state.currentuser}/>
        <Switch>
          <Route exact path="/" component={Home}/>
          <Route exact path="/Hats" component={Hats}/>
          <Route exact path="/shoes" component={Shoes}/>
          <Route exact path="/jackets" component={Jacket}/>
          <Route exact path="/men" component={Men}/>
          <Route exact path="/women" component={Women}/>
          <Route exact path="/shop" component={Shop}/>
          <Route exact path="/signin" component={Signin}/>
        </Switch>
      </Router>      
    </div>
  )
}}

export default App

Why it is used in ComponentWillUnmount? I heard something about memory leak, does it prevents from it? why it was changed in ComponentDidMount? I'm using firebase in Reactjs.

CodePudding user response:

This is the standard flow in a React Component lifecycle, when you have to subscribe to some event. This is just the initialization of the instance variable, it is executed as soon as the Component is mounted:

unsubfromAuth = null

This is where you effectively subscribe to your event ("auth-state-changed") and start to listen to it, you want always to subscribe to events like this in componentDidMount or useEffect if you use hooks, since this is executed when the Component has fully mounted.

The method auth.onAuthStateChanged() returns a function that automatically clears any subscription when called.

componentDidMount(){

this.unsubfromAuth =  auth.onAuthStateChanged((user) => {
  this.setState({currentuser : user})
  console.log(user)
})
  }

The unsubscription method will be called in:

componentWillUnmount() {
    this.unsubfromAuth()
  }

This will be executed just before the Component is going to unmount to clear the subscription, since you don't want your event listeners, and subscriptions to keep being in memory when you unmount, or you will end up with memory leaks if your component mounts and unmounts many times.

  • Related