javascript - Using forceUpdate instead of setState in React? - Stack Overflow

If I have a react ponent, and I just set its class variables, ieclass MyComponent extends React.Compon

If I have a react ponent, 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?

If I have a react ponent, 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?

Share Improve this question edited Jul 12, 2020 at 18:20 norbitrial 15.2k10 gold badges39 silver badges64 bronze badges asked Mar 3, 2018 at 18:19 Shai UIShai UI 52k77 gold badges218 silver badges316 bronze badges 2
  • Yeah it's bad practise, there is a reason why lifecyle events and setState / props are there. If you need to use forceUpdate then it indicates that you are doing something wrong, imho – Icepickle Commented Mar 3, 2018 at 19:15
  • This might throw more light on it stackoverflow./questions/47237556/… – Shubham Khatri Commented Mar 3, 2018 at 19:28
Add a ment  | 

1 Answer 1

Reset to default 4

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

From the docs:

By default, when your ponent’s state or props change, your ponent will re-render. If your render() method depends on some other data, you can tell React that the ponent 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 remended 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().

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745357321a4624196.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信