When I first learned useState, I thought I had state figured out. A counter goes up, an input updates, a modal opens and closes. Done. It felt like React had one simple trick, and I’d learned it.
But as I started building actual projects, the word state quietly got bigger.
Consider something as simple as calling setCount(count + 1) and logging count on the very next line, only to see the old value. Or pushing a new item into an array stored in state and wondering why the UI hasn’t updated. These seem like small problems, but they expose gaps in how we understand React’s rendering model, state updates, and immutability.
Then things become more interesting once asynchronous data enters the picture. Even a straightforward API request can introduce separate pieces of state for data, loading, and error. And that’s before we start thinking about race conditions, caching, refetching, or keeping the UI synchronized with the server.
Naturally, you start looking for better ways to handle all of this.
And suddenly, there’s Context, reducers, Redux, Zustand, React Query, URL parameters, form state, and people arguing in comment sections about which one you should be using. You open a Redux tutorial and find yourself learning about actions, reducers, and stores just to build another counter. At some point, it’s reasonable to wonder whether you’re learning something genuinely useful or introducing complexity that you don’t actually need.
I think this is where much of the confusion around state begins.
Learning useState is relatively straightforward. But state isn’t just a React feature. It’s a much broader programming concept, and different kinds of state introduce different problems.
Managing whether a modal is open isn’t the same problem as sharing data across distant components. And neither is quite the same as keeping your UI synchronized with information coming from a server.
Yet we often encounter all of these under the same umbrella: state management.
That’s what I want to unpack in this series.
We’ll start with the fundamentals: what state actually is, why applications need it, and how React handles it under the hood. From there, we’ll work our way toward state ownership, shared and global state, asynchronous and server data, and the tools that have emerged to solve these problems.
The goal isn’t to memorize another collection of Hooks or libraries. It’s to develop a mental model that helps us understand what problem we’re solving, where our state should live, and why a particular approach makes sense.
If you’re already familiar with useState, that’s more than enough to get started.
It’s easy to think React invented the concept of state, especially if your first encounter with it was through useState. But state existed in programming long before React came along. React simply introduced its own way of working with it.
So, before we dive into how React manages state, let’s go back to where it all begins.
Before React: What Is State?
Forget React for a moment.
Imagine you’re listening to music on Spotify. You press play, the song starts playing. You pause it, the playback stops. You skip to the next track, and a different song begins.
At any given moment, the application needs to know a few things: which song is currently selected, whether it’s playing or paused, how far into the song you’ve listened, and perhaps what volume you’ve set.
These pieces of information describe the application’s current state.
And the important part is that they can change.
When you press pause, the application transitions from a playing state to a paused state. When you skip a track, the current song changes. The application behaves differently depending on what those values are at a particular moment.
That’s essentially what state represents in programming.
State is the information a system retains at a particular point in time that helps determine its current condition and future behavior.
This concept isn’t specific to frontend development. A video game tracks a player’s health and position. A shopping cart tracks which items have been added. A database tracks information that persists between requests. Even a simple counter program can maintain state through a variable that changes over time.
The underlying idea is the same: a system remembers information, and that information influences what happens next.
State, Data, and Variables: Are They the Same Thing?
It’s tempting to use these terms interchangeably, but there’s a useful distinction.
Data is a broad term for information. Variables are one of the mechanisms programs use to hold or reference information. State, on the other hand, describes information in the context of a system’s current condition.
For example:
const appName = "Music Player";
let currentSong = "Song A";
let isPlaying = false;
All three variables contain data. But currentSong and isPlaying represent aspects of the music player’s state because their values describe its current condition and may change as the user interacts with it.
appName, meanwhile, is static configuration in this example.
There’s another subtle point: state doesn’t necessarily have to change constantly, or even change at all during a particular execution. What makes something state is its role in describing the system, not simply the fact that it was declared using let instead of const.
State Changes Through Events
Let’s take our music player a little further.
Initially, the player is paused:
let isPlaying = false;
function togglePlayback() {
isPlaying = !isPlaying;
}
Every time togglePlayback() executes, the value changes between true and false.
We can describe this as a state transition: the system moves from one state to another in response to an event.
The important relationship is:
Current State + Event → Next State
An event might be a user clicking a button, an HTTP response arriving, a timer expiring, or something happening elsewhere in the system.
In more complex applications, transitions may also depend on additional inputs and rules. For instance, a music player shouldn’t necessarily begin playback if no playable track is selected.
Thinking about applications in terms of states and transitions helps us move beyond merely assigning values to variables. We begin asking what changes are allowed, what triggers them, and how the application should respond.
Why Does This Matter for User Interfaces?
Now bring the same idea into the browser.
A user interface is essentially a representation of an application’s current information and condition.
If a shopping cart contains three items, the interface might display a badge showing 3. If the user adds another item, the cart’s state changes, and the interface should reflect that change.
This introduces an important requirement: the information held by the application and what the user sees must remain consistent.
And that’s where things get interesting.
In plain JavaScript, we can update a variable without automatically updating the corresponding HTML element. We need to explicitly connect changes in our application data to changes in the DOM.
For a small interface, that’s manageable. But as an application grows, keeping track of what changed and which parts of the interface need updating can become increasingly difficult.
This is one of the problems that libraries like React help us manage.
React gives us a declarative way to describe what the UI should look like for a given state, then coordinates rendering when that state changes.
But to appreciate how React does that, we first need to understand why ordinary JavaScript variables aren’t enough to drive its rendering model.
Why React Needs State
In the previous section, we established that state isn’t something React invented. Applications have always needed to remember information and respond when that information changes.
But when we’re building user interfaces, there’s another problem to think about.
It’s not enough for the application to know what its current state is. What the user sees must also reflect that state.
Imagine a shopping cart. The application knows that you’ve added three items, but the cart icon still displays zero. Technically, the data might be correct, but the interface is showing something completely different.
This is where the relationship between application state and the DOM becomes important.
State and the DOM: Two Things That Need to Stay in Sync
When a browser loads an HTML document, it constructs the Document Object Model, or DOM, a tree of nodes representing the document. JavaScript can interact with this tree through browser-provided DOM APIs.
We can select elements, change their text, modify attributes, create new nodes, or remove existing ones.
But there’s an important distinction.
Changing a JavaScript variable does not automatically change the DOM.
Consider this simple example:
<p id="count">0</p>
<button id="increment">Increment</button>
let count = 0;
const countElement = document.querySelector("#count");
const button = document.querySelector("#increment");
button.addEventListener("click", () => {
count += 1;
});
Clicking the button updates the count variable, but the paragraph still displays 0.
Why?
Because the browser doesn’t automatically know that the text inside #count is supposed to represent the JavaScript variable count.
We created that relationship in our heads, but never expressed it in the program.
To make it work, we need to update the DOM explicitly:
button.addEventListener("click", () => {
count += 1;
countElement.textContent = count;
});
Now both values stay consistent.
Diagram 1: In vanilla JavaScript, our code explicitly connects state changes to DOM updates.
For a counter, this is hardly a problem. It’s one variable and one DOM element.
But real applications rarely remain this simple.
Building a Small Shopping Cart Without React
Let’s extend the same idea to a shopping cart.
Our application needs to track three things:
- The quantity of an item.
- The total price.
- Whether the cart is empty.
Suppose we’re selling a product that costs ₹499.
Our HTML might look like this:
<div class="cart">
<h2>Shopping Cart</h2>
<p>Quantity: <span id="quantity">0</span></p>
<p>Total: ₹<span id="total">0</span></p>
<p id="empty-message">Your cart is empty.</p>
<button id="add">Add Item</button>
<button id="remove">Remove Item</button>
</div>
And here’s one way to implement it using vanilla JavaScript:
const PRICE = 499;
let quantity = 0;
const quantityElement = document.querySelector("#quantity");
const totalElement = document.querySelector("#total");
const emptyMessage = document.querySelector("#empty-message");
const addButton = document.querySelector("#add");
const removeButton = document.querySelector("#remove");
function renderCart() {
quantityElement.textContent = quantity;
totalElement.textContent = quantity * PRICE;
emptyMessage.hidden = quantity > 0;
removeButton.disabled = quantity === 0;
}
addButton.addEventListener("click", () => {
quantity += 1;
renderCart();
});
removeButton.addEventListener("click", () => {
quantity = Math.max(0, quantity - 1);
renderCart();
});
renderCart();
This works perfectly well.
In fact, notice that we’ve already made an important improvement: instead of modifying every DOM element inside every event handler, we’ve extracted the UI-update logic into a dedicated renderCart() function.
Whenever the state changes, we call that function to synchronize the interface.
There is also another useful design choice here: we don’t store the total price and empty-cart status as separate variables.
We calculate them from quantity, which is the actual state our application needs to remember.
This distinction between stored and derived state will become important later.
Where Does the Difficulty Begin?
Our shopping cart works fine for now. But imagine adding a few more features: a navigation badge, discount calculations, stock warnings, and a checkout button.
Suddenly, a single change to quantity affects multiple parts of the interface.
Diagram 2: Every dependent UI element must reflect the latest state.
Now, every operation that changes the cart must also keep these elements synchronized. Forget to update even one, and the interface can become inconsistent.
We could solve this with reusable rendering functions, modules, or our own reactive system. But as the application grows, we’re increasingly responsible for coordinating what changed and which parts of the DOM need updating.
And that’s the problem React helps us manage.
Imperative vs Declarative UI
This brings us to an important programming distinction: imperative and declarative approaches.
With an imperative approach, we explicitly describe the operations required to change the interface.
For example:
if (quantity === 0) {
emptyMessage.hidden = false;
removeButton.disabled = true;
} else {
emptyMessage.hidden = true;
removeButton.disabled = false;
}
We’re telling the browser exactly which properties to change and under what conditions.
A declarative approach expresses the desired result instead.
Conceptually, we might write:
const view = {
quantity,
total: quantity * PRICE,
showEmptyMessage: quantity === 0,
disableRemoveButton: quantity === 0,
};
This object isn’t React code or a rendering system. It simply demonstrates the difference in thinking.
Instead of beginning with the DOM operations, we’re describing how the interface should look for a particular state.
Of course, something still needs to turn that description into actual DOM updates. Declarative programming doesn’t eliminate the underlying operations. It delegates responsibility for coordinating them to another layer.
Diagram 3: Imperative vs. Declarative UI
And that’s where React comes in.
React’s Approach: Describe the UI as a Function of State
React encourages us to describe our interface as a function of its current state.
A useful simplified mental model is:
UI = f(state)
In other words, given the same relevant state and other inputs, our component should describe the same UI.
Rather than instructing the browser to show an empty-cart message, update a price, and disable a button individually, we describe what those elements should look like for the current quantity.
When React processes a state update, it can calculate the next UI description and coordinate the necessary changes to the rendered interface.
Let’s revisit our shopping cart using React.
import { useState } from "react";
const PRICE = 499;
export default function ShoppingCart() {
const [quantity, setQuantity] = useState(0);
const total = quantity * PRICE;
const isEmpty = quantity === 0;
function addItem() {
setQuantity((previous) => previous + 1);
}
function removeItem() {
setQuantity((previous) => Math.max(0, previous - 1));
}
return (
<div className="cart">
<h2>Shopping Cart</h2>
<p>Quantity: {quantity}</p>
<p>Total: ₹{total}</p>
{isEmpty && <p>Your cart is empty.</p>}
<button onClick={addItem}>Add Item</button>
<button onClick={removeItem} disabled={isEmpty}>
Remove Item
</button>
</div>
);
}
Notice what’s missing.
There’s no document.querySelector(), no direct manipulation of textContent, and no manually written renderCart() call.
Instead, we describe the UI using JSX and state.
When a user adds an item, we request a state update through setQuantity.
React then handles the rendering work needed to bring the UI in line with the new state.
But that doesn’t mean React blindly rebuilds the entire browser DOM whenever something changes.
React can call components again to calculate updated output, determine what changed, and commit the necessary updates to the DOM. A component render does not necessarily result in any DOM mutation.
We’ll explore exactly how this works when we examine React’s rendering model.
So, Does React Make State Management Automatic?
Not entirely.
React helps coordinate rendering, but it doesn’t automatically make every state-management decision for us.
We still need to decide what information should be stored, what can be derived, where state should live, which components need access to it, and how to handle information arriving from external systems.
React also doesn’t prevent us from designing contradictory state, mutating values incorrectly, or creating synchronization problems with asynchronous data.
It gives us a more structured model for connecting state to the interface, not a guarantee that our state architecture will be correct.
And there’s still one unanswered question.
In our vanilla JavaScript example, quantity was an ordinary variable. We changed it, called renderCart(), and updated the DOM.
But in React, why can’t we simply declare a variable inside a component, change its value, and expect the component to update?
Why do we need something like useState at all?
That’s where we need to look more closely at how React components render and remember information between renders.
Where We Go From Here
We’ve gone from state as a general programming concept to a problem every interactive UI faces: keeping what the application knows consistent with what the user sees. React gives us a declarative way to describe that UI, but it doesn’t remove the need to understand how state behaves.
In Part 2: How React State Actually Works, we’ll start with that ordinary-variable question and follow what happens when a component renders, remembers state, and processes an update. We’ll explore useState, render snapshots, queued updates, and why React sometimes preserves state and sometimes resets it.
For now, the idea to carry forward is simple: state describes what the application knows; rendering determines what the user sees. Understanding how React connects the two is our next step.