What is state?
This article was originally published at https://gist.github.com/joepie91/8c2cba6a3e6d19b275fdff62bef98311.
"State" is data that is associated with some part of a program, and that can be changed over time to change the behaviour of the program. It doesn't have to be changed by the user; it can be changed by anything in the program, and it can be any kind of data.
It's a bit of an abstract concept, so here's an example: say you have a button that increases a number by 1 every time you click it, and the (pseudo-)code looks something like this:
let counter = 0;
let increment = 1;
button.on("click", () => {
counter = counter + increment;
});
In this code, there are two bits of "state" involved:
- Whether the button is clicked: This bit of data - specifically, the change between "yes" and "no" - is what determines when to increase the counter. The example code doesn't interact with this data directly, but the callback is called whenever it changes from "no" to "yes" and back again.
- The current value of the counter: This bit of data is used to determine what the next value of the counter is going to be (the current value plus one), as well as what value to show on the screen.
Now, you may note that we also define an increment
variable, but that it isn't in the list of things that are "state"; this is because the increment
value never changes. It's just a static value (1
) that is always the same, even though it's stored in a variable. That means it's not state.
You'll also note that "whether the button is clicked" isn't stored in any variable we have access to, and that we can't access the "yes" or "no" value directly. This is an example of what we'll call invisible state - data that is state, but that we cannot see or access directly - it only exists "behind the scenes". Nevertheless, it still affects the behaviour of the code through the event handler callback that we've defined, and that means it's still state.