Home > Software design >  How state updates merge in React hooks?
How state updates merge in React hooks?

Time:01-24

Will react merge the state updates for hooks too, like it does for setState

    state={count:0}  
  
    increment = () => {
    this.setState({count: this.state.count 1})
    this.setState({count: this.state.count 2})
    }

In Class component, the last setState action will be taken into consideration.Since the state updates are shallow merged.

When you call setState(), React merges the object you provide into the current state.The merging is shallow.

Object.assign(
    {},
    {count: this.state.count 1},
    {count: this.state.count 2}
)

the final result will be state = {count: 2}

In functional component ,

const [count,setCount] = useState(0)

const increment = () => {
    setCount(count 1)
    setCount(count 2)
}

The result is same as Class component count = 2.

Does setCount in useState hook will behave the same as setState?, Will setCount(count 1) ever execute?

CodePudding user response:

Its not true what you state here:

"In Class component, the last setState action will be taken into consideration. Since the state updates are shallow merged.".

Same goes for your example with Object.assign.

The "merge" mentioned in React docs is related to merging with current state, for example:

state = { count: 0, name: 'Dennis' }

// Merged with this.state, the 'name' attribute is not removed
this.setState({count: this.state.count 1})

// the state now is { count: 1, name: 'Dennis' }

While same code, won't work with function component, since its different API, as mentioned in the docs, it doesn't merge.

const [state,setState] = useState({ count: 0, name: 'Dennis' })

// NO MERGE, you assign a new object
setState({count: state.count 1})

// the state now is { count: 1 }

Therefore, asking if the "setState call ever execute" is not related to class / function component, its a matter if the set state call is batched or not.

Does setCount in useState hook will behave the same as setState?, Will setCount(count 1) ever execute?

If the calls don't batch, the first call will be executed.

When set state calls are batched? See here.

  •  Tags:  
  • Related