We code the web

React 0.14's coolest feature: function components

React 0.14 introduced some cool additions, one of them is a more simple way to create components. This is one of those nifty little features that makes developers happy :-).

This feature is meant for simple components that don’t use state and purely render based on props every time. Basically, you just provide React a function that takes props as an argument, and returns DOM elements!

This is how you would ‘normally’ create a (simple) component in React (using ES6):

class Ingredients extends React.Component {
  //comment
  render() {
    return (
      <ul>
        {this.props.ingredients.map((ingredient) => (
          <li>{ingredient}</li>}
        )
      </ul>
    }
  }
}

And now in the new ‘functional way’:

let Ingredients = (props) => (
  <ul>
    {props.ingredients.map((ingredient) => <li>{ingredient}</li>}
  </ul>
)

See? Way simpler, same result. And if you are old fashioned or don’t have any other choice, here’s the ES5 version:

function Ingredients(props) {
  return (
    <ul>
      {props.ingredients.map(function (ingredient) {
        return <li>{ingredient}</li>;
      }
    </ul>
  );
}

Notice how ES6 really shines here, you can even use destructuring inside of the parameter declaration to make it even more neat:

let Ingredients = ({ ingredients }) => (
  <ul>
    {ingredients.map((i) => <li>{i}</li>}
  </ul>
)

There is another nice plus the React team mentioned. In the future, these components will be rendered more performant than ‘normal‘ components. Because they are more predictable React can remove some operations on them and render them more efficient.

Downsides

Currently, this feature has some downsides:

  • Not all component features are available, like state and life cycle methods.
  • Testing is harder, some React test utilities don’t work on this type of component.

Update: I’ve written a little snippet/lib that can convert function components into ‘normal’ ones for testing purposes github.com/ngerritsen/react-stateless-wrapper

But the first point can also be seen as a plus. This type of component encourages you to compose you application of many simple (and performant) components.

So, I really like this feature, try it out. Happy coding!

Reference

Related posts

Flux, what and why?

If you are into front-end development, you’ve probably heard or read the term ‘Flux’. What does it mean and why should you care?

Using React with ES6 and Browserify

ECMAScript 6 is great! It gives us Javascript developers a long time longed for set of core functionalities like classes, imports and more. Browsers do not support most of the features yet, but we can use transpilers to be able to use ES6.

Async ... await in Javascript

We’ve all been through callback hell, maybe we use Promises and Observables to get some relief. Will async await liberate us once and for all?