Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
React 17 Design Patterns and Best Practices

You're reading from   React 17 Design Patterns and Best Practices Design, build, and deploy production-ready web applications using industry-standard practices

Arrow left icon
Product type Paperback
Published in May 2021
Publisher Packt
ISBN-13 9781800560444
Length 394 pages
Edition 3rd Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (21) Chapters Close

Preface 1. Hello React!
2. Taking Your First Steps with React FREE CHAPTER 3. Cleaning Up Your Code 4. How React Works
5. React Hooks 6. Exploring Popular Composition Patterns 7. Understanding GraphQL with a Real Project 8. Managing Data 9. Writing Code for the Browser 10. Performance, Improvements, and Production!
11. Making Your Components Look Beautiful 12. Server-Side Rendering for Fun and Profit 13. Improving the Performance of Your Applications 14. Testing and Debugging 15. React Router 16. Anti-Patterns to Be Avoided 17. Deploying to Production 18. Next Steps 19. About Packt 20. Other Books You May Enjoy

Differentiating between declarative and imperative programming

When reading the React documentation or blog posts about React, you will have undoubtedly come across the term declarative. One of the reasons why React is so powerful is that it enforces a declarative programming paradigm.

Therefore, to master React, it is essential to understand what declarative programming means and what the main differences between imperative and declarative programming are. The easiest way to approach this is to think about imperative programming as a way of describing how things work, and declarative programming as a way of describing what you want to achieve.

Entering a bar for a beer is a real-life example in the imperative world, where normally you will give the following instructions to the bartender:

  1. Find a glass and collect it from the shelf.
  2. Place the glass under the tap.
  3. Pull down the handle until the glass is full.
  4. Hand me the glass.

In the declarative world, you would just say "Can I have a beer, please?"

The declarative approach assumes that the bartender already knows how to serve a beer, an important aspect of the way declarative programming works.

Let's move into a JavaScript example. Here we will write a simple function that, given an array of lowercase strings, returns an array with the same strings in uppercase:

toUpperCase(['foo', 'bar']) // ['FOO', 'BAR']

An imperative function to solve the problem would be implemented as follows:

const toUpperCase = input => { 
const output = []

for (let i = 0; i < input.length; i++) {
output.push(input[i].toUpperCase())
}

return output
}

First of all, an empty array to contain the result is created. Then, the function loops through all the elements of the input array and pushes the uppercase values into the empty array. Finally, the output array is returned.

A declarative solution would be as follows:

const toUpperCase = input => input.map(value => value.toUpperCase())

The items of the input array are passed to a map function that returns a new array containing the uppercase values. There are some significant differences to note: the former example is less elegant and it requires more effort to be understood. The latter is terser and easier to read, which makes a huge difference in big code bases, where maintainability is crucial.

Another aspect worth mentioning is that in the declarative example, there is no need to use variables, nor to keep their values updated during the execution. Declarative programming tends to avoid creating and mutating a state.

As a final example, let's see what it means for React to be declarative. The problem we will try to solve is a common task in web development: creating a toggle button.

Imagine a simple UI component such as a toggle button. When you click it, it turns green (on) if it was previously gray (off), and switches to gray (off) if it was previously green (on).

The imperative way of doing this would be as follows:

const toggleButton = document.querySelector('#toggle')

toogleButton.addEventListener('click', () => {
if (toggleButton.classList.contains('on')) {
toggleButton.classList.remove('on')
toggleButton.classList.add('off')
} else {
toggleButton.classList.remove('off')
toggleButton.classList.add('on')
}
})

It is imperative because of all the instructions needed to change the classes. In contrast, the declarative approach using React would be as follows:

// To turn on the Toggle
<Toggle on />

// To turn off the toggle
<Toggle />

In declarative programming, developers only describe what they want to achieve, and there's no need to list all the steps to make it work. The fact that React offers a declarative approach makes it easy to use, and consequently, the resulting code is simple, which often leads to fewer bugs and more maintainability.

In the next section, you will learn how React elements work and you will get more context on how props are being passed on a React component.

You have been reading a chapter from
React 17 Design Patterns and Best Practices - Third Edition
Published in: May 2021
Publisher: Packt
ISBN-13: 9781800560444
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image