meg
meg

Reputation: 37

ComponentDidMount( ) function

componentDidMount() is called just once but the dispatch and subscribe function inside it are called more than once... 1st line of this function executes for the first time only, but the subscribe function is called every time my component is re-rendered. How does react reaches subscribe function without encountering console.log("mounted"), i.e., the first line of function?

componentDidMount() {
     console.log("mounted"); //executed just once
      const {store}=this.props; 
      store.subscribe(()=>{
        console.log("SUBSCRIBE"); // executed everytime my funct is re rendered
        this.forceUpdate();
      })
     store.dispatch(addMovies(movies));
     console.log("State is :", store.getState());
   }

Upvotes: 1

Views: 170

Answers (1)

Drew Reese
Drew Reese

Reputation: 202751

You've subscribed to your redux store and provided a callback.

subscribe listener

Adds a change listener. It will be called any time an action is dispatched, and some part of the state tree may potentially have changed. You may then call getState() to read the current state tree inside the callback.

The callback will be invoked any time an action has been dispatched, and the state tree might have changed. This includes any action dispatched to the store by any other component, not just the component the subscription is created in.

Seems if there is a one-to-one relationship between component rerender and redux store updating that this component is likely dispatching an action that eventually causes it to be rerendered.

Upvotes: 1

Related Questions