It makes perfect sense for us to write our UIs with declarative code. The reason is that we need to reuse UI elements and compose them together in different configurations. UIs are complex.
DECLARATIVE
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
IMPERATIVE
const list = document.createElement('ul')
const item1 = document.createElement('li')
const item2 = document.createElement('li')
item1.innerHTML = 'Item 1'
item2.innerHTML = 'Item 2'
list.appendChild(item1)
list.appendChild(item2)
But what about our application logic? Applications are becoming more complex in nature as we push the boundaries of user experiences. The code we write to manage this complexity would also benefit from having the same properties as our UI code.
DECLARATIVE
[
setLoading(true),
getUser,
{
success: setUser,
error: setError
},
setLoading(false),
]
IMPERATIVE
function getUser() {
this.isLoading = true
ajax.get('/user')
.then((user) => {
this.data = user
this.isLoading = false
})
.catch((error) => {
this.error = error
this.isLoading = false
})
}
A declarative approach to application logic also allows us to build developer tools that builds the mental image of this complexity for you: