ReactJS in Simple English — state

Johnny Lai
Analytics Vidhya
Published in
3 min readNov 5, 2020

What is state?

state is the property in your app. When the app is running, it changing the state according the business logic in order to fulfil the user requirement.

If you familiar with Java, state is something like private variable, we can’t edit it outside of the class which created it. They’re invisible to other class unless we explicitly pass to another class (or function component) and they’re called “props” there. Other class can edit the state only if we explicitly pass the function

Before React 16.8, state is only available in class component. Since then, function component have their own state use it via React hooks.

In this passage, we would focus on the state in class component. Please feel free to try the working example in the bottom of the page

  1. Initialize state
class App extends Component {
constructor (props) {
super(props);
this.state = {
car:
{ model: 'tesla modal-X', price: 50000 },

otherState: 'some other value'
};
}
}
export default App;

You can initialize the state either inside or outside the constructor, they’re same just different coding style.

class App extends Component {
state = {
car:
{ model: 'tesla modal-X', price: 50000 },

otherState: 'some other value'
};
}
export default App;

2. Passing state to other class / function

Let say we have a class call “Car”, we would like to pass state from class “App” to class “Car”
In the render() function of class “App”, we pass
this.state.car.price via price
this.state.car.model via model
this.switchCarHandler via clicked
* becoz we aren’t execute switchCarHandler() immediately, so without()

render() {
return (
<div className="App">
<div>
<p>
<Car
price={this.state.car.price}
model={this.state.car.model}
clicked={this.switchCarHandler}
></Car>
</p>
</div>
</div>
);
}

In the class “Car”
we access
this.state.car.price via this.props.price
this.state.car.model via this.props.model
this.switchCarHandler via this.props.clicked

import React, { Component } from "react";class Car extends Component {
render() {
console.log("[Persons.js] rendering...");
return (
<div>
<button onClick={this.props.clicked}>Switch Car</button>
<p>
{this.props.model} - ${this.props.price}
</p>
</div>
);
}
}
export default Car;

3. state is immutable

We don’t change the state, but replace it.

Consider the following example
We try to change the car object in state by trigger “switchCarHandler” via a button. In “switchCarHandler”, we update the value inside object directly.

//Not working exampleimport React, { Component } from 'react';
import './styles.css';
class App extends Component {
state = {
car: { model: "tesla modal-X", price: 50000 },
insuranceFee: 1000
};
switchCarHandler = () => {
this.state.car.modal = 'toyota';
};
render() {
return (
<div className="App">
<button onClick={this.switchCarHandler}>Switch Car</button>
<div>
<p>Spent {this.state.car.price} for my new car - {this.state.car.model}</p>
</div>
</div>
);
}
}
export default App;

This is not working because only setState() can trigger the render method. The correct way to update the state would be create and replace with another object

switchCarHandler = () => {
this.setState({
car: { model: "tesla modal-S", price: 40000 }
});
};

***notes: this.setState only replace the “car” object, it still keeps the insuranceFee***

4. setState() is asynchronous

It means the change of state may not available immediately, as a result the state value may not up to date
Let say we’re going to increase the price of the insurance fee by increasing 10% but this is our special customer so we provide 10% discount

Consider this example, at first we add 10% by calculateInsuranceFee function and then we provide 10% discount by calculateDiscount function. If the original fee is 1000, then

1000* 1.1 * 0.9 = 990

However, we got 900 only, because we’re referring to this.state.insuranceFee in both function. As mentioned, React not guarantee that is up to date, so in this case React probably ignored the result of calculateInsuranceFee and calculated the discount with the original value — 1000, 1000*0.9, so the result is 900

//Not working examplestate = {
car: { model: "tesla modal-X", price: 50000 },
insuranceFee: 1000
};
calculateInsuranceFee = () => {
this.setState({ insuranceFee: this.state.insuranceFee * 1.1 });
};
calculateDiscount = () => {
this.setState({ insuranceFee: this.state.insuranceFee * 0.9 });
};
increasePriceHandler = () => {
this.calculateInsuranceFee();
this.calculateDiscount();
};

In order to solve this problem , React provide another form of setState()

calcInsuranceFee() {
this.setState((state) => {
return { insuranceFee: state.insuranceFee * 1.1 };
});
}
calcDiscount() {
this.setState((state) => {
return { insuranceFee: state.insuranceFee * 0.9 };
});
}
increasePriceHandler = () => {
this.calculateInsuranceFee();
this.calculateDiscount();
};

Problem fixed, it would output 990 instead of 900

Try the working code, for the above examples

--

--