React and Stateless Function Components

Nov 15, 2015  

In React, components can be defined in various ways:

  • const Foo = React.createComponent({...}) → component Foo.
  • class Foo extends React.Component {...} → component Foo.
  • function Foo(props) {...} → stateless function component Foo.

The stateless function component can be used to produce very easily create stateless components which only implement a (pure) render() function:

const Hello = props => <div>Hello {}</div>;
ReactDOM.render (<Hello name='world' />, mountNode);

Since such components are intrinsically pure I was expecting that React would handle them as such, and that it would only call the function once when repeatedly calling ReactDOM.render with the same properties.

For now, this is not the case. Every rendering goes through the (implicit) render method call defined by the stateless function component. To test this, I’ve written this small piece of code:

const Hello = function (props) {
  return <div>Hello {}</div>;

describe ('React', () => {
  describe ('Stateless function component', () => {
    it ('calls render() even if props do not change', () => {
      Hello.renderCount = 0;
      ReactDOM.render (<Hello name='world' />, mountNode);
      expect (Hello.renderCount).to.equal (1);
      ReactDOM.render (<Hello name='world' />, mountNode);
      expect (StatelessHello.renderCount).to.equal (2);

The full source code for the test can be found on epsitec-sa/react-usage.

See pull request and relevant discussion on GitHub.