6

In React I have state variable name1. Is there any difference between. Is there any difference between

this.state.name1 = value;

And

this.setState({name : value});
Denis
  • 1,181
  • 2
  • 11
  • 18

4 Answers4

3

You will usually set the initial state like this:

this.state = {name1: value}

Then when you need to update it you will use setState:

this.setState(prevState => ({name1: newValue}));
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
0

Yes there is a difference it is two different variables in react application.

It is just like what in simple javascript file would be

var name = value;
var name1 = value;

So the setting state there on name by this.setState({name : value}); sets the state of variable (state) of name, where this.state.name1 = value; updates the value of name1

Tadas Stasiulionis
  • 1,316
  • 3
  • 16
  • 18
0
this.state.name1 = value;

The above code directly mutates your state which is not a good idea and causes a discrepancy in react change detection cycles.

this.setState({name : value});

The above doesn't mutate the state directly and is the proper approach to modify/alter your state.

In fact, you can also add a callback as the second argument to setState which will be executed after the state is changed. Example:

this.setState({name: value}, function() {
   // do something here after you have changed the state.
});
0

Yes there is a difference, your first statment is assigning the name1 property on the this.state object, and you should avoid it because there is a function "setState" (your second statment) which is done for this.

This function can take an object or another function which in turn take the previous state and give you the ability to return a new one (and in the same time accessing the previous state values which can be convenient)

// Used to set the initial state in the construcor
// (but in some case you don't need a constructor
// and can just add state = { } directly in your class.

this.state = {
  foo: bar
}


// Set a new state by merging the existing one and the object
// you pass in setState()

this.setState({
  name: value1
})


// Set a new state with a function instead of an object
// and give you the previous state to manipulate it
// Here for example we use the previousState to create the new one
// (if isTrue was true, it's now false)

this.setState(previousState => ({
    isTrue: !previousState.isTrue 
  })
)

Check the react documentation for more details !

Halkeand
  • 67
  • 1
  • 6