gman gman - 16 days ago 5
Javascript Question

When is it safe to save state in React?

Let's say I have a react component that updates state from a form.

class Form extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
someCheckboxState: false,
}
}
render() {
return (
<input onChange={this.handleChange} checked={this.state.someCheckboxState} />
);
}
handleChange(event) {
this.setState({
someCheckboxState: event.target.checked,
});
}
}


Now I want to send that state to the server (or somewhere). If I just do this

handleChange(event) {
this.setState({
someCheckboxState: event.target.checked,
});
SendStateToServer(JSON.stringify(this.state)); // BAD! Not yet mutated
}


I could put it in
render
but then it will get sent to the server on initial render as well as well and it seems silly to send state a function called
render
.

When is it okay to persist/serialize the state?

Answer

You can put it in a callback:

handleChange(event) {
  this.setState({
    someCheckboxState: event.target.checked,
  }, () => {
    SendStateToServer(JSON.stringify(this.state));
  });
}
Comments