Performance issues with a tree structure and shouldComponentUpdate in React / Redux

 ̄綄美尐妖づ 提交于 2019-11-30 00:30:42

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

git clone https://github.com/rackt/redux.git

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

open http://localhost:3000/
Sebastien Lorber

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!