Search code examples
javascriptreactjsfluxreactjs-flux

When and how does re-rendering happens when stores emits any event in flux?


I am a newbee in react + flux. I'm bit confused about when and how does re-rendering happens when an event is emmitted by stores. In my app I am listening to a event in the function componentWillMount() which is called just before rendering happpens. It's working fine and my views are getting updated. I have just once concern that what causing my component to re-render. Below is the codes.

function to update store

 createTodo(text){
const id = Date.now();
this.todos.push({
    id,
    text,
    complete:false
});

this.emit("change");

My component -- listener method.

componentWillMount(){

TodoStore.on("change", () => {
    this.setState({
        todos: TodoStore.getall()
    })
})
}

Here what is causing my component to re-render? Can you please explain me in details.


Solution

  • Every time you call setState the component will re-render.

    See: https://facebook.github.io/react/docs/component-api.html

    setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate(). If mutable objects are being used and the logic cannot be implemented in shouldComponentUpdate(), calling setState() only when the new state differs from the previous state will avoid unnecessary re-renders.