Creating Stateless Function Components

When a component is purely a result of props alone, no state, the component can be written as a pure function avoiding the need to create a React component instance. In the code example below MyComponent is the result of a function that returns the results from React.createElement().

source code

Having look at the same code not using JSX should clarify what is going on.

  1. var MyComponent = function MyComponent(props) {
  2. return React.createElement(
  3. "div",
  4. null,
  5. "Hello ",
  6. props.name
  7. );
  8. };
  9. ReactDOM.render(React.createElement(MyComponent, { name: "doug" }), app);

Constructing a React component without calling React.createClass() is typically referred to as a stateless function component.

Stateless function components can’t be passed component options (i.e., render, componentWillUnmount, etc.). However .propTypes and .defaultProps can be set as properties on the function.

The code example below demonstrates a stateless function component making use of .propTypes and .defaultProps.

source code

Notes

  • Make as many of your components as possible, as stateless components.