The Wayback Machine - http://web.archive.org/web/20220607150056/https://www.geeksforgeeks.org/reactjs-state-react/amp/

ReactJS | State in React

In the previous article on ReactJS | Components, we got to know that React Components can be broadly classified into Functional and Class Components. It is also seen that Functional Components are faster and much simpler than Class Components. The primary difference between the two is the availability of the State.
 

What is State?

The state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component. For example, let us think of the clock that we created in this article, we were calling the render() method every second explicitly, but React provides a better way to achieve the same result and that is by using State, storing the value of time as a member of the component’s state. We will look into this more elaborately later in the article.
 

Difference of Props and State.

We have already learned about Props and we got to know that Props are also objects that hold information to control the behavior of that particular component, sounds familiar to State indeed but props and states are nowhere near be same. Let us differentiate the two.
 



Now we have learned the basics of State and are able to differentiate it from Props. We have also seen a few places where we can use State now all that is left is to know about the basic conventions of using the React State before implementing one for ourselves.
Conventions of Using State in React: 
 

this.state.attribute = "new-value";
this.setState({attribute: "new-value"});
this.setState({counter: this.state.count + this.props.diff});
this.setState((prevState, props) => ({
  counter: prevState.count + props.diff
}));
this.setState(function(prevState, props){
    return {counter: prevState.count + props.diff};
});
this.state = {
darkTheme: False,
searchTerm: ''
};

After going through the article we should have a clear concept of State in React, but other than the constructor and render methods can we add user-defined functions as well? Yes, we can also create user-defined functions inside a class but how to call them? React provides a few special methods that are called at some proper context that solves this problem. We will see these special functions in the next article on the Lifecycle of a component.

For the implementation of the state go to the given link below:

Implementing state & Lifecycle.
 




Article Tags :