React concepts: declarative

By

Understand what it means that React is declarative: you describe what the UI should look like, and React updates the DOM for you, unlike imperative jQuery.

~~~

You’ll run across articles describing React as a declarative approach to building UIs. Declarative means you describe what the UI should look like for a given state, and React figures out how to update the DOM to get there.

React made its “declarative approach” quite popular and upfront so it permeated the frontend world along with React.

It’s really not a new concept, but React took building UIs a lot more declaratively than with HTML templates:

The opposite of declarative is imperative. A common example of an imperative approach is looking up elements in the DOM using jQuery or DOM events. You tell the browser exactly what to do, instead of telling it what you need.

What does this look like in practice?

Say we show a badge with the number of unread messages, and hide it when there are none.

The imperative way: find the element, change its text, toggle its visibility. Step by step:

const badge = document.querySelector('.unread-badge')
badge.textContent = unreadCount
if (unreadCount > 0) {
  badge.style.display = 'inline'
} else {
  badge.style.display = 'none'
}

We must remember to run this every time the count changes. Miss one spot, and the UI shows stale data.

The declarative way with React: describe what the badge looks like for a given count.

const UnreadBadge = ({ count }) => {
  if (count === 0) return null
  return <span className='unread-badge'>{count}</span>
}

There are no steps here. No “find the element”, no “change the text”. We wrote a description of the UI as a function of the data. When count changes, React re-renders and the DOM ends up correct.

Why is this better?

The hard part of UIs is keeping the screen in sync with the data over time. With the imperative approach, every possible change needs its own update code, and the combinations grow fast.

With the declarative approach, you only write what each state looks like. The syncing is React’s job. Fewer places to forget, fewer stale-UI bugs.

The React declarative approach abstracts the DOM for us. We just tell React we want a component to be rendered in a specific way, and we never have to interact with the DOM to reference it later.

One warning: don’t mix the two styles. Reaching into React’s DOM with document.querySelector() and editing it by hand seems to work, until React re-renders and overwrites your change. If you need to escape the declarative model (for example to focus an input), use the tool React provides for that, refs.

Tagged: React · All topics
~~~

Related posts about react: