Using arrow functions for stateless React.js components

Stateless is good. It's a fundamental strength of functional programming. React components are class based, but basic components, that don't need a state, can be written as an arrow function.

Why stateless

Stateless components are predictable because they do not have their own this variable that can be sneakily manipulated in a function. An arrow function's this is inherited from the scope above it. If you are making a component that doesn't use any React.js features (aside from jsx), you can probably turn it into an arrow function component. Less overhead, less lines and more predictable behavior.

Class-based component

import React, { Component } from 'react'

class ProfilePicture extends Component {
  render() {
    return (
      <div>
        <img src={this.props.imageUrl}/>
        {this.props.name}
        {this props.userDescription}
      </div>
    )
  }
}

Arrow function component

import React from 'react'

const ProfilePicture = props => (
  <div>
    <img src={props.imageUrl}/>
    {props.name}
    {props.userDescription}
  </div>
) //parentheses for implicit return

Comments

Popular posts from this blog

Contrasting var and ES6s new declarations: let and const

Modularity vs. Abstraction. Which is More Important?

Unit testable components pt.3: Testing components