Stateless react components

look at the state of you.

Generally when building applications with react you will have two types of components, smart and dumb.

Dumb components are there for presentation, they take props and render them. They have no logic or state.

Unfortunately most example of components that ‘should’ be dumb are written in the same way a/Users/atmd/Projects/atmd83.github.io/_drafts/2016-12-14-oh-my-zsh-git-shortcuts.markdowns smart component when they should be written as a pure function.

A pure function is one that given the same input will always produce the same out put with no side effects. With react we can create pure components.

pure components

Taking learning from pure functions we can create our pure components, imagine this component below:

export default react.createClass({
  render() {
    return (
      <h1>Hello {this.props.name}</h1>
    );
  }
});

The above component is just taking a prop and rendering it, it’s a prime candidate for a refactoring which removes some boilerplate and makes the component ‘purer’. like this:

export default (props) => {
  return (
    <h1>Hello {this.props.name}</h1>
  );
}

how is the second example better then the first?

You’d be forgiven for thinking that both examples above do the same thing and that neither is more or less a pure component then the other, and you’d be right.

The first example though allows for state, logic and side effects to be easily and lazily added. What was once a pure component can be polluted and hacked.

It’s impossible in the second example to add state.

If a developer wanted to change the component form stateless to stateful they’d need to rewrite that component and because of the added time and complexity required more thought and system design will go into that decision (is making this component stateful the right thing to do or simply the easiest?)