Hey, everyone, welcome to a new post in the React Js Series. Today, we'll learn all about React State. I suggest you read the previous articles on React Js components and props to get a better understanding of state.
So let’s begin and learn what exactly is a state in React Js.
In our previous post, we learned about props, and although props and state dictate and control the behavior of a component. They have significant differences. So let’s go ahead and read the comparison between the two.
Now that we’ve learned all about state, let’s go ahead and build an application to see the working of state. So in my code editor that is VS Code, I’ve created a application let say “My App”.
here in my source folder, I have my app.js
import logo from './logo.svg'; import './App.css'; function App() { return ( <div> <h1>React Js Tutorial</h1> </div> ); } export default App;
So let’s create a class component say Myclasscomp.js .Let’s display a message “Hello Student, welcome to React Js Tutorial”.
import React, { Component } from "react"; class Myclasscomp extends Component { render() { return <h2>Hello Student,welcome to React Js Tutorial </h2> } } export default Myclasscomp;
Let’s follow the JSX conventions and enclose all the HTML tag within the <div> tag.
import React, { Component } from "react"; class Myclasscomp extends Component { render() { return <div> <h2>Hello Student,welcome to React Js Tutorial</h2> </div> } } export default Myclasscomp;
I’m going to make use of a button ,Every time the user clicks on the button, the value gets incremented. So for this, I’m going to use a variable count and I’m going to use the concept of states. So let’s go ahead and define our variable count and initialize it to zero.
And as mentioned earlier, we initialize the state object in a constructor. Now, in the state object, we initialize a property.
let’s define the count variable, in the render method so every time we click on a button, the count value has to get incremented by 1.
so we make use of an event called onclick. So every time the button gets clicked, incrementcount method is called.
import React, { Component } from "react"; class Mycounter extends Component { constructor(props) { super(props); this.state = { counter: 0, }; } incrementcount = () => { this.setState({ counter : this.state.counter + 1 } )} render() { const { counter } = this.state; return <span><button onClick={this.incrementcount}>Touch Me-{counter} times</button></span> } } export default Mycounter;
and let’s see the browser.
Now a setstate can be updated in response to even handler and server responses or props changes. Now all the updates can be done using the setstate() method. This is a general trend that’s used by the method.
Thanks for reading