Skip to main content
Version: v1.4

📓 3.1.1.6 State

In the last lesson, we used a variable called state to represent a creature's current properties. That wasn't a coincidence — state is an extremely important concept in programming, and it's worth taking a moment to understand what it actually means.

In simple terms, state is anything we're asking a computer to remember. We can think of it as a "snapshot" of the application at a given moment. It captures the current conditions: what data exists, what's been changed, what's been calculated so far.

When we used object-oriented programming, we created stateful objects with constructors and updated them with methods. In other words, we regularly mutated state — we changed things in place. A Plant object had a water property, and calling hydrate() would directly change it.

Functional programming takes a different approach. Where possible, our functions should be pure and avoid side effects. We aim to keep our application as immutable as we can — sometimes described as making it stateless.

That's a lofty goal. The reality is that most useful applications do need to store state. Think about what happens in a simple counter app: the user clicks a button, and the count goes up. Something, somewhere, has to remember the current count. The challenge in functional programming is figuring out how to store that information without directly mutating it.

Here's the problem in concrete terms. If we store state in a global variable and let any function modify it, we get bugs that are hard to track down — any function could have changed the value, and it's hard to know which one did, or when. That's the kind of unpredictability functional programming is designed to avoid.

So instead of storing state in mutable variables that anyone can change, we use other patterns to manage it in a more controlled way. In the next lesson, we'll look at one approach: using closures to store state inside a function, where it's protected from the outside world.

In more complex applications (like React apps), frameworks provide dedicated tools for state management. We'll explore those later in the course.