Why is React called a declarative library?
React is called a declarative library because in it we describe what should be shown to the user, rather than exactly how to do it.
Imperative vs declarative approach
To understand this, let's compare two approaches:
Imperative style (plain JavaScript)
You tell the browser step by step how to update the interface:
const button = document.createElement("button");
button.textContent = "Click me";
button.addEventListener("click", () => {
button.textContent = "Clicked!";
});
document.body.appendChild(button);Here you directly manage the DOM: you create elements, add listeners, update the text.
Declarative style (React)
You describe the final state of the interface, and React decides on its own how to achieve it:
function Button() {
const [clicked, setClicked] = useState(false);
return (
<button onClick={() => setClicked(true)}>
{clicked ? "Clicked!" : "Click me"}
</button>
);
}Here you don't touch the DOM manually. You simply say: "if
clickedis true, show the text 'Clicked!'". React compares the old and new state itself and updates only the necessary part.
Why this is convenient
- The code is easier to read and maintain (you describe what should be, not how to change the DOM).
- Fewer errors when working with state.
- Easier to scale large interfaces.
Analogy
Imperative code is like telling a robot:
"Take the spoon, scoop up the soup, bring it to your mouth, tilt it, bring the spoon back".
Declarative code is like saying:
"Feed me soup".
The robot (React, in our case) figures out exactly how to do it on its own.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.