B
B
bernex2017-01-04 11:56:14
React
bernex, 2017-01-04 11:56:14

Should I switch to React.PureComponent by default?

Now I usually use React.Component + redux + reselect in the code (a lot of places) to ensure that only changing is rendered. Maybe I forgot and I need to use React.PureComponent everywhere? Although it seems like there is no deep check of shouldupdate going on. where is wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PQR, 2017-01-12
@PQR

React.PureComponent implements the shouldComponentUpdate method in such a way that it does a shallow comparison of props and state (not a deep one). Here is the actual code:
https://github.com/facebook/react/blob/c8fbdac2271...

shouldUpdate =
            !shallowEqual(prevProps, nextProps) ||
            !shallowEqual(inst.state, nextState);

What is shallow Equal? This is essentially a === comparison of each element from prevProps with each element from nextProps. Just in case, I will give a link to the implementation for a complete understanding: https://github.com/facebook/react/blob/6963ea4bfcd...
In the end, it all depends on the structure of your props. If in props you pass objects that are sometimes mutated, i.e. by reference, they are equal ===, but inside some data has changed (which in itself looks strange in the redux + reselect ecosystem, but technically quite possible), then using PureComponent will break everything for you, because some components on the screen will stop redrawing!
If everything is in your mind, the data that is passed through props are scalar types (string, int, float, bool) or immutable objects, then feel free to use PureComponent - in some cases it will help get rid of unnecessary render calls.
Important note: PureComponent should only be used for so-called presentational components, i.e. for those components that are NOT wrapped in a redux connect() call.
For container components (i.e. those components that are wrapped in redux connect() ) it makes no sense to inherit from PureComponent, because the connect() method wraps your component with its shouldComponentUpdate implementation, which also uses shallowEqual. If you inadvertently inherit the container component from PureComponent, there will be no errors, but this does not make any sense, because your code will essentially do shallowEqual twice, why do extra work?
To summarize, the recipe is:
- presentational components inherit from React.PureComponent
- container components (which are wrapped in redux connect()) inherit from good old React.Component

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question