Pure Components
source: https://www.fullstackreact.com/30-days-of-react/day-11/
For more performance and simplicity, React _also _allows us to create pure, stateless components using a normal JavaScript function.
A _Pure _component can replace a component that only has a render
function. Instead of making a full-blown component just to render some content to the screen, we can create a _pure _one instead.
_Pure _components are the simplest, fastest components we can write. They are easy to write, simple to reason about, and the quickest component we can write. Before we dive into _why _these are better, let's write one, or heck a couple!
// The simplest one
const HelloWorld = () => (<div>Hello world</div>);
// A Notification component
const Notification = (props) => {
const {level, message} = props;
const classNames = ['alert', 'alert-' + level]
return (
<div className={classNames}>
{message}
</div>
)
};
// In ES5
var ListItem = function(props) {
var handleClick = function(event) {
props.onClick(event);
};
return (
<div className="list">
<a
href="#"
onClick={handleClick}>
{props.children}
</a>
</div>
)
}
Uhh... so why care?
Advantages to using functional components in React are:
- We can do away with the heavy lifting of components, no constructor, state, life-cycle madness, etc.
- There is no
this
keyword (i.e. no need to bind) - Presentational components (also called dumb components) emphasize UI over business logic (i.e. no state manipulation in the component)
- Encourages building smaller, self-contained components
- Highlights badly written code (for better refactoring)
- FAST FAST FAST FAST FAST
- They are easy to reuse
You might say why not use a functional component? Well, some of the disadvantage of using a functional component are some of the advantages:
- No life-cycle callback hooks
- Limited functionality
- There is no
this
keyword