Declarative vs. Imperative UI

Stop writing steps to mutate the DOM. Start describing the final state.

React3 min readConcept 1 of 46

What it is

In traditional web development, you write **imperative** code. You write exact, step-by-step instructions telling the browser how to mutate the DOM: find this element, add this class, update this text node.

React introduces a **declarative** model. Instead of writing steps, you describe what the UI should look like for a given state. When the state changes, React figures out the exact steps needed to update the DOM to match your description.

Why it matters

Imperative code becomes impossible to manage as an application grows. If five different events can change a button's state, you have to write manual DOM updates for every possible transition.

By using a declarative model, you eliminate an entire class of bugs. You no longer worry about how the UI transitions from one state to another. You simply declare the rules, and React guarantees the DOM matches your state.

How it works

Imagine a button that turns blue when active. In vanilla JavaScript, you would query the element and manually call classList.add('blue') when clicked.

In React, you define a variable (like isActive). Then, you conditionally render the class name inside your JSX: className={isActive ? 'blue' : ''}.

React watches that variable. The moment it flips to true, React automatically updates the real DOM for you.

The Paradigm Shift

Compare the traditional imperative approach (left) to the modern declarative React approach (right). Notice how React never touches the DOM directly.

// 1. Declare the state variable
const [isActive, setIsActive] = useState(false);
// 2. Describe the final UI for any state
return (
<button
className={isActive ? "active" : "inactive"}
onClick={() => setIsActive(!isActive)}
>
Toggle State
</button>
);

Internal State

isActive: false

Rendered Result

Notice how we never write `button.classList.add()`. We just change the variable, and React syncs the DOM.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the primary difference between declarative and imperative programming in UI?
  2. 2Why is it dangerous to manually mutate the DOM using `document.getElementById` inside a React component?
  3. 3How should you handle a button that needs to toggle an 'active' CSS class?

Remember this

  • React is a declarative library. You describe the UI, React handles the DOM updates.
  • Never mix manual DOM mutations (document.querySelector) with React components.
  • Always treat your UI as a pure reflection of your data.

Done with this concept?

Mark it complete to track your progress. No login needed.