Accepted answer

I just added a new example showing just that.
You can run it like this:

git clone

cd redux/examples/tree-view
npm install
npm start

open http://localhost:3000/


Dan Abramov solution is fine in 99% of usual cases.

But the computation time required on each increment is proportional O(n) to the number of nodes in the tree , because each connected node HOC has to execute a little bit of code (like identity comparison...). This code is pretty fast to execute however.

If you test Dan Abramov solution, with 10k nodes on my laptop I start to see some latency when trying to increment the counter (like 100ms latency). It is probably much worse on cheap mobile devices.

One could argue that you should not try to render 10k items in the DOM at once, and I totally agree with that, but if you really want to display a lot of items and connect them it is not that simple.

If you want to turn this O(n) to O(1), then you can implement your own connect system where the HOC's (Higher Order Component) subscription is only triggered when the underlying counter is updated, instead of all HOC's subscriptions.

I've covered how to do so in this answer.

I created an issue on react-redux so that connect becomes more flexible and permit easily to customize the store's subscription through options. The idea is that you should be able to reuse connect code and subscribe efficiently to state slices changes instead of global state changes (ie store.subscribe()).

const mapStateToProps = (state,props) => {node: selectNodeById(state,props.nodeId)}

const connectOptions = {
   doSubscribe: (store,props) => store.subscribeNode(props.nodeId)

connect(mapStateToProps, undefined,connectOptions)(ComponentToConnect)

It is still your own responsability to create a store enhancer with a subscribeNode method.

Related Query

More Query from same tag