jmreidy / fluxy

An implementation of Facebook's Flux architecture
232 stars 19 forks source link

Example in documentation on how to optimize with Store watch handlers #8

Open nicolashery opened 10 years ago

nicolashery commented 10 years ago

The handler passed to Store.addWatch is a function(keys, oldState, newState). I think that's great, but at first it wasn't obvious how I would optimize React's re-render by using the keys. Now it's clearer, but there is still the question of when keys is an array (I'm guessing a deep compare, with Lo-Dash maybe? or a JSON.stringify with equality check?). Could it be worth adding an example to the README for that?

jmreidy commented 10 years ago

The following comment already exists:

Note the keys argument of the watcher handler. It's a reference to string or array of keys passed into the set function. Using keys, you can easily figure out whether your watcher handler should care about the updated state (or not).

How should this be elaborated on?

nicolashery commented 10 years ago

Good question. Maybe an example? But that might not be necessary...

Initially I was wondering what to do when keys is an array. I thought of something like:

function arrayEquals(arr1, arr2) {
  return mori.equals(mori.js_to_clj(arr1), mori.js_to_clj(arr2));
}

Then:

// PublicProfile.react.js
handleUserStoreChange: function(keys, oldState, newState) {
  if (arrayEquals(keys, ['user', 'publicProfile']) {
    return;
  }
  this.setState({profile: UserStore.get(['user', 'publicProfile']});
}

However, I realized that I'm mostly watching for changes on stores' top-level objects, so keys is almost always a string.

On a related subject, I wondered if I should optimize using the components' shouldComponentUpdate method, or the handleStoreChange methods, or both. I ended up using shouldComponentUpdate in my controllers (React component with state as mori data structures, so easy to check for change in state), but the question is still up in the air :)