Reactjs - What Is Difference Between Component State And Class Variable?
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
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?"