ReactJS State and Local Variable
The timerID should not be state because it's not related to UI (when state changes page is re-rendered). If it's in state then page will re-render after every change in timerID value.
Is timerID in the assignment this.timerID = setInterval just a variable
Yes, timerID
is a variable returned by the setInterval function. It also is a normal property of class Clock ...
.
Why is this not a state?
Use timerID
in state
brings no benefits. It is only another place from state
to store a shared variable within your class. Storing it in state
only makes your state
bigger and more complex (which is harder to manage) since timerID
does not take place for the final view. Or more simpler, timerID
is not used within render
, so we don't need to put it in the state
.
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 timerID doesn't express the representation of the UI in any way.
- Updating the timerID shouldn't trigger a re-render.
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.
Well, you can store timerID
in state, but this is not a good practice, as you can
read in the same documentation page:
If you don't use something in render(), it shouldn't be in the state.
Every time that you update your state via setState
, render method is invoking. So if this data doesn't change UI, then calling render method doesn't change anything and it will be a waste.
That is why all the 'helper' data, such as API requests, e.t.c is better to store as component-object keys.