Do I need to setState on the only property that changes?

this setstate this state
setstate in render
react setstate from props
react setstate async
react override setstate
react setstate callback
react setstate multiple properties
react native setstate

Let's say I have a Person class:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

And then I instantiate a Person object in the state:

export default class SomeComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      cena: new Person('John Cena', 40)
    }
  }

  render() {
    const { name, age } = this.state.cena;
    return (
      <div>
        <p>Name: {name}</p>
        <p>Age: {age}</p>
      </div>
    )
  }
}

Let's say we have a button that increments Cena's age by one. Is it safe to set the state with an entirely new Person object although we only need to change the age?

this.setState(prevState => ({
  cena: new Person(prevState.cena.name, prevState.cena.age + 1)
}));

I did test this with Chrome's paint flashing tool. When I set this.state.cena with a brand new Person with incremented age, only the Age paragraph gets repainted the Name paragraph stays intact.

However, I am still a bit concerned. Should I rely on React to handle efficient shallow comparison, or should I manually change only what's need to be changed?

I don't even know how I could achieve that. If I try to only setState the age, I still have to do something like:

this.setState(prevState => ({
  cena: { ...prevState, age: prevState.age + 1 }
}));

Which is exactly the same as creating a new Person through its constructor. To update only the age 'efficiently', I have to spread Person to the first level of the state.

constructor() {
  super();
  this.state = {
    ...new Person('John Cena', 40)
  }
}

Which is terrible because I might need to create another Person later on.

So, I'll rephrase my question: should I setState an entirely new object and rely on React to handle shallow comparison?


Should I rely on React to handle efficient shallow comparison, or should I manually change only what's need to be changed?

Whatever you pass into setState is merged with the current state. After that merge, if state has changed, React will rerender the components which use this state.

All three of your examples are functionally identical and you should use the one you find most readable.

In general, you can rely on this to be very performant. You can also get improved performance by using PureComponent and/or functional components where appropriate.

reactjs, Is it safe to set the state with an entirely new Person object although we only need to change the age? this.setState(prevState => ({ cena: new  if you only pass the property you're changing, it only updates that property and leaves the rest as it is. Also, changes to state happen asynchronously, so the state could be changing in the middle of the code where you're changing one property on the state object, and then calling setState. If you assign the current state or part of state that you're changing to another variable, you're essentially getting the value at that particular moment and ensuring that the changes you make to that


Your state will only live in the component (SomeComponent) unless it's sent back through a function property.

Why not go with your last proposed solution, spreading the new Person instance. If it seems odd, maybe try instantiating the class outside of the constructor.

Example:

let person = new Person('Name', 40);
this.state = {
  ...this.person,
};

console.log(this.state); // outputs the instance members

or

let person = new Person('Name', 40);
this.state = {
  person: this.person
};

console.log(this.state.person); // outputs the instance members

If your component state needs to store multiple Person instances, you could store them in an array:

let personA = new Person('A', 21);
let personB = new Person('B', 25);

this.state = {
  persons: [personA, personB]
}

And to update the person, treat the state as if it's immutable:

const persons = this.state.persons.slice() //copy the array
persons[1].name = 'C' //manipulate Person 'B' instance
this.setState({ persons }) //set the new state

Reactjs, setState() to update only a single property on an object (or can I?). need to make a new function for every field to handle changes to that  The scenario. I have a Component parent which creates passes a property to a child component. The Child component reacts according to the property received. In React the "only" proper way to change the state of a component is using the functions componentWillMount or componentDidMount and componentWillReceiveProps as far as I've seen (among others,


Generally, I would not create class object for storing state. I would just set the state as object for its simplicity:

this.state = {
  cena: {
    name: '',
    age: ''
  }
}

Now, I can change the state simply like this:

this.setState({
  cena: {
   ...this.state.cena,
   age: this.state.cena.age+1
  }
})

Is it better to update a specific property using setState(), or dump the , But what if state contains some properties that do not need to be updated? Is it better to only let setState to change players.score property when  Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).


Updating properties of an object in React state, Of course we will need to do some sort of clean-up. The most day, items: [] } }) }. So, we are changing day and items in one setState . There is  You can expect property b remains while you only put a in setState. While in Redux, if you only return a in the new state, don’t expect you can find b anymore. That means, you need to take care of the entire state object in Redux. That also means, you need to put all the specific logic in one place and can’t delegate to multiple handlers.


Progressive Web Apps with React: Create lightning fast web apps , Inside handleClick, we want to change our state. What setState does is to take the object passed in as an argument and merge it into the object with one property to setState, it'll change only that property, rather than overwriting the rest​). If you need to give the user the opportunity to input something or in some way change the variables the component is receiving as props, you’ll need setState. Whether you declare a Component as a function or a class, it must never modify its own props. All React Components must act like pure functions with respect to their props. This means functions that never try to change their inputs and always return the same result for the same inputs.


TypeScript Blueprints, setState({ foo: 42, bar: true }) instead. In most cases, you do not have to change all properties of the state. In such cases, you only have to specify the properties  While a React component can have initial state, the real power is in updating its state — after all, if we didn't need to update the state, the component shouldn't have any state. State is only reserved for data that changes in our component and is visible in the UI.