What Is React-js State?

10K

You must have already learned about the basic building block of any React application which is a Component

A component represents a feature that may be made up of several smaller components. Components can be broadly classified into functional or class components.

Components may take in some values as properties (prop) to render a page. These props decide how to render a page.

function Welcome(props) {
return < h1 >Hello, {props.name}</h1>;
}

In addition to props, a component can also have a state that holds a value that can keep a track of all the information within a component.

In this article, we will focus mainly on what is State, how we can define and utilize State and how components can use it in data management.

Defining React State

So what exactly is state? What is it used for?

State represents a component’s underlying data model and is rendered by the component. But more importantly, whenever data in the state changes, it causes the component to re-render to reflect the change. This facilitates declarative programming where you can simply manipulate state; while React takes care of implementing updates to ensure your component reflects the data in the State accurately.

In Class component we can use State as follows:

class Welcome extends React.Component {
constructor() {
super();
// Space To define the state
this.state = {
isDisabled: false,
totalCost: 0,
products: []
}
}
// To Define render method
} 

We can also use state in Functional components using the useState Hook. Hooks are a new addition in React 16.8 which let us use State and other React features in functional components.

When should I use a Hook?

If you are writing a functional component and realize that you need to add State to it, the only option previously was to convert it to a class. Now you can use a Hook inside the existing function component.

For this, you can directly read the React documentation of Hooks here.

In this article, we will mainly focus on “what is a State” and how is it different from Props.

Difference of Props and State

Most of the developers who are new to React often think about when to use State and when to use a Prop. Let’s understand this dilemma with an example.

A React component is akin to a JavaScript function.  A State can only be utilized in class components natively and is quite similar to a Prop, with the only exception that it is fully private, which means it can only be fully controlled and accessed by a component. In functional components, you have to opt-in to the useState hook to include stateful features.

Props, on the other hand, allow you to reuse the component by giving it an ability to receive data as input from the parent component.

A fictional example of Using a State:

class MyComponent extends React.Component {
state = {
name: 'Tom'  //defining the name property inside component state
}
render() {
return <div>Hello {this.state.name}</div>;
}
}  

Here, we can use the state ‘name’ anywhere in the component named “MyComponent” with the value ‘Tom’, or we can assign a new state also in the same component.

And, Using Prop:

Prop is a short name for properties. React is nothing without a Prop. Earlier we saw an example where we used the same data over and over again, but what if we have a scenario where we need the same component but not the same data? For example, I might want the theme component, but instead of a dark theme, I would like to use a light theme!

What I mean here is that basically, I want to re-use “MyComponent” again, but not the data defined in it. This is where Props will come in useful; in cases when we want to change the content inside the reusable component.

class ThemeProvider extends React.Component {
render() {
return <div>Current theme is {this.props.theme}</div>;
}

}
// when re-using the component with differnt data
<ThemeProvider name="Light" />
<ThemeProvider name="Dark" />         

It’s absolutely fine if you are not familiar with this code snippet. The idea is to understand when to use state or prop, and not the code as of now!

For now, just know that Prop is just a state, which is passed from parent to child. And because props can’t change their value in the child component, they take the help of an event listener or callback function in the parent component.

Now let’s quickly jump into the basics of a State.

Creating the State Object

React component has a built-in state object.

Before you think that state is a very simple concept, let me stop you right there!

It’s not!

You should not forget the data flow in React! In React there is a uni-direction flow of data, which is from parent to child. This can be a bit confusing, in that different components will never know what is changing in their component and when. Besides, they might be unaware of whether a component is stateless or stateful.

This is why the state is usually said to be encapsulated or having a local scope.

This is why the state is usually said to be encapsulated or having a local scope.

And therefore, you initialize the state in the class component by simply using a constructor.

Inside the Constructor

To declare a local state in the component, we can use a constructor as follows:

class Welcome extends React.Component {
constructor() {
super();
this.state = {
name: 'Michael Jackson',
currentTimer: 0,
hasPicked: false,
themeRed: false,
todoList: []
}
}
render() {
return <p>My name is {this.state.name}</p>;
}
}    

And the output or the result of the above < p> tag will be rendered as:

Hello, my name is Michael Jackson

However, this was the older convention of declaring a state. We can also declare a state without the ‘constructor’ and ‘super’ keywords with the help of Property Initializer which came in 2017.

Wait, what is Property Initializer?

If you have a lot of code, it becomes harder to understand what is what. And if there are any arguments in the constructor, then it becomes an extra overhead to keep track of all of them.

Therefore, the idea behind using an Initializer is to use a cleaner ES6 component, by assigning an arrow function to a property that will act like a normal method. In other words, it can also be termed as class field syntax.

