Ref: ReactJS documents page URL: https://facebook.github.io/react/docs/state-and-lifecycle.html
Is timerID in the assignment this.timerID = setInterval just a variable. Why is this not a state?
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() .
What Is 'State' in ReactJS? The state is a built-in React object that is used to contain data or information about the component. A component's state can change over time; whenever it changes, the component re-renders.
Local state is perhaps the easiest kind of state to manage in React, considering there are so many tools built into the core React library for managing it. useState is the first tool you should reach for to manage state in your components. It can take accept any valid data value, including primitive and object values.
You could have it be a state variable, but that wouldn't make much sense since the state is meant to hold variables that relate to the current state of the UI. Also, state variables are meant to trigger a re-render if they are updated (with setState()
).
Neither of these would make much sense for a timer ID to be stored in the state. In other words, it's not a state variable because:
The official docs actually mention this:
The state contains data specific to this component that may change over time. [...] If you don't use it in
render()
, it shouldn't be in the state. For example, you can put timer IDs directly on the instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With