J
J
justifycontent2021-04-11 13:29:52
React
justifycontent, 2021-04-11 13:29:52

How does state and setState work internally?

There is a React code:

state = {
    activeItem: 0,
    test: 1
  }

  onSelectItem = i => {
    this.setState({
      activeItem: i,
    })
  }

How does it work from the inside? How does setState() change exactly this value in the state object? I would really appreciate an explanation, thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vItalIyIrtlach, 2021-04-11
@justifycontent

setState works in the following way:
it takes as input a function that returns a new state or a new state. Since state is an object then it does the following:
// ... - spread operator
state = {...state, ...newState} // since newState comes after state then it will overwrite all old values ​​with new ones or add new
https://learn.javascript.ru/rest-parameters-spread...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question