John Dough
John Dough

Reputation: 55

Not setting a properties in the state?

in all the tutorials that I have seen, the state properties are set to empty strings, arrays, ...etc so I assumed it's best practice.

So is it bad practice to set the state properties by the event handler ??

class Form extends Component {
  state = { };

  handleOptionChange = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    return (
      <div>
        <form>
          <label>
            <input
              type="radio"
              name="size"
              value="small"
              checked={this.state.size === "small"}
              onChange={this.handleOptionChange}
            />
            Small
          </label>
          <label>
            <input
              type="radio"
              name="size"
              value="large"
              checked={this.state.size === "large"}
              onChange={this.handleOptionChange}
            />
            Large
          </label>
        </form>
      </div>
    );
  }
}

export default Form;

the code works just fine and updates the state every time an input is selected.

Upvotes: 0

Views: 40

Answers (1)

helloitsjoe
helloitsjoe

Reputation: 6529

What you have written will work fine. It's considered best practice to set initial values in state for a few reasons:

  1. The component has a default value when it initializes
  2. Anyone reading the code knows what to expect for state properties (and their types)

    class Form extends Component {
      state = {
        size: 'small'
      }
      ...
    }
    

This will set this.state.size to 'small' by default. If you don't want a default value, it's good to set an empty value of the same type you expect that state property to have.

In other words, if you're expecting this.state.size to be a string but you don't want it to have a default value, state = { size: '' } will send the message 'this state has a size property, which we can expect to be a string'

Upvotes: 2

Related Questions