Here's a quick rundown on what's going on with React v16 components.
Suppose that you are calling a Foo
component in your React code like so:
<Foo name="Fred" />
In earlier versions of React, Foo
may have looked something like this, using React.createclass()
.
var Foo = React.createClass({
render: function() {
return (<div>Hello, {this.props.name}!</div>);
}
});
Since React v15, this has been deprecated and React now uses ES6 classes for declaring stateful components. Which looks like:
class Foo extends React.Component {
constructor (props) {
// Can do constructery stuff here
}
render () {
return (<div>Hello, {this.props.name}!</div>);
}
};
However, React also now includes the ability to use what are known as functional stateless components for enabling the consistent rendering of simpler components that don't need to have internal state management. It's considered a best practice to use FSCs whenever possible, as it makes the code smaller, easier to read, and forces the developer to keep logic and rendering seperate whenever possible.
An FSC can look like this:
const Foo = function(props) {
return (<div>Hello, {props.name}!</div>);
}
Something you'll notice right away is that it's just a normal function instead of a class or an object literal, with the props being passed in as a parameter, and the return value being the JSX component itself. There's no React lifecycle functions (since it itself is a function), and the returned JSX component is what is rendered. There's also no need for this
, so this.props
becomes props
.
Furthermore, modern JS usage includes ES2015 functionality like arrow functions, which utilize the "fat arrow" (=>
), which causes our FSC to look instead like this:
const Foo = (props) => {
return (<div>>Hello, {props.name}!</div>);
}
You can learn a bit more about functional stateless components here, more about ES6 classes here, and more about fat arrow notation here.