Rect.js Anti-patterns

Published:

Welcome

  1. For the most part, changing state directly without setState() is an antipattern and should be avoided.

It’s important to note that setState() updates only the states you pass to it (partially or merged, but not a complete replace). It doesn’t replace the entire state object each time. So, if you have three states and change one, the other two will remain unchanged. In the following example, userEmail and userId will remain intact:

constructor(props) {
super(props)
this.state = {
userName: 'Azat Mardan',
userEmail: 'hi@azat.co',
userId: 3967
}
}
updateValues() {
this.setState({userName: 'Azat'})
}

Keep in mind that setState() triggers render(). It works in most cases. In some edge-case scenarios where the code depends on external data, you can trigger a rerender with this.forceUpdate(). But this approach should be avoided as a bad practice, because relying on external data and not state makes components more fragile and depends on external factors (tight coupling).