Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript React Components (2018) React Component Patterns Optimize Performance with PureComponent

Clarification on PureComponent

I get the concept of having a component that doesn't re-render unless it's state or props change, but I'm still a bit confused because to me it seems that every React component should be a pure component. Isn't a component ONLY supposed to re-render when it's data changes? And isn't that the definition of a pure component? So I don't really understand why you wouldn't just want every component to be pure. Nothing should re-render unless it's data changes. Can someone explain to me how this works or help clear up my confusion? Thanks.

1 Answer

Mia Filisch
Mia Filisch
16,117 Points

The following is my current understanding: The root component in App.js renders a list of <Player /> elements based on an array of objects called players, which contains all the player data.

React will call the render() method when updates to state or props are detected - so if anything changes on our players array data in the state, the render() method in App will be called, which will re-render all the players in it, even if the change to the players data only affected one particular player.

This makes sense as a default as there is some cost to computing where exactly the change is - so by default, if thing X changes, anything using thing X will re-render, down through the child components. If everything were pure components, performance may actually be worse depending on the complexity of objects / arrays in your app that React is having to check to prevent unneccessary re-renders, and in this case not bothering with the checks and just doing the re-renders (as is the default) would be more performant.

With PureComponent, there's also a risk of false negatives, as the comparison is only shallow, so in complex data structures things that should update might get missed - as explained in the docs that were included in the Teacher's notes: https://reactjs.org/docs/react-api.html#reactpurecomponent