Without the Constructor

Take a look at the representation below:

class Welcome extends React.Component {
state = {
name: 'Michael Jackson'
}
}
render() {
…
}
}  

In the following example, we have added a state to the “Welcome” component.

Let’s see how we can consume the data from the object  not outside the component, but within it!

Rendering data from state

A state is either initialized in the constructor or by using the class fields syntax to directly initialize it in a class component. Now let’s see how we can consume the state from the component in the render.

A point to note here while using state is we use “this.state” to get the value of the name property and it can be accessed in the render() method as follows:

~~~Wrong Approach~~~
class Welcome extends React.Component {
constructor() {
super();
this.state = {
name: 'Michael Jackson'
}
}
render() {
const { name } = this.state
return < h1 >My name is {name}</h1>;
}
} 

or an alternative to the above is:

~~~Right Approach~~~
class Welcome extends React.Component {
constructor() {
super();
this.state = {
name: 'Michael Jackson'
}
}
render() {
return < h1 >My name is { this.state.name }</h1>;
}
} 

The only difference in both is that in the first snippet I used State as:

const { name } = this.state

But we have already initialized the state in the constructor, why should we do it again?

We should not reassign it, and hence we should never update the component state directly.

A state should always be accessed using this.state.propertyName.

Updating the State

So far, we have seen how to create state and use state in the component.

Now let’s understand why and how to update state and what happens after updating a state.

A state can’t be changed directly and the only permissible way of updating it is by using setState as follows:

this.state.site = "Welcome"; // wrong implementation

this.setState({ // correct implementation
site: "Welcome"
});

// Or
this.setState((prevState, props) => ({ site: "Welcome" })))  

The setState( ) method makes the component re-render; and hence when a state changes the component re-renders and updates the changes.

Each time setState is called, it sends a request to React to update and re-render and give it back a newly updated state.

Let’s understand this with an example:

Let’s suppose we have a component and want to change the name in the component with a method called handleNameChange(). It should look as follows:

handleNameChange(name) {
this.setState({ name })
}  

The above method receives an argument and it uses that argument to update the state.

Component Demo to update a state should look as follows:

class App extends React.Component {
constructor() {
super()
this.state = { name: 'Michael Jackson' }
}
handleNameChange(name) {
this.setState({ name })
}
render() {
const { name } = this.state
return (
<div>
< div>
< input
type="text"
value={this.state.name}
onChange={event => this.handleNameChange(event.target.value)}
/>
</ div>
<p>My name is, {name}</p>
</ div>
)
}
}  

When is setState asynchronous?

React doesn’t have just one job to do, or only one component to observe for. It is possible that different components will be asking for different updates and DOM manipulations at the same time, hence the state updates are merged!

When setState() is called, React merges the object provided into the current state object.

For example, if we have different variables in our state like this:

constructor(props) {
super(props);
this.state = {
likes: [],
names: []
};
}  

And both states can be independently updated by using setState() calls as follow:

componentDidMount() {
fetchLikes().then(response => {
this.setState({
likes: response.likes
});
});

fetchNames().then(response => {
this.setState({
names: response.names
});
});
}  

Here we are calling multiple setState during one update cycle, so this.setState({names}) will leave this.state.likes unmarked but will completely replace this.state.names.

Hence you will not get the recently updated data in {names} and previous changes will be lost.

A quick fix to the above problem is as follows: Instead of giving a new state directly we can provide a function that can automatically provide the current state into a new state. There are two approaches to this:

// Method #1
this.setState({ foo: this.state.counter + 1 }, this.anyCallback);  

Or

// Method #2
this.setState((prevState) => { return { counter: prevState.counterfoo + 1 } }, this.anyCallback);  

The main difference is that in example #1, the counter gets incremented by 1 based on the state at the time when you have called the setState() method, whereas

In the example-2, the counter will be incremented by 1 only depending on the value that the previous state had while the arrow function was called.

So if we have multiple setState() which happen at the same time before the actual state update, it is possible that they may conflict or have outdated state data, but if we go with approach #2 they are guaranteed to have the most recent updated state because they update synchronously!

Bonus Section:

Changing Title on Click Example Using State

So far you have understood how to use State in React and what are the basic principles that define when to use State and when to use Prop. Here is a simple Demo for using State in a component and using Props to reuse the component.

Try this code to understand the power of State and reusable components.

let imgLogo = 'https://apod.nasa.gov/apod/image/2009/CrabNebula_Hubble_960.jpg';

