Introduction to React
Facebook's React is "a library for user interfaces". Its single role is to manage and render your user interface. On its own it does nothing more... no communication with your API, no central state management, and no extra logic.
Facbeook's documentation and introduction to React is pretty thorough and worth a read. Because of that we'll jog through the key concepts to React and some tips to getting the most out of it.
That aside, let's talk about how React works and why it's taken the UI world by storm.
Note
This section assumes knowledge of HTML, CSS, and JavaScript (subsequently called JS), including ES6. If you don't know JS you should read http://eloquentjavascript.net/ before continuing. And you can brush up on ES6 with these resources: https://github.com/ericdouglas/ES6-Learning.
How react works: components
The most important concept to react are components. Writing a component is like writing a group of HTML tags, or sometimes a single custom tag.
Here's a basic component defined using ES6 classes (this is the same as the React documentation):
import React from 'react';
/**
* Rendering <HelloMessage text='Hello Sarah' /> results in this HTML:
* <div>Hello Sarah</div>
*/
class HelloMessage extends Component {
render() {
return <div>{ this.props.text }</div>
}
}
It's basic. We didn't discover a new particle. That said, the idea of a component is so powerful that it'll change the way you build UI — hopefully forever.
Why components work
Components are compositional
You can nest and combine components in any combination. You'll end up writing less code and you'll end up having less tests. It also means reusing components is easy – whether you want to reuse something across projects or in the same project.
Components contain no state and no data logic
This makes writing components similar to writing basic HTML. They're easy to write, easy to test, and easy to come back to in a year's time and figure out just what the flying tosspot you were doing.
Components have a basic lifecycle
There's no complex logic and no stream of events to follow. You'll be stoked to hear that you don't have to breakpoint and namespace every single event in your app and follow the chain 10 events deep to see why your views are updating.
Components can be enhanced
You can enhance basic components by wrapping them with more complex parents. ES7 introduces decorators that allow us to do this with a single line. You essentially keep all of your hardcore logic within higher-order components — which only exist to add functionality to child components.