React.PureComponent
is exactly the same as
React.Component
except that it handles the
shouldComponentUpdate()
method for you. When props or state change, PureComponent will perform a shallow comparison of both props and state. A regular component, on the other hand, will not compare the current props and state with the next ones out of the box. Therefore, the component will re-render by default on every
shouldComponentUpdate
call.
You will find that your components are far easier to reuse and reason about if you split them into two categories. I call them Smart and Dumb, but I have also heard Fat and Skinny, Stateful and Pure, Screens and Components, and so on. These are not all exactly the same thing, but the idea is similar.
My dumb components:
- do not depend on the rest of the application, for example Flux actions or stores
- are often contained in this.props.children
- receive data and callbacks exclusively through props
- have their own css file
- occasionally have their own state
- may use other dumb components
- examples: Page, Sidebar, Story, UserInfo, List
My smart components:
- wrap one or more dumb or smart components
- hold store state and pass it down as objects to dumb components
- call Flux actions and provide them to dumb components as callbacks
- never have styles of their own
- rarely emit DOM themselves, use dumb components for layout
- examples: UserPage, FollowersSidebar, StoryContainer, FollowedUserList
I put them in different folders to make the distinction explicit.
The benefits of this approach
- Better separation of concerns. You understand your application and your UI better if you write components this way.
- Better reusability. You can use the same dumb component with completely different sources of state.
- Dumb components are effectively the “palette” of your application; you can put them all on a single page and let a designer tweak them without digging into the application logic. You can run regression testing on such a page.
- It forces you to extract “layout components” such as Sidebar, Page, ContextMenu and to use this.props.children instead of duplicating the same markup across different smart components.
Remember, components should not emit DOM. They should only provide boundaries between UI.
Comments