Declarativeness in React
In short
A declarative approach is a way of describing what needs to be obtained, not how to do it. React is built precisely on declarativeness: you describe the state of the interface, and React itself takes care of how to efficiently update it in the DOM.
Example by contrast
Imperative approach (Vanilla JS)
You tell the browser yourself, step by step, what to do:
javascript
const button = document.createElement('button');
button.textContent = 'Click me';
button.addEventListener('click', () => {
button.textContent = 'Clicked';
});
document.body.appendChild(button);Here you manually:
- create the element,
- add the text,
- attach the handler,
- change the DOM on the event.
This is imperative: you describe how to achieve the result.
Declarative approach (React)
You describe what should be depending on the state:
javascript
function Button() {
const [clicked, setClicked] = React.useState(false);
return (
<button onClick={() => setClicked(true)}>
{clicked ? 'Clicked' : 'Click me'}
</button>
);
}Here you do not describe the steps for updating the DOM. You simply declare what the interface should look like for different states (
clicked).
React itself:
- tracks state changes,
- recomputes the virtual DOM,
- updates only the necessary parts of the real DOM.
The meaning of declarativeness in React
| Imperative style | Declarative style |
|---|---|
| Describe how to do everything | Describe what should be |
| You manage the DOM manually | React updates the DOM itself |
| A lot of code and side effects | Minimal DOM-handling logic |
| Hard to maintain complex interfaces | Easy to understand and extend the UI |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.