React is Declarative - What Does it Mean?
September 21, 2021
It's drilled into you when learning React that it is declarative. But what does declarative mean, and what is the opposite of declarative?
Declarative vs Imperative UI
The opposite of declarative is imperative. These are not React-specific terms. They apply to programming in general.
StackOverflow - What is the difference between declarative and imperative paradigm in programming?
In terms of web user interfaces:
- The imperative approach is when you provide step-by-step DOM mutations until you reach desired UI
- The declarative approach is when you describe the final state of the desired UI
Example of declarative vs imperative UI
Let’s say we need to build this user interface:
Here is the imperative solution. For every interaction, we provide step-by-step DOM mutations to reach the desired state of UI. (The example is slowed down to show how each instruction affects the user interface)
Here is a declarative React solution. We don’t provide step-by-step instructions to reach the desired UI. Instead, we describe the final UI we want for each scene.
We may structure the component differently. It doesn’t make it less declarative.
What makes it declarative is that we describe a final UI for any given state representation. It is the opposite of providing manual DOM mutations to transition between UI states (imperative).