DEV Community

Alex Sidorenko
Alex Sidorenko

Posted on • Originally published at alexsidorenko.com

React is Declarative - What Does it Mean?

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:

example1

Imperative approach

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)

example-imperative

Declarative approach

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.

example-declarative

We may structure the component differently. It doesn't make it less declarative.

example-declarative-2

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, which would be considered imperative.


Originally published at alexsidorenko.com

Top comments (0)