Learn React Now
  • Table of Content
  • Design Patterns and Techniques
    • Conditional in JSX
    • Async Nature Of setState()
    • Dependency Injection
    • Context Wrapper
    • Event Handlers
    • Flux Pattern
    • One Way Data Flow
    • Presentational vs Container
    • Third Party Integration
    • Passing Function To setState()
    • Decorators
    • Feature Flags
    • Component Switch
    • Reaching Into A Component
    • List Components
    • Format Text via Component
    • Share Tracking Logic
  • Anti-patterns
    • Introduction
    • Props In Initial State
    • findDOMNode()
    • Mixins
    • setState() in componentWillMount()
    • Mutating State
    • Using Indexes as Key
    • Spreading Props on DOM elements
  • Coding Styles
  • Handling UX Variations
    • Introduction
    • Composing UX Variations
    • Toggle UI Elements
    • HOC for Feature Toggles
    • HOC props proxy
    • Wrapper Components
    • Display Order Variations
  • Performance Tips
    • Introduction
    • shouldComponentUpdate() check
    • Using Pure Components
    • Using reselect
  • Styling
    • Introduction
    • Stateless UI Components
    • Styles Module
    • Style Functions
    • npm Modules
    • Base Component
    • Layout Component
    • Typography Component
    • HOC for Styling
  • Gotchas
    • Introduction
    • Pure render checks
    • Synthetic Events
    • Related Links
Powered by GitBook
On this page
  • Bad
  • Good
  • Related links:

Was this helpful?

  1. Anti-patterns

Mutating State

  • Causes state changes without making component re-render.

  • Whenever setState gets called in future, the mutated state gets applied.

Bad

class SampleComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: ['foo', 'bar']
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // BAD: We mutate state here
    this.state.items.push('lorem');

    this.setState({
      items: this.state.items
    });
  }

  render() {
    return (
      <div>
        {this.state.items.length}
        <button onClick={this.handleClick}>+</button>
      </div>
    )
  }
}

Good

class SampleComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: ['foo', 'bar']
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // We update using setState() - concat return new array after appending new item.
    this.setState(prevState => ({
      items: prevState.items.concat('lorem')
    }));
  }

  render() {
    return (
      <div>
        {this.state.items.length}
        <button onClick={this.handleClick}>+</button>
      </div>
    )
  }
}

Related links:

  • React Design Principles

  • React Design Patterns and best practices by Michele Bertoli.

  • 2019 ReactJS Best Practices

PrevioussetState() in componentWillMount()NextUsing Indexes as Key

Last updated 4 years ago

Was this helpful?