class BonusExample extends React.Component {
constructor() {
super();
this.state = {
newTitle: false
};
this.changeTitle = this.changeTitle.bind(this);
}
changeTitle() {
this.setState({
newTitle: !this.state.newTitle
});
}
render() {
let title = this.state.newTitle ? 'Here is my New Title - Google Page' : 'Here is my Old Title - Facebook Page';
if (this.state.newTitle) {
} else {
}
return (
< div>
<Main title={title}>
<div className=" wrapper">
< button style={{ margin: '20px' }} type="button" className="btn btn-primary" onClick={this.changeTitle}>Change Name</button>
</div>
</Main>
<Footer>< HelperComponent /></Footer>
</div>
);
}
}

render() {
return (
<div style={{margin:'20px'}} className="wrapper">
</div>
);
}
}

render() {
return (
<div style={{ margin: '20px' }} className="wrapper">
</div>
);
}
}

render() {
return (
{this.props.children}
);
}
}

class Main extends React.Component {
render() {
return (
<div>
<h 1>{this.props.title}</h1>
{this.props.children}
</div>
);
}
}

class Footer extends React.Component {
render() {
return (
<footer>
{this.props.children}
</footer>
);
}
}

class LogoComponent extends React.Component {
render() {
return (
<img width="150px" src={imgLogo} />
);
}
}

class HelperComponent extends React.Component {
render() {
return (
<p>Changing the title from one to Another</p>
);
}
}

ReactDOM.render(<BonusExample />, document.getElementById('example'));  

Conclusion

I hope you have understood the concept of State and its usage. We have learned the basic difference between State and Props and when each should be used. We have also understood the data flow in a React component and how to consume and update a State object in React.

Now that you have understood all the fundamentals of State, there are some high-level pointers that you should always keep in mind while using a State.

• State is private to a component
• State Updates have shallow merging
• You should never modify a State Directly
• Updates in a State may Be asynchronous
• State is only used when you want to change component data

KnowledgeHut

Author

KnowledgeHut is an outcome-focused global ed-tech company. We help organizations and professionals unlock excellence through skills development. We offer training solutions under the people and process, data science, full-stack development, cybersecurity, future technologies and digital transformation verticals.
Website : https://www.knowledgehut.com

Join the Discussion

SPECIAL OFFER Upto 20% off on all courses
Enrol Now

Full Stack Development – the Hottest Developer Skill for the Digital Age

With over 1.7 billion websites worldwide and 4.54 billion people using the internet actively, the need for heightened customer experience is on the rise. This is one of the major reasons why professionals who are adept at handling both the client-side and server-side interfaces of an application/website have become more important than ever. It has been estimated that by the next decade, there will be 300,000 new developer jobs in US. The Full Stack developer role is the No.1 position to be filled in 2020 according to 38% of hiring managers. This is closely followed by the role of a back-end developer.Handsome pay packagesThe average annual salary for a full-stack developer is about $110,737 per annum. Even beginners are offered about$58,000 per year and on the other hand, experienced professionals would earn up to \$188,253 per year.These professionals are paid handsomely because enterprises are aware that a full stack developer does the job of two professionals (back-end and front-end developer).Plenty of growth opportunitiesAs per reports by The United States Bureau of Labor Statistics, full-stack development job opportunities will increase from 135,000 to 853,000 by the year 2024. This is quite promising for aspiring full stack developers as an ocean of opportunities will be available for them in both startups as well as in multi-national organizations.Skills to become a Full Stack developerBecoming a full-fledged full stack developer is not child’s play. It takes a wide range of skills to become a good full stack developer. Below are the mandatory skills:Front-end skills: They should be well-versed with basic front-end technologies like HTML5, CSS3, and JavaScript. They should also be comfortable working with front-end frameworks or third-party libraries such as JQuery, SASS, and AngularJS.Programming languages: They should be aces in at least one server-side coding language like Java, Python, Ruby or .Net.Databases: They should be efficient at handling data from databases like MySQL, MongoDB, Redis, Oracle and SQLServer.Version control systems (VCS): Full stack developers must be aware of Git so that they can make appropriate changes to the codebase.Basic design skills: Awareness about the basic prototype design and UI/UX design is essential to become a successful full stack developer.Server and API: They should have adequate exposure to Apache or Linux servers as well as web services.The way forward for Full Stack developersThe growing demand for full-stack developers is due to the ample benefits they offer to organizations. With technology evolving at a rapid pace, foresighted companies will keep adding them to their workforces. Full stack development became the No.1 developer skill because these developers are trained to multi-task various technologies and products. For aspiring full stack developers out there, now is the best time to make the most of these opportunities.Real products require real challenges. Check out our live online workshops and build your portfolio of projects.
4858
Full Stack Development – the Hottest Develop...

With over 1.7 billion websites worldwide and 4.54 ... Read More