What's the difference between pure() from the Recompose library and React.PureComponent? I'm guessing they are essentially solving the same problem. Can someone please clarify this?
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.
It is the type of component which re-renders only when the props passed to it changes and not even if its parent component re-renders or if the shouldComponentUpdate()method is called. It is greatly used to enhance the performance of a web application.
A React component is considered pure if it renders the same output for the same state and props. For this type of class component, React provides the PureComponent base class. Class components that extend the React. PureComponent class are treated as pure components.
When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won’t compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate is called.
For functional components we can use pure function as shown below − As PureComponent does shallow comparison of state and props objects and so there is a possibility that if these objects contains nested data structure then PureComponent’s implemented shouldComponentUpdate will return false .
In case of React Pure Component, the changes in react “props” and “state” is Shallow Compared. We need to understand the concept of Shallow Comparison before we proceed.
It works only if the state and props are simple objects. Components can be termed as pure if they return same output for same input values at any point of time. If state or props references new object, PureComponent will re-render every time.
The difference is that React.PureComponent
is stateful component and keeps track on the state:
React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.
While Recompose is aimed at stateless functional components, pure
shallowly detects changes in props only.
Both use shouldComponentUpdate
to shallowly detect changes, so there's no practical difference between them, as long as a component doesn't involve local state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With