React Component OR React PureComponent - reactjs

I am new to React and I want to know when should I be using a React Component and when should I be using React PureComponent?
Component:
import React, { Component } from 'react'
PureComponent:
import React, { PureComponent } from 'react'
Can I use React PureComponent everywhere?
OR
is it safe to use shouldComponentUpdate and check and return false of not required
I just read an article stating that using pure components actually cause more harm than good. they recommend using "react-update-if-changed". How much true is this?
Article: https://hackernoon.com/react-purecomponent-considered-harmful-8155b5c1d4bc

Can I use React PureComponent everywhere?
Yes, you can but trying using Functional component more and more. In case of Class component, keep it small and extend it to PureComponent or Component if you want to implement your own shouldComponentUpdate, would advise to do it when, on minimal non complex (nested deep array or/and object) props change your component needs to update.
Is it safe to use shouldComponentUpdate?
Yes, it is, if you know what you are doing, meaning that any flaw in your implementation, could lead to performance issues like unnecessary component re rendering just because your implementation of shouldComponentUpdate returned true or worse, that your component doesn't rerender on certain props change as your shouldComponentUpdate returns false due to some glitch.
The referenced medium post is trying to sell out react-update-if-changed package which seems like a good deal to go for at start but when you realize that
the real problem statement is all about performance optimization (refer https://reactjs.org/docs/optimizing-performance.html)
How to avoid unnecessary checks to determine component can update and avoid unwanted rerender ?
Pass props to component which you know is needed by the component and is going to change
In case, if there are many props being send to a component and on very few limited props change, the component needs to update and re render then you could very well implement your own shouldComponentUpdate (refer the example in the above shared link of react optimization). But be wary of props which are arrays and object, as differentiating them is a pain, especially the deep bulky nested ones.
Use a Functional (pure & stateless) component for your UI while for it's presentation logic (show-hide, sort, etc) would be present in a components which would be a Class (stateful and pure by extending it to React.PureComponent) having children prop as a function; with the help of HOC linking the logical and UI component
Do use the React Context API while trying to pass props between ancestor and descendant, especially if they are a level beyond like grand parent component to child component.
Using the last method which is all about Advanced React Patterns is the best way to have optimized performance and codebase. To understand it better, please refer Dumb and Smart Components and Presentational and Container Components.

import React, { PureComponent } from 'react'
export default Class PureComponent extends React.PureComponent{
}
import React, { Component } from 'react'
export default Class NormalComponent extends React.Component{
}
PureComponent Don’t have any Lifecycle Methods
PureComponent check shallow comparison and re-render when Needed
Use Pure Component when used when primitive data types int string boolean etc,
Note:-
PureComponent Don’t have any Lifecycle Methods
React PureComponent's shouldcomponentupdate() only shallowly compares the objects.

Related

React native PureComponent and shouldComponentUpdate

I need to know what is the meaning of shallow comparison when using PureComponent. Actually I read some treats but I could not understand the meaning of that so please simplify it.
An other question is, when we could use PureComponent and when using shouldComponentUpdate?
About Shallow Comparison you can check this answer
https://stackoverflow.com/questions/36084515/how-does-shallow-compare-work-in-react#:~:text=Shallow%20compare%20is%20efficient%20way,you%20don't%20mutate%20data.&text=shallow%20comparison%20is%20when%20the,comparisons%20deeper%20into%20the%20properties.
About shouldComponentUpdate [https://en.reactjs.org/docs/react-component.html#shouldcomponentupdate]
Use shouldComponentUpdate() to let React know if a component’s output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior.
Basically, the component will be re-render every single change of state, if you want to prevent it, you can use the shouldComponentUpdate().
About PureComponent[https://blog.logrocket.com/pure-functional-components-in-react-16-6/]
A React component can be considered pure if it renders the same output for the same state and props. For class components like this, React provides the PureComponent base class. Class components that extend the React.PureComponent class are treated as pure components.
I do strong recommend you to read about React Hooks[https://en.reactjs.org/docs/hooks-intro.html] It makes easy to have PureComponents and to control when and how it should be re-render.
Regards.

React memo with stateless component

Before react introduce memo and hook All functional component was stateless.
After Introducing memo and hook I'm little confused with these two concept.
Is React.memo for functions that use hook only?
Should I update all my stateless functional component to React.memo for optimizing? Or react optimize it when a function does not use hook automatically?
For understanding what React.memo is used for, first you have to understand the difference between React.Component and React.PureComponent.
From the 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.
If your React component’s render() function renders the same result
given the same props and state, you can use React.PureComponent for a
performance boost in some cases.
React.memo is the same as a React.PureComponent, just for the functional components. So, if you think that with a given props, your component will be rendered the same, you can wrap your component with React.memo for performance boost and memoizing the result as mentioned in the docs.
But do specifically take a look at the line in the docs, which says -
This method only exists as a performance optimization. Do not rely on
it to “prevent” a render, as this can lead to bugs.
And you should make your decision about using React.memo irrespective of the hooks.

Do I need React.PureComponent when the component is `connect`ed to react-redux store?

They say we can improve the performance of React app by using React.PureComponent in some cases, because it shallow compares its props before updating the component.
https://reactjs.org/docs/react-api.html#reactpurecomponent
On the other hand, react-redux's mapStateToProps uses shallow comparison when it decides whether we need to update the component.
https://redux.js.org/faq/reactredux#why-is-my-component-re-rendering-too-often
So, can I say I do not need React.PureComponent when its props are from react-redux connect, and it has no state? Or is there any difference between them?
As long as your component receives all its props from Redux and all changes to state can be recognized with a shallow comparison, you can use regular Component to the same effect as PureComponent. Just make sure when you update the state you don't mutate it, but instead return a new copy of the state. Immutable.JS is extremely helpful for this.

Is state the only difference between a PureComponent and a stateless functional component?

If I define a PureComponent that
only has a render() method, and
does not use this.state,
...is it effectively identical to a stateless functional component? Or are there any differences in behaviour or performance?
This is not a duplicate of React functional stateless component, PureComponent, Component; what are the differences and when should we use what? because the answer to my question is not contained there, at least not in a way that's easy to pinpoint. That is a big, wide-ranging question, and mine is very specific.
A stateless functional component is effectively identical to React.Component without lifecycle methods and state, not to React.PureComponent.
The whole point of React.PureComponent is to use one of the life cycle methods (shouldComponentUpdate) and make it to return true only if properties & state have changed, using shallow comparison.
There is no way how to do that in stateless functional components since they are always rendered and have no way to define shouldComponentUpdate.
This behavior is described in detail in Optimizing Performance.

Will a stateless component re-render if its props have not changed?

One thing I had learned about React is that if the props to a component don’t change, then React doesn’t bother re-rendering the component. Is that true for stateless components too? Or do they behave more like “stupid” functions and get executed every time?
For example, if I had:
import StatelessComponent from '../StatelessComponent';
export default class DocumentsTable extends React.Component {
state = {
something: 'foobar',
};
render() {
return (
<div>
{ this.state.something }
<StatelessComponent theOnlyProp='baz'>
</div>
)
}
};
When this.state.something updates its value, does <StatelessComponent> get re-rendered? Or is it “smart” enough to see that its props didn’t change, like other React components?
UPDATE 25.10.2018
Since React 16.6, you can use React.memo for functional components to prevent re-render, similarly to PureComponent for class components:
const MyComponent = React.memo((props) => {
return (
/* markup */
);
});
Also, memo does internal optimization.
And unlike a userland memo() higher-order component implementation, the one built into React can be more efficient by avoiding an extra component layer.
Blockquote
OLD ANSWER
Yes, they always re-render 1 (unless you use React.memo as explained above) if setState() is called in the component itself or one of its parents, because functional stateless components don't carry a shouldComponentUpdate. In fact, each React component is being re-rendered1 unless they implement shouldComponentUpdate.
Important to note is that calling render() doesn't mean that DOM Nodes are being manipulated in any way. The render method just serves the diff algorithm to decide which DOM Nodes need to really be attached / detached. Note that render() is not expensive, it's the DOM manipulations that are expensive. They are executed only if render() returns different virtual trees.
From React's documentation
Just to be clear, rerender in this context means calling render for all components, it doesn’t mean React will unmount and remount them. It will only apply the differences following the rules stated in the previous sections.
Just don't worry and let render() be called unless your component is huge, then you're better off with stateful Component that implements shouldComponentUpdate().
Look here for an interesting discussion.
1 means that render() function of the component is called, not that the underlying DOM node is being manipulated.
See react does not only rerenders only If props are changed it even rerenders itself if any state change is there. In your case the component will rerender as your state is changing. The way react works is based on an algorithm named Reconciliation, what this algorithm does is that it compares your virtual DOM with real DOM and if it sees any change then it rerender your actual DOM by replacing it with your virtual DOM so any change in state will cause rerendering of the whole component.
Will a Stateless component re-render if its props have not changed?
Yes. Stateless render function will be called even if nothing has changed. However, React will in the reconciliation phase compare the virtual DOM (generated by the render function) against the existing DOM. This is far in the pipeline, hence not ideal if the render function was costly to compute.
A Pure component does have a default shallow comparison of the property and would have stopped the render to be executed. See the Pure component as a normal class React component that has a shouldComponentUpdate that compare with a triple equal the existing properties and the new one.
That being said, you can wrap your Stateless component into a Pure Component by using Recompose.pure (https://github.com/acdlite/recompose/blob/master/docs/API.md#pure) which will automatically perform, like the Pure Component, a shallow comparison without compromising on the short syntax of the Stateless component.
import StatelessComponent from '../StatelessComponent';
const PureChildFromStatelessComponent = Recompose.pure(StatelessComponent);
// ...
<PureChildFromStatelessComponent ... />

Resources