Introduction
The concept of state is used in many fields, and even in everyday life, to describe how something behaves under certain conditions. A simple example is traffic lights: they mainly use two important colors, red and green, and cars behave according to which one is currently on. When the red light is on, all cars stop; when the green light is on, cars move.
This same idea is also applied in the world of programming. In this article, we will explore what states are in programming, why they are important, and how to use them effectively.
What is State in Programming
State refers to the current condition or data stored in memory that can change over time and directly affects how a program behaves.
For example, consider a website with a login form. There are two main states:
-
Logged out state – The user has not entered valid login information yet. In this state, the user cannot access the main functionalities of the site. Instead, they might only see options like logging in, signing up, or requesting help.
-
Logged in state – The user has successfully entered their information. In this state, the website grants access to its main features, such as viewing content, managing settings, or making purchases.
Stateful vs Stateless Programs
What is a Stateful Program ?
A program is described as stateful when it retains memory of past interactions and uses that information to decide what to do next. In other words, it maintains a state (data stored in memory) that changes over time as the user interacts with it or as events occur.
For example, consider an online shopping website. If you add an item to your cart, the site remembers what’s inside. Even if you navigate to another page, the item is still stored in the cart. That “memory” of your cart is the program’s state.
Here’s another example to make it clearer: imagine a TV where you can change channels. Each time you switch, the TV remembers the old channel and the current channel. Let’s see this in code:
let oldChannel = 5;
let currentChannel = 11;
function changeTVChannelTo(newNumber) {
if (typeof newNumber === "number") {
oldChannel = currentChannel;
currentChannel = newNumber;
return `Channel changed from ${oldChannel} to ${currentChannel}`;
}
}
// Change the channel of the TV:
changeTVChannelTo(48);
// The invocation above will return:
"Channel changed from 11 to 48"
In the snippet above:
-
oldChannelandcurrentChannelare the states managed by the program. -
changeTVChannelTo()is a stateful function that updates and uses those states.
What is a Stateless Program ?
In contrast to a stateful program, a stateless program does not recall past interactions or data. It depends only on the information provided at the moment it is executed. Once it runs, it performs its task and produces a result without saving any state that could affect future executions.
In other words, a stateless program works independently of previous states because it doesn’t store them, it behaves solely based on the input it receives at runtime.
A simple example of this is a static website built with only HTML (and no JavaScript). Every time you load the site, it shows the same content and doesn’t remember your previous actions.
function add(a, b) {
return a + b;
}
add(3, 7); // Always returns 10
add(3, 7); // Still returns 10
The function add() is stateless because it always produces the same result for the same inputs. It doesn’t rely on or modify any stored values, it just processes the arguments it receives.
Summary table
| Aspect | Stateful Program | Stateless Program |
|---|---|---|
| Definition | Retains memory of past interactions and uses it to determine future behavior. | Does not remember past interactions; each execution is independent. |
| Data handling | Stores and updates state (data in memory) over time. | Depends only on the input provided at the moment of execution. |
| Behavior | Output may vary depending on current state and past actions. | Output depends only on current input; same inputs always give the same output. |
| Use cases | Applications that need to track user sessions, carts, or histories. | Simple utilities, stateless APIs, or static websites. |
How State is Stored in Programs
The usage of state can take many forms depending on the type of program and what it needs to achieve. State doesn’t have to be stored in just one specific place. Let’s look at the most common places where state is stored:
1. In Variables
In simple programs, state is stored in variables that live in the computer’s memory (RAM). These values last only while the program is running.
Example:
let clicks = 0; // initial state
clicks++; // update state
console.log(clicks); // prints 1
Here, clicks is the program’s state. But as soon as you close the program, that value is lost because it only lives in memory.
2. In Data Structures
As programs grow, state becomes more complex and needs suitable data structures to manage it, such as arrays, objects, or classes.
Example
let user = {
name: "Alice",
loggedIn: false
};
user.loggedIn = true; // update state
Here, the whole user object represents the state of one user.
3. In Databases
In real-world applications, we often need to save state permanently so we can retrieve it even after the program is closed. Variables or data structures that live only in memory are not enough, because their data disappears once the program ends.
That’s why we use databases to store state. This way, we can return to it any time. For example, in social media platforms, databases store information such as usernames, profile pictures, posts, and likes so users can access them whenever they log in.
Let’s build on the user example:
let user = {
name: "Alice",
loggedIn: false
};
user.loggedIn = true; // update state
Here, the loggedIn value is stored in memory (RAM). That means it only exists while the program is running. If Alice closes her browser or the app restarts, this state disappears.
In a real application, we don’t want Alice to lose her information every time she closes her browser. That’s why we save her details permanently in a database.
// When Alice first registers, we save her info to the database
let userData = {
id: 1,
name: "Alice",
email: "alice@example.com",
password: "encrypted_password_here"
};
// Save to database (persists even after app closes)
database.saveUser(userData);
Now, whenever Alice comes back:
// 1. Retrieve her saved data from the database
let savedUser = database.getUserByEmail("alice@example.com");
// 2. Set a temporary state in memory for the current session
let currentUser = {
id: savedUser.id,
name: savedUser.name,
loggedIn: true // session-only state
};
Key Difference
-
Memory state (
loggedIn: true) → temporary, only valid while Alice is using the app. Lost when the browser or program closes. -
Database state (
name,email,id) → permanent, stored safely and available every time Alice comes back.
Note: The database.saveUser() and database.getUserByEmail() functions here are just representations of state being stored and retrieved. In real projects, databases can be SQL (like MySQL, PostgreSQL) or NoSQL (like MongoDB, Firebase). Each type has its own way of handling data. The goal of this example is only to show the difference between temporary state in memory and persistent state in a database, not to use an exact database syntax.
4. In the Browser (For Web Apps)
When working on websites, the browser itself provides ways to store state:
- Cookies → small pieces of data stored by the browser, often used for login sessions.
// Set a cookie
document.cookie = "username=JohnDoe";
// Read cookies
console.log(document.cookie); // "username=JohnDoe"
- Local Storage → stores key-value data that stays even after you close the browser. Example: dark mode preferences.
// Save data
localStorage.setItem("theme", "dark");
// Get data
console.log(localStorage.getItem("theme")); // "dark"
- Session Storage → like local storage, but cleared once the tab is closed.
// Save data
sessionStorage.setItem("cart", "2 items");
// Get data
console.log(sessionStorage.getItem("cart")); // "2 items"
States in Web Frameworks
Modern web frameworks like React, Vue, and Angular rely heavily on state to make websites interactive. When the state (the stored data) changes, these frameworks automatically update the user interface (UI) to reflect the new data.
For example:
-
In React, when you update a state variable (like
setCount(count + 1)), React re-renders the component so the UI shows the new count. -
In Vue, when a data property changes, the framework updates the DOM elements that use that property.
-
In Angular, the UI is kept in sync with the component’s state through its change detection system.
For a clearer picture, let’s look at how React uses state. In React, state is usually tied to components, and when that state changes, React automatically re-renders the component to show the new data. Here’s a simple example:
import { useState } from "react";
function Counter() {
// Declare a state variable "count" and a function "setCount" to update it
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default Counter;
This makes building dynamic websites much easier, because you don’t have to manually update the page every time data changes, the framework handles it for you.
Common Beginner Mistakes with State
When starting out, it’s easy to make mistakes with state. Some common ones are:
1. Mixing up variables and state
Beginners sometimes rely on plain variables to store values that are supposed to persist or update the UI. For example, in React it’s wrong to just write let count = 0. You need to use useState so React knows to re-render the component when the state changes.
2. Not resetting state properly
Forgetting to reset state when needed is a very common mistake. This can cause old data to “leak” into new situations. For example, if a game doesn’t reset the score when a new round starts, the player might begin with leftover points from the previous round instead of starting at zero.
3. Overcomplicating state
Sometimes beginners try to keep everything in state, even values that don’t really need to be stored. This only makes the program more complicated. For example, if you have an array in your program, there’s no need to store its length in a separate state, you can just use array.length whenever you need it. The more you store, the more you’ll have to update and keep in sync, which increases the chances of mistakes.
Conclusion
To wrap it up, state is simply the memory of a program, the data it keeps track of that changes over time and affects how the program behaves, state is what makes programs dynamic and responsive.
Understanding state is an essential foundation before moving on to more advanced topics like state management libraries (such as Redux, Vuex, or NgRx), which help organize and control state in bigger projects.
So, before diving into advanced tools and libraries, focus on truly understanding state itself. It’s the foundation that makes modern, interactive applications possible.