State makes React powerful

State makes React powerful

·May 13, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

The heart of React - that's the state. It is an object which makes your component active and dynamic. This post will improve or build your understanding of this abstract topic for the most developer. As always, let's dive in!

I am gonna take in mind that you already know what are props - if no check my series (What the React), since the best way to understand the state is by comparing it to props.

It is an object passed to a component by its parent component. It can be used with all kinds of componentsIt is an object which is directly initialized and managed by the component where it is created. The state is possible inside a stateful component(class). However, hooks male it possible to defined and manage state in any kinds of components.

Both state and props are the most important features of React component, and they're the only ones that can trigger re-rendering of the page content.

How to implement and use state in Class Components?

import React form 'react'; 
class Bapp etends React.componentt {
    // when we use class component we need to extend React.comp...
    // this gived us access to the lifecycle method like render()

    state = { // we just assign state to an object
      btClicked: false, 
      justNum: '5', 
      justSth: [23, 12, 79]
    clickHandler = () => {// invoked on button click
     this.setState(( state, props) => ({btnClicked: true}) ); 
     // the proper way we change state. (NEVER STATE.PROP = X)
     // thi is going to trigger a page re-render

     // the way we access state. we can also access its properties this way: this.state.just Numb (5)
    render () => {
        <button onClick={this.clickHandler}>Blah Blah </button>

export default Bapp; 
// on clicking the button, the state is going to change which triggers a content re-render.

Thank You for Reading 🤩

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
Share this