Sitemap

React Pure Components

#an extension to class component

--

In the previous article, we learnt about React Reusable Material-UI Dialog Component. You can check the previous topic here.

  • In React we use shouldComponentUpdate() Lifecycle method to return a Boolean value that specifies whether React should continue with the rendering component or not and its default value is true.
  • We can use this method to let know React whether component’s output is affected by the current change in state or props or not.
  • But there is another option that is React PureComponent (a Class component). If we extend a class component with Pure Component, there is no need for shouldComponentUpdate() Lifecycle Method.
  • Pure Component compares current state and props with new props and states to decide whether the React component should re-render itself or not.
  • If the previous value of state or props and the new value of state or props is the same, the component will not re-render itself.
  • Pure Components restricts the re-rendering when there is no use of re-rendering of the component.

Consequences of using PureComponents

  • In Pure Components the value of State and Props are Shallow Compared (Shallow Comparison). So there is a possibility that if these State and Props Objects contain nested data structure then Pure Component’s implemented shouldComponentUpdate() will return false and will not update the whole subtree of Children of this Class Component.
  • So in Pure Component, the nested data structure doesn’t work properly.

React Child component to be imported and rendered in PureComponent

React PureComponent

React PureComponent Output

  • Initial state value is 1 in the above example.
  • In the componentDidMount lifecycle method state value modified after 4000 milliseconds, if value is same then component will not be rendered. In this case value is same (which is 1).
  • Pure Components prevents re-rendering of the component because there is no change in the state value.
  • Check console to see whether component is rendered or not. You can notice we specified console statement in life cycle method.

Above console statement helps to identify whether component is rendered or not. But if we specify value as 2(for example) then component will be re-rendered after 4000 milliseconds because there is change in state value.

Get Vinitha Subhash’s stories in your inbox

Join Medium for free to get updates from this writer.

Note: Read comments in code

--

--