React state – Learn everything about react state

The react state is an instance of React Component Class can be defined as an object of a set of observable properties that control the behaviour of the component. In other words, the react State of a component is an object that holds some information that may change over the lifetime of the component. In simple word, The state object is where you store property values that belongs to the component. When the react state object changes, the component re-renders.

Define State

The following sample code shows how to create a stateful component using EcmaScript2016 syntax.

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
		
      this.state = {
         header: "Header content...",
         body: "body content"
      }
   }
   render() {
      return (
         <div>
            <h1>{this.state.header}</h1>
            <h2>{this.state.body}</h2>
         </div>
      );
   }
}
export default App;

Changing the state Object

To change a value in the state object, use the this.setState() method.

When a value in the state object changes, the component will re-render, meaning that the output will change according to the new value(s).

import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
		
      this.state = {
         header: "Header content...",
         body: "body content",
         count: 1
      }
   }
   
   changeData() {
      this.setState({
         header: "Header content changed at " + (new Date()).toString(),
         body: "body content changed at " + (new Date()).toString(),
         count : this.state.count + 0
      });
   }

   render() {
      return (
         <div>
            <h1>Changed {this.state.count} times</h1>
            <h1>{this.state.header}</h1>
            <h2>{this.state.body}</h2>
            <button onClick={this.changeData}>Change</button>
         </div>
      );
   }
}
export default App;

Now due to asynchronous processing, this.state.count may produce an undesirable result. A more appropriate approach would be to use the following.

this.setState((prevState, props) => ({
  count : prevState.count + 1
}));

Setting Callback

ThesetState method takes a callback as its second argument. Since setState works in an asynchronous way. That means after calling setState the this.state variable is not immediately changed. so if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful

this.setState({
	header: "Header content changed at " + (new Date()).toString(),
	body: "body content changed at " + (new Date()).toString(),
	count : this.state.count + 1
}, 
() => {
	console.log(this.state)	
});

When this callback fires, this.state is the updated state.

Running the App

Run application using npm start. Congrats!! See, it was easy.

Preview

9 Comments

  1. créditos personales said:

    ¿Necesita urgentemente un préstamo en efectivo? Consulte préstamos grandes y pequeños en línea y obtenga un préstamo rápido para aquellos que están endeudados y más. http://creditospersonalesvtgi.es/

    January 6, 2021
    Reply
  2. erectile dysfunction pills said:

    Thank you for every one of your hard work on this web page. My aunt really loves making time for investigations and it’s really obvious why. Most of us learn all of the lively mode you offer priceless suggestions through this web site and even increase participation from some other people on the matter so our favorite girl is now starting to learn a lot of things. Take advantage of the rest of the year. You are always doing a remarkable job. https://hierectiledysfunctionout.com/

    January 7, 2021
    Reply
  3. vardenafil tablets said:

    A lot of thanks for each of your hard work on this website. My mum take interest in setting aside time for research and it is simple to grasp why. We notice all relating to the powerful way you provide very helpful tips and hints via your website and therefore strongly encourage response from visitors on this subject matter while our own simple princess is without a doubt studying so much. Take pleasure in the rest of the year. Your performing a tremendous job. https://joneslawncarela.com/

    January 7, 2021
    Reply
  4. geodon said:

    My husband and i felt now excited Emmanuel could conclude his inquiry from your ideas he gained in your site. It’s not at all simplistic just to choose to be giving for free ideas that most people have been making money from. And we all do understand we have the website owner to be grateful to because of that. The explanations you’ve made, the easy site menu, the friendships you can give support to engender – it’s everything extraordinary, and it’s facilitating our son and our family feel that that idea is cool, and that is highly important. Many thanks for all the pieces! https://geodonziprasidone.com/

    January 8, 2021
    Reply
  5. generic pamelor said:

    I’m also commenting to let you be aware of of the brilliant discovery my child encountered checking the blog. She came to understand a lot of details, including how it is like to have a marvelous coaching character to get folks completely fully grasp a variety of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel. https://pamelornortriptyline.com/

    January 9, 2021
    Reply
  6. doxepin generic said:

    I simply wanted to thank you so much once more. I am not sure the things that I would’ve made to happen without the type of smart ideas revealed by you over that situation. It seemed to be an absolute hard issue in my opinion, however , seeing the very specialised strategy you resolved that made me to leap over gladness. I am just happy for this information and then pray you realize what a great job you happen to be providing teaching people today thru your web page. More than likely you have never got to know any of us. https://sinequandoxepin.com/#

    January 10, 2021
    Reply
  7. https://www.vfv79.com/ said:

    Plus, there’s a built-in social sharing option. Commenters can check a box to also post on Facebook, which allows them to quickly share your post to their Facebook audience while commenting.
    Facebook Comments are great for blogs where people won’t mind being publicly linked to their comments. On the other hand, people may be less likely to comment with their photo and profile link on blogs that cover more personal topics.
    카지노사이트

    January 19, 2021
    Reply
  8. https://txt2080.com/ said:

    This comment system requires comment authors to create an account with Disqus via email or their Facebook, Twitter or Google+ profiles. Once someone creates an account, they can use it on any website with the Disqus comment system.
    Whenever someone leaves a comment using Disqus, they will get notified via email each time the blog post gets a new comment, when someone likes their comment and when they get a direct reply from someone. This is a great reminder for them to return to the discussion and your website. Disqus users can also tag specific people in a comment.
    카지노

    January 19, 2021
    Reply
  9. https://liveone9.com/woori/ said:

    Plus, if someone wants to follow a conversation, they can subscribe to the comments of a blog post with or without commenting. Visitors can also share a particular discussion or the post on Twitter and Facebook, as well as flag comments they feel are inappropriate to help moderators find and remove them.
    Business bloggers will love the advanced capabilities Disqus has to offer. Enable Disqus to publish comments, hold them all for moderation or allow only those with verified emails to be published. Set up additional moderators to login and moderate comments. Also, get analytics for all of your comments, information about specific commenters and much more.
    우리카지노

    January 19, 2021
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *