ReactJS, Calling setState with same parameter

前端 未结 3 1029
旧巷少年郎
旧巷少年郎 2021-01-07 16:45

I have been reading the React docs and came across shouldComponentUpdate(). My understanding is that everytime setState() is called, a re-render of

3条回答
  •  天涯浪人
    2021-01-07 17:06

    Adding more to @Jyothi's answer regarding implementing shouldComponentUpdate() to skip unnecessary re-renders, in React 15.3 they introduced a new concept PureComponent. From reactjs docs

    The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

    This allows to skip unnecessary calls of render in class components by just implementing PureComponent instead of the usual Component. There are a few caveats with PureComponent though, from the docs about React.PureComponent’s shouldComponentUpdate():

    ... only shallowly compares the objects. If these contain complex data structures, it may produce false-negatives for deeper differences.

    ... skips prop updates for the whole component subtree. Make sure all the children components are also “pure”.

    Usage of PureComponent can in some cases improve performance of your app. Moreover, it enforces you to keep state and props objects as simple as possible or even better, immutable, which might help simplify the app structure and make it cleaner.

提交回复
热议问题