Reduce state changes
State is the snapshot of your program at a specific time. It’s the name given to all your variables—primitives and objects—that can be observed in your program.
When you create a variable, you create a state for your program. The variables you create is stored in memory and can be used in the program anytime.
const myName = 'Zell'
console.log(myName) // Zell
When you change a variable, you change the state of your program. In the example below, when we assign Vincy
to myName
, we change the state of the program—myName
is no longer Zell
; henceforth, it’s Vincy
.
let myName = 'Zell'
console.log(myName) // Zell
myName = 'Vincy'
console.log(myName) // Vincy
Program state and function state
Functions can have state too—you can create variables in a function; and these variables can be changed. )
const sayName = name => {
name = name + ' Liew'
console.log(name)
}
sayName('Zell') // Zell Liew
Although functions can have state, we’re usually not concerned with the state in functions.
This is because variables declared in the functions are scoped to the function. These variables are discarded when JavaScript exits the function; they’re are not accessible anymore.
const someFunction = _ => {
const value = 'test'
console.log(value)
}
someFunction() // 'test'
console.log(value) // ReferenceError: value is not defined
That’s why, when we say state, we usually refer to the state of the program.
Websites always have a state
Websites always have a state. It doesn’t matter whether you wrote any JavaScript. The DOM, the window
object, and other variables that exist automatically gives a program a default state.
Should you change state?
Nothing happens if states don’t change; this means you need to change states for your program to function.
For example, when you change the class of an accordion (adding and removing .is-open
), you change the state of the accordion. The accordion is able to open and close because of this change in state.
Although state changes are required for programs to work, you should reduce state changes. This is because state changes are valid changes. They’re hard to detect. If you change states everywhere in your program, you make your program hard to debug.
How to reduce state changes
To reduce state changes, you prevent two things from happening:
- reassignments
- mutations
You’ll learn about reassignments and mutations in the following lessons.
Wrapping up
State is the snapshot of a program at a specific time. You need state changes for your programs to function, but you should reduce state changes because they can be difficult to debug.