Skip to content Skip to sidebar Skip to footer

Reactjs - What Is Difference Between Component State And Class Variable?

I think it works differently but I don't know how it works. 1. Using class variable 2. Using React component state I think it doesn't need to re-render using State if it's only a

Solution 1:

The difference between the two is that React will re-render your component when state changes (with this.setState(/*...*/)).

If you update the class variable, React will be unaware of it and won't re-render your component.

Note that what you're achieving in your code requires neither state or class variable. You're simply computing another value directly from the props. A better way to write your component would be like this :

exportdefaultclassTestextendsComponent {
  render() {
    const active = this.props.name === 'Dan';
    return (
      <div>
        {active? 'ssup?' : 'noooo'}
      </div>
    );
  }
}

Solution 2:

The simple answer to your question is that by using state you call the setState() which automatically calls render() automatically. Which cannot be obtained by class variables

  • You use the `state variables` when you want to change the component when that variable is changed.
  • When you don't want to automatically call `render()` you use the `class` variables
  • Solution 3:

    React component only re-renders when there are changes to state or class. But updating class variable involves neither so it does not trigger render.

    Though using state may seem similar to class variable but state is a protected keyword in React that refers to stored component data. The major difference between using class variables and state is updating data. Instead of manually reassigning the variable, you call this.setState().

    When you call this.setState(). It compares this new state to the previous state. If there is a change, React re-renders the component, resulting in the updated count value displayed on the screen.

    But when you update class variable, it sure gets updated but does no re-render. You can do so using this.forceUpdate(). But Normally you should try to avoid all uses of forceUpdate() and only read from this.props and this.state in render().

    Refer to this article for detailed info.

    Post a Comment for "Reactjs - What Is Difference Between Component State And Class Variable?"