In React, what is the difference between setState and forceUpdate
reactjs
Solution
General about `setState()`
The `setState()` function is typically used to update the component state with one or more new state properties. This is the typical way of mutating your state and managing view updates.
From the official docs:
`setState()` enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state. This is the primary method you use to update the user interface in response to event handlers and server responses.
General about `forceUpdate()`
The `forceUpdate()` function is just a way to force a re-render of the component and its children in question. It does not mutate the state at all.
You should avoid to use this function, when possible, as it deviates from the React mindset where your state and props are solely responsible for keeping your application logic up-to-date with your view.
From the official 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()`.
Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`.
The differences
It's important to note that `forceUpdate()` will skip checking the logic in `shouldComponentUpdate()` (if you have any), where as `setState()` does not skip it.
An interesting note here is that the following 2 lines will always yield the same results:
this.setState(this.state);
this.forceUpdate();
...unless `shouldComponentUpdate()` can return `false` as explained above.
Other than the above, there is no functional difference between the two.
Problem
In a component that does not override shouldComponentUpdate, is there any difference between forceUpdate and setState? Update: I already know what the docs say and that forceUpdate is not the recommended way to do it. I am just trying to gain a deeper understanding of what is going on. I'd like to know why? And I already know that setState merges the passed object (state "delta" - kind of like an sql update) with the current state object. Suppose a simple use-case: no need for undo or time-travel functionality. No need to do pointer comparison inside shouldComponentUpdate. In fact, no need to use shouldComponentUpdate at all. In that case, it appears to me, that mutating state and calling forceUpdate() is a perfectly valid way to use React. From a black box perspective, these two techniques appear to have the exact same effect: Technique #1: this.state.x = 10; this.forceUpdate(); Technique #2: this.state.setState({x:10}); Again, I already know that some people prefer to never mutate state. And to use the functional programming style. I was just wondering if there is any technical reason to avoid Technique #1. Or am I missing something?