V
V
vetsnakara2019-07-21 18:39:02
JavaScript
vetsnakara, 2019-07-21 18:39:02

How to properly update the state of a component?

Let in the state of the component I have an array of users objects, where I want to add a new user. It's not entirely clear to me why you can't change state directly? And why, when executing setState(), make a copy of the users array, if only references to objects are copied to the new array anyway, and not the objects themselves? Just so that a reference to a new array appears in state and React detects the change?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-07-21
@vetsnakara

More than a dozen articles have been written about the advantages and disadvantages of using immutable data updates. The React library uses this concept to track changes to the state and properties of components.
It is for this.

R
Robur, 2019-07-22
@Robur

And why, when executing setState(), make a copy of the users array,

You don’t have to if you somehow let React know that the state has changed and you need to call render.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question