Shai UI
Shai UI

Reputation: 51918

Using forceUpdate instead of setState in React?

If I have a react component, and I just set its class variables, ie

class MyComponent extends React.Component {

    constructor(props) {
      super(props);
      this.numberElements = 20;
      this.color = 'red';
    }

    render() { 
       ...
    }
}

Can't I just call this.forceUpdate() to issue a re-render (whenever I update my class variables) instead of maintaining a state and calling setState?. Or is it bad to do that, and if so, why?

Upvotes: 4

Views: 6866

Answers (1)

Oro
Oro

Reputation: 1867

forceUpdate() is actually useful in scenarios like the one you're describing.

From the docs:

By default, when your component’s state or props change, your component will re-render. If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate().

The caveat, however, is that it will skip shouldComponentUpdate(), so you're not getting the optimization benefit.

Also, using forceUpdate() "bypasses" the proper lifecycle, making your code less straight-forward and possibly harder to understand and maintain.

It is therefore recommended to use state and props when possible.

Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

Upvotes: 4

Related Questions