Mutating State without setState()

  • Causes state changes without making component re-render.
  • Whenever setState gets called in future, the mutated state gets applied.

Bad

  1. class SampleComponent extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. items: ['foo', 'bar']
  6. };
  7. this.handleClick = this.handleClick.bind(this);
  8. }
  9. handleClick() {
  10. // BAD: We mutate state here
  11. this.state.items.push('lorem');
  12. this.setState({
  13. items: this.state.items
  14. });
  15. }
  16. render() {
  17. return (
  18. <div>
  19. {this.state.items.length}
  20. <button onClick={this.handleClick}>+</button>
  21. </div>
  22. )
  23. }
  24. }

Good

  1. class SampleComponent extends Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = {
  5. items: ['foo', 'bar']
  6. };
  7. this.handleClick = this.handleClick.bind(this);
  8. }
  9. handleClick() {
  10. // We update using setState() - concat return new array after appending new item.
  11. this.setState({
  12. items: this.state.items.concat('lorem')
  13. });
  14. }
  15. render() {
  16. return (
  17. <div>
  18. {this.state.items.length}
  19. <button onClick={this.handleClick}>+</button>
  20. </div>
  21. )
  22. }
  23. }

React Design Patterns and best practices by Michele Bertoli.