DEV Community

Alan Montgomery
Alan Montgomery

Posted on

Understanding states in ReactJS

Hi there - this is my first post and it's aimed at beginners to get an insight into the states in components.

In ReactJS it's very useful to use the state in a component.

We would first declare and initiate our state in our constructor e.g;

constructor() {

    this.state = ({ Manipulated: false });
}
Enter fullscreen mode Exit fullscreen mode

If we had a further function or piece of code that needed to alter or update the state of a component then we would use the setState e.g;

componentWillReceiveProps(NewProps) {

    var MyBool = NewProps.ManipulativeBool;
    this.setState({ Manipulated: MyBool });
}
Enter fullscreen mode Exit fullscreen mode

The setState will also trigger a re-render of any DOM elements that will be affected by this state variable.

The states in a component then become very useful when we are rendering our content in the render method to determine what to do based on certain criteria like this;

render() {

    var Manipulated = this.state.Manipulated;

    return (
        {Manipulated === true ? <p>Our state has been manipulated!</p> : <p>Our state is still false</p>}
    );
}
Enter fullscreen mode Exit fullscreen mode

In this simple example we will output and render different content based on the state of the Manipulated Boolean we have set up.

If the Boolean is true then only then will it render and allow our content Our state has been manipulated to successfully be rendered and shown. And in other cases it will remain as Our state is still false.

This is just an insight into the powerful functionality you can have by using states in ReactJS and hopefully this is a short little trick for people who are just beginning.

Top comments (3)

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Thanks for the post Alan, it was easy to digest ๐Ÿ™‚

For code snippets, you can wrap'em using triple backticks around the code for syntax highlighting.

demo

Code ๐Ÿ‘† will show code like ๐Ÿ‘‡

componentWillReceiveProps(NewProps) {
  var MyBool = NewProps.ManipulativeBool;
  this.setState({ Manipulated: MyBool });
}
Collapse
 
93alan profile image
Alan Montgomery • Edited

Thank you so much - Really loving this community. It's awesome.

Ah that makes life a lot easier haha. I'll edit my post to reflect this now as well and remember for the future ๐Ÿ˜„

Collapse
 
dance2die profile image
Sung M. Kim

You're welcome & thank you for updating the post~

And.. ๐Ÿ‘‹ Welcome to dev.to, Alan ๐Ÿ™‚