DEV Community

Lam Hoang
Lam Hoang

Posted on

1

React State Summary

Update state with setState, except in constructor

this.setState({
  title: 'Updated title',
});

Set state with previous state

this.setState((prevState, props) => {
  return {count: prevState.count + 1};
});

Declare initial state in constructor

class Heading extends React.Component {
  constructor(props) {
    super(props);
    this.state = {title: 'My title'};
  }
}

Do not update state directly

this.state.title = 'Hello';

Lifting state up to share state between component

class Wrapper extends React.Component {
  constructor(props) {
    super(props);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.state = {value: ''};
  }

  handleInputChange(value) {
    this.setState({value});
  }
  render() {
    const value = this.state.value;
    return (
        <Input value={value} onInputChange={this.handleInputChange} />
    );
  }
}

class Input extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onInputChange(e.target.value);
  }

  render() {
    const value = this.props.value;
    return <input value={value} onChange={this.handleChange} />;
  }
}

Source: React Cheat Sheet

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay