5

Many time we send props in the constructor but we never use this.props anywhere in the constructor so why do need to pass that and when do need to do that.

 class App extends React.Component {

      constructor(props) {
        super(props);    // When do we need to send props to the constructor
        this.state = {
           data: 'Initial data...'
        }
        this.updateState = this.updateState.bind(this);
      };

      updateState(e) {
          this.setState({data: e.target.value});
      }

      render() {
        return (
           <div>
             <input type = "text" value = {this.state.data} 
              onChange = {this.updateState} />
             <h4>{this.state.data}</h4>
          </div>
        );
      }

   }
saprative
  • 371
  • 1
  • 3
  • 14

1 Answers1

6

Props aren't actually needed by the React.Component constructor. You can write this code and everything works just fine:

constructor() {
    super();
    this.state = {
       data: 'Initial data...'
    };
    this.updateState = this.updateState.bind(this);
  };

This is because the constructor path is not actually where your props get assigned in the standard React life cycle. React.Component does not actually use props and only sets this.props in case your constructor needs to use it. But usually you shouldn't be using props in your constructor anyway because using props to initialize your state is an anti-pattern

If you've configured babel, you don't even need a constructor for stuff like this:

class MyComponent extends React.Component {
    state = { data: "initial data" };

    updateState = (arg1, arg2) => { ... };

    // instead of:
    // updateState(arg1, arg2) { ... }

}
Brandon
  • 38,310
  • 8
  • 82
  • 87
  • Is replacing constructor() to set initial state with simple state = {} expression, considered a good practice when using ES2015? – jkulak Feb 25 '17 at 23:42