Declarative UI means you describe the desired output; the library figures out how to update the DOM. Imperative UI means you spell out each step: create node, set attribute, append child, replace text.
Imperative vs declarative (conceptual)
// Imperative (vanilla)
const el = document.createElement('p');
el.textContent = 'Hello, ' + name;
container.appendChild(el);
// Declarative (React idea)
// return <p>Hello, {name}</p>;
When name changes in React, you re-run the component function with new state; React patches only what changed. You do not manually remove and recreate the paragraph.
UI as a function of state
A useful mental model: UI = f(state). Given the same state, you get the same description. That predictability makes debugging and testing easier than scattered DOM mutations.
Important interview questions and answers
- Q: What does declarative mean in React?
A: You declare what the UI should look like for current props/state; React handles DOM updates. - Q: Can React be used imperatively?
A: Rarely via refs for focus or third-party widgets, but the default pattern is declarative components.
Self-check
- Rewrite “toggle a CSS class on click” in declarative terms (what state drives the class?).
- Why is
UI = f(state)easier to reason about than ad-hoc DOM edits?
Interview prep
- Declarative vs imperative UI?
Describe UI as a function of state; React patches the DOM when state changes instead of hand-writing every DOM step in large apps.