Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS State and Local Variable

Tags:

reactjs

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?

like image 476
Saptadeep Avatar asked Sep 07 '17 10:09

Saptadeep


People also ask

What is difference between state and variable in react JS?

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 a state variable in React?

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.

What is local state in React?

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.


1 Answers

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:

  1. The timerID doesn't express the representation of the UI in any way.
  2. 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.

like image 75
Chris Avatar answered Sep 28 '22 00:09

Chris