The primary way that you make UI updates to your React applications is through a call to the setState() function. This function will perform a shallow merge between the new state that you provide and the previous state, and will trigger a re-render of your component and all decedents.
1. updater: It can be an object with a number of key-value pairs that should be merged into the state or a function that returns such an object.
2. callback (optional): a function which will be executed after setState() has been executed successfully. Due to the fact that calls to setState() are not guaranteed by React to be atomic, this can sometimes be useful if you want to perform some action after you are positive that setState() has been executed successfully.
The setState method accepts an updater argument that can either be an object with a number of key-value-pairs that should be merged into the state, or a function that returns such an object computed from prevState and props.
Using setState() with an Object as updater
Using setState() with a Function as updater
This can be safer than using an object argument where multiple calls to setState() are used, as multiple calls may be batched together by React and executed at once, and is the preferred approach when using current props to set state.
These calls may be batched together by React using Object.assign(), resulting in the counter being incremented by 1 rather than 3.
The functional approach can also be used to move state setting logic outside of components. This allows for isolation and re-use of state logic.