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
Top comments (0)