The Development of Stateful Components in React

React.createClass()

var SayHello = createReactClass({
  getInitialState: function() {
    return {message: 'Hello!'};
  },

  handleClick: function() {
    alert(this.state.message);
  },

  render: function() {
    return (
      <button onClick={this.handleClick}>
        Say hello
      </button>
    );
  }
});
  • Old (es5)
  • Don't
  • Included for reference

ES6 Classes

class SayHello extends React.Component{
  constructor(props) {
    super(props);
    this.state = {message: 'Hello!'};
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
    console.log(this.state.message);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Say hello
      </button>
    );
  }
}
  1. You create state in the constructor with this.state = {}
  2. You have you have to bind this to methods or they can't see it
  3. This is all because we didn't have class fields then...

ES6 Classes (with Class Fields)

class SayHello extends React.Component {

  state = { message: 'Hello!' }

  handleClick = () => {
    console.log(this.state.message);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Say hello
      </button>
    );
  }
}
  1. Once we had class fields we could do away with the constructor
  2. We can use arrow functions which will auto-bind this, so that's easier too
  3. Don't have to use super

What's the modern way?

const { useState } = React;

function SayHello() {

  const [message, setMessage] = useState('Hello!'); //A 'hook'

  const handleClick = () => {
    setMessage('hi')
  };

  return (
    <>
      <p>{message}</p>
      <button onClick={handleClick}>
        Change Message
      </button>
    </>
  );
}
  • We no longer have to re-write our components into 'class-components' in order to use state!!!!!

The Development of Stateful Components in React

By James Sherry

The Development of Stateful Components in React

  • 835