Articles
November 3, 2024

Demystifying the Pure Component

Demystifying the Pure Component

Sleek v2.0 public release is here

Lorem ipsum dolor sit amet, consectetur adipiscing elit lobortis arcu enim urna adipiscing praesent velit viverra sit semper lorem eu cursus vel hendrerit elementum morbi curabitur etiam nibh justo, lorem aliquet donec sed sit mi at ante massa mattis.

  1. Neque sodales ut etiam sit amet nisl purus non tellus orci ac auctor
  2. Adipiscing elit ut aliquam purus sit amet viverra suspendisse potent i
  3. Mauris commodo quis imperdiet massa tincidunt nunc pulvinar
  4. Adipiscing elit ut aliquam purus sit amet viverra suspendisse potenti

What has changed in our latest release?

Lorem ipsum dolor sit amet, consectetur adipiscing elit ut aliquam, purus sit amet luctus venenatis, lectus magna fringilla urna, porttitor rhoncus dolor purus non enim praesent elementum facilisis leo, vel fringilla est ullamcorper eget nulla facilisi etiam dignissim diam quis enim lobortis scelerisque fermentum dui faucibus in ornare quam viverra orci sagittis eu volutpat odio facilisis mauris sit amet massa vitae tortor condimentum lacinia quis vel eros donec ac odio tempor orci dapibus ultrices in iaculis nunc sed augue lacus

All new features available for all public channel users

At risus viverra adipiscing at in tellus integer feugiat nisl pretium fusce id velit ut tortor sagittis orci a scelerisque purus semper eget at lectus urna duis convallis. porta nibh venenatis cras sed felis eget neque laoreet libero id faucibus nisl donec pretium vulputate sapien nec sagittis aliquam nunc lobortis mattis aliquam faucibus purus in.

  • Neque sodales ut etiam sit amet nisl purus non tellus orci ac auctor
  • Adipiscing elit ut aliquam purus sit amet viverra suspendisse potenti
  • Mauris commodo quis imperdiet massa tincidunt nunc pulvinar
  • Adipiscing elit ut aliquam purus sit amet viverra suspendisse potenti
Coding collaboration with over 200 users at once

Nisi quis eleifend quam adipiscing vitae aliquet bibendum enim facilisis gravida neque. Velit euismod in pellentesque massa placerat volutpat lacus laoreet non curabitur gravida odio aenean sed adipiscing diam donec adipiscing tristique risus. amet est placerat in egestas erat imperdiet sed euismod nisi.

“Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum”
Real-time code save every 0.1 seconds

Eget lorem dolor sed viverra ipsum nunc aliquet bibendum felis donec et odio pellentesque diam volutpat commodo sed egestas aliquam sem fringilla ut morbi tincidunt augue interdum velit euismod eu tincidunt tortor aliquam nulla facilisi aenean sed adipiscing diam donec adipiscing ut lectus arcu bibendum at varius vel pharetra nibh venenatis cras sed felis eget dolor cosnectur drolo.

Photo by David Besh on Unsplash

What? PureComponent again? That belongs to classes, and nobody uses classes anymore! How come you’re not writing about hooks?

Well, React hooks are very amazing and very useful – I definitely love ’em and will write about those soon. However, I am convinced that in even a year from now, people will still need the know-how of PureComponent and how it works. Even in his Resilient components article, which provides best practices and use cases for hooks, Dan Abramov is mentioning PureComponent’s work as a strategy and not necessarily as a specific React component.

Whether you’ve been doing React for 6 months or 2+ years or more, there’s no chance you’ve never at least heard of PureComponent.

That said, even after several years of React development, I found myself still having some questions about how exactly a PureComponent behaves.

Sure, most of us know it simply implements a shallow shouldComponentUpdate() comparison method and some of us have also learned to not just use PureComponent blindly in all cases. However, I still had doubts about how and when exactly its children are rendered, and under which conditions.

As I don’t like to guess around when it comes to tech / coding (or any other exact technical subject for the matter), I created an example for myself. And as it made things clear for me and for some of my colleagues, I was thinking why not clean it up, make it clearly readable and share it for others, so they could also have a clear understanding of how PureComponent works.

So here goes:

So, what do we have here?

We have a Parent – which is a Pure component. This parent is Pure but its props keep changing (due to the setInterval() which keeps modifying a state value) and so it keeps re-rendering.

class PureParent extends PureComponent {
  render() {
    const now = Date.now();
    return (<div className='pure-parent'>
      <span>Pure parent</span>
      <ul className='properties'>
        <li><i class="fas fa-parking" />Pure</li>
        <li><i class="fas fa-angle-double-down"></i>Props keep changing</li>
        <li><i class="fas fa-sync-alt" />keeps re-rendering</li>
      </ul>
      <ul>
        <li>I was last updated at: {now}</li>
        <li>With the prop value of: {+ ' ' + this.props.value}</li></ul>
      <div className='child-container'>
        <UnPureChild value={456} title={'UnPure child'} isChangingProps={false} />
        <PureChild value={123} />        
      </div>
    </div>);
  }
}

pureParent.jsx hosted with ❤ by GitHub (view raw)

The Pure Parent has children – one of them is Pure and the other isn’t. So one of them keeps re-rendering, and the other doesn’t. Really they are very similar and could be extracted to a more generalized form, but for the sake of this example we’ll keep it that way.

class PureChild extends PureComponent {
  render() {
    const now = Date.now();
    return (<div className='pure-child'>
      <span>Pure child</span>
      <ul className='properties'>
        <li><i class="fas fa-parking" />Pure</li>
        <li>
          {this.props.isChangingProps
            ? <Fragment><i class="fas fa-angle-double-down" />Props keep changing</Fragment>
            : <Fragment><i class="fas fa-ban" />Props NOT changing</Fragment>}
        </li>
        <li><i class="fas fa-pause-circle" />
          NOT re-rendering
        <i class="fas fa-thumbs-up" />
        </li>
      </ul>
      <ul>
        <li>I was last updated at: {now}</li>
        <li>With the prop value of: {+ ' ' + this.props.value}</li></ul>
    </div>);
  }
}

class UnPureChild extends Component {
  render() {
    const isChangingProps = this.props.isChangingProps;
    const now = Date.now();
    return (<div className='other-child'>
      <span>{this.props.title}</span>
      <ul className='properties'>
        <li><i class="fas fa-parking" style={{ color: 'white' }} />NOT Pure</li>
        <li>
          {isChangingProps
            ? <Fragment><i class="fas fa-angle-double-down" />Props keep changing</Fragment>
            : <Fragment><i class="fas fa-ban" />Props NOT changing</Fragment>}
        </li>
        <li><i class="fas fa-sync-alt" />
          keeps re-rendering
        {isChangingProps
            ? <i class="fas fa-thumbs-up" />
            : <i class="fas fa-thumbs-down" />}
        </li>
      </ul>

      <ul>
        <li>I was last updated at: {now}</li>
        <li>With the prop value of: {+ ' ' + this.props.value}</li></ul>
    </div>);
  }
}

pure-example-children.jsx hosted with ❤ by GitHub (view raw)

This example is quite simple and illustrates well how PureComponent handles props changes, and how it relates to its children. You can play with the code on the excellent StackBlitz platform to simulate more scenarios if you’d like.

About the author

Subscribe to our newsletter

Thanks for subscribing to our newsletter
Oops! Something went wrong while submitting the form.
Subscribe To Our Newsletter - Sleek X Webflow Template