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):
And now in the new ‘functional way’:
See? Way simpler, same result. And if you are old fashioned or don’t have any other choice, here’s the ES5 version:
Notice how ES6 really shines here, you can even use _destructuring_ inside of the parameter declaration to make it even more neat:
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.
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!
- React 0.14 release notes: facebook.github.io/react/blog/…/react-v0.14-rc1
- ES6 Arrow functions: developer.mozilla.org/en-US/docs/…/Arrow_functions