Search code examples
reactjsflux

listening a store vs forceUpdate()


If I have five components on a page, which can get something from a store. They all are listening to a single store. For all components I create listeners in a store.

My question is - Can I use forceUpdate() instead of listener. Send something in a store and wait for update:

getInitialState: function() {
   return {val: Store.getFoo};
},
click: function(info) {
  Store.updateInfo(info, function() {
   this.forceUpdate();
  })
}

In store:

updateInfo: function(info, callback) {
   foo = info + someValue;
   callback()
}

But in documentation:

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render(). This makes your application much simpler and more efficient

Thank you.


Solution

  • You can use forceUpdate, but you shouldn't.

    Your current approach is correct (not using forceUpdate).

    If you have a common parent of these 5 listen for changes and pass data down to the children, the parent code will become bloated and you'll have 6 components (parent, 5 children) render when the store changes. Having more of these "container" components that listen to the store creates more isolation between components ("independent children") and is more performant because less components re-render when the store updates. Make sure you use shouldComponentUpdate, too.

    If you'd like to learn more about "independent children" and higher-performance react, watch: https://www.youtube.com/watch?v=KYzlpRvWZ6c