DEV Community

Lauren Beatty
Lauren Beatty

Posted on • Updated on

React Deep Dive: It's Declarative

This year, I'm starting to read through the React docs and take notes as I go so that I can be a better technical communicator.

Declarative

In looking at the React website, one of the first things you'll see is that React is "declarative". I felt like I had only a basic understanding of what that meant. I mean, you just declare it, right? 😂

I thought I might need a better understanding than that. I found a great explanation from Tyler McGinnis, that really informed my understanding, and also helped me understand why learning React felt like such a huge departure from jQuery-land.

So, what does it mean when we say that React is a declarative programming language?

Declarative means that we describe the end state of our program without dictating the steps to get there.

What does that look like?

// Describe a BasicButton component
const BasicButton = ({onClick, buttonText}) => {
  return (
    <button onClick={onClick}>{buttonText}</button>
  )
}

// later, when using BasicButton
<BasicButton
  onClick={() => setDrawerOpen(!open)}
  buttonText="Toggle"
/>
Enter fullscreen mode Exit fullscreen mode

Here I'm describing to React what I want a BasicButton component to look like. It should render a button, it should have an onClick handler, and buttonText. When I use it, I can pass a function to onClick and some text to the button. I'm not telling React how to do it, I'm just describing what I'd like. I'm leaving the implementation details to React. Notice, too, that I can use this button anywhere, it doesn't rely on any specific context.

Imperative

How is that different from imperative? When I think of imperative, I think of a jQuery implementation like this:

$('button').on('click', () => {
  $('#drawer').toggleClass('open')
})

// Um, I have not used jQuery in quite some time. That was hard.
Enter fullscreen mode Exit fullscreen mode

Here I'm engaging in direct DOM manipulation. When I click on the button, find the element that has an id of drawer, and then add or remove the class open from that element. I'm giving specific instructions for how I want this to happen. Do this thing, and then do that other thing. This code really depends on the existence of an element that has an id of drawer. It's not context-independent.

When learning React, I think that was the biggest challenge for me, is that switch from a more imperative style to a declarative style. I was used to directly manipulating the DOM and telling it the steps to follow, as opposed to just describing the UI state(s) I wanted.

(Here's another read that was super helpful)

Top comments (0)