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.

var MyComponent = function MyComponent(props) {
    return React.createElement(
        "div",
        null,
        "Hello ",
        props.name
    );
};

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.

results matching ""

    No results matching ""