In React, what is the difference between setState and forceUpdate

In a component that does not override shouldComponentUpdate, is there a difference between forceUpdate and setState?

Update: I already know what the docs say, and that forceUpdate is not recommended for this. I'm just trying to get a deeper understanding of what is happening. I would like to know why? And I already know that setState combines the passed object (state "delta" - sort of like updating sql) with the current state object.

Suppose a simple use case: there is no need for a cancel function or time. No need to do pointer comparisons inside shouldComponentUpdate. Actually, you should not use shouldComponentUpdate at all.

In this case, it seems to me that the mutating state and the calling force of Update () is a perfectly acceptable way to use React. From a black box perspective, these two methods have the same effect:

Technique No. 1: this.state.x = 10; this.forceUpdate ();

Technique No. 2: this.state.setState ({x: 10});

Again, I already know that some people prefer never to mutate a state. And use the style of functional programming. I'm just wondering if there are any technical reasons to avoid Technique No. 1. Or am I missing something?

+5
source share
1 answer

setState()

The setState() function is typically used to update the state of a component with one or more new state properties. This is a typical way to change state and manage updates.

From official docs:

setState() changes to the state of the component and tells React that this component and its children should be re-displayed using the updated state. This is the main method that you use to update the user. interface in response to event handlers and server responses.


forceUpdate()

The forceUpdate() function is just a way to force the re-rendering of a component and its children. He does not mutate the condition at all.

You should avoid using this feature whenever possible, as it differs from React thinking, where your state and details are solely responsible for ensuring that your application logic is relevant to your presentation.

From official docs:

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

Usually you should try to avoid using forceUpdate() and only read this.props and this.state in render() .


Differences

It is important to note that forceUpdate() will skip the logic check in shouldComponentUpdate() (if any), where setState() does not skip ..

It is interesting to note that the following two lines will always give the same results:

 this.setState(this.state); this.forceUpdate(); 

... if shouldComponentUpdate() cannot return false as described above.

In addition to the foregoing, there are no differences between the two functional differences.

+10
source

All Articles