JavaScript State Management: Classes vs Data Attributes
State Management Issues
The Trouble with Classes
CSS classes are fantastic for styling. They let us group visual rules and apply them to elements efficiently. But problems arise when we ask classes to do a second job: managing an element's state.
Using a class like is-expanded or is-hidden seems simple at first. It's a quick way for our JavaScript to tell the CSS how an element should behave. However, this mixes two different concerns. A class should describe what an element looks like, not what state it's in. When we merge these roles, our code becomes harder to understand and maintain.
When Meanings Collide
Imagine you have a class named .highlighted. In the CSS, it's defined to give an element a blue background. A developer might use this class in JavaScript to mark the currently selected item in a list. Everything works fine, for now.
Then, a designer decides the highlight color should be yellow, not blue. They update the .highlighted class in the stylesheet. Simple, right? But what if another part of the application used .highlighted just for its blue color, not to indicate a selection? Suddenly, changing a style has broken the application's logic. This is where ambiguity leads to bugs.
The name of a class starts to mean two different things at once: one for the stylesheet (its appearance) and one for the script (its state).
This creates a tight and brittle connection between your CSS and your JavaScript. A developer can't change a class name used in a script without checking every stylesheet, and a designer can't change a style without worrying about breaking the application's behavior.
The Limits of a Class
Using classes for state also has practical limitations. What if an element needs to hold more complex information? For example, what if you need to know which user ID is associated with a clicked button? A class name can't store that value.
You also end up with long, messy lists of classes as states multiply. An element might look like this:
<div class="item is-active is-editing has-error is-featured">...</div>
This becomes difficult to read and manage. The HTML is cluttered with state information that doesn't describe the content itself. Furthermore, the CSS has to account for all possible combinations of these state classes, which can lead to overly complex and specific selectors.
Ultimately, relying on classes for state management forces your CSS file to act like a database for your application's logic. It wasn't designed for that purpose, and the strain eventually shows through maintenance headaches and unexpected bugs.
What is the fundamental problem with using CSS classes like is-hidden or is-expanded to manage an element's state?
When a designer changes the style of a .highlighted class from blue to yellow, it unexpectedly breaks application logic elsewhere. This is an example of...
