Read it in 11 Mins
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. To know more about usereducer hook in React, click here.
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.
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.
If you are writing a functional component and realize that you need to add a 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.
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.
We will learn more about the State and its usage later in this article, but here is the practical difference between the two:
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 a Prop:
A 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.
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!
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.
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>
)
}
}
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!
To learn more about setState() and its powers, head over to this official link.
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';
let link;
if (this.state.newTitle) {
link = <NewPageLink />;
} else {
link = <OldPageLink />;
}
return (
< div>
<Header ><LogoComponent /></Header>
<Main title={title}>
{link}
<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>
);
}
}
class OldPageLink extends React.Component {
render() {
return (
<div style={{margin:'20px'}} className="wrapper">
<a target="_blank" href= "http://www.facebook.com" > http: //www.facebook.com</a>
</div>
);
}
}
class NewPageLink extends React.Component {
render() {
return (
<div style={{ margin: '20px' }} className="wrapper">
<a target="_blank" href= "http://www.google.com" > http: //www.google.com</a>
</div>
);
}
}
class Header extends React.Component {
render() {
return (
<header>
{this.props.children}
</header>
);
}
}
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.
We hope you have found this article useful. Happy Learning!
Avail your free 1:1 mentorship session.