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 Design Patterns and Best Practices

You're reading from   React Design Patterns and Best Practices Build easy to scale modular applications using the most powerful components and design patterns

Arrow left icon
Product type Paperback
Published in Jan 2017
Publisher Packt
ISBN-13 9781786464538
Length 318 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Michele Bertoli Michele Bertoli
Author Profile Icon Michele Bertoli
Michele Bertoli
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Everything You Should Know About React FREE CHAPTER 2. Clean Up Your Code 3. Create Truly Reusable Components 4. Compose All the Things 5. Proper Data Fetching 6. Write Code for the Browser 7. Make Your Components Look Beautiful 8. Server-Side Rendering for Fun and Profit 9. Improve the Performance of Your Applications 10. About Testing and Debugging 11. Anti-Patterns to Be Avoided 12. Next Steps

Declarative programming

Reading the React documentation or blog posts about React, you have surely come across the term declarative.

In fact, one of the reasons why React is so powerful is because it enforces a declarative programming paradigm.

Consequently, to master React, it is important to understand what declarative programming means and what the main differences between imperative and declarative programming are.

The easiest way to approach the problem 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.

A real-life parallel in the imperative world would be entering a bar for a beer, and giving the following instructions to the bartender:

  • Take a glass from the shelf
  • Put the glass in front of the draft
  • Pull down the handle until the glass is full
  • Pass me the glass

In the declarative world, instead, you would just say: "Beer, please."

The declarative approach of asking for a beer assumes that the bartender knows how to serve one, and that is an important aspect of the way declarative programming works.

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

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

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

const toLowerCase = input => { 
  const output = [] 
  for (let i = 0; i < input.length; i++) { 
    output.push(input[i].toLowerCase()) 
  } 
  return output 
} 

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

A declarative solution would be as follows:

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

The items of the input array are passed to a map function, which returns a new array containing the lowercase values.

There are some important 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, in fact, 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: showing a map with a marker.

The JavaScript implementation (using the Google Maps SDK) is as follows:

const map = new google.maps.Map(document.getElementById('map'), { 
  zoom: 4, 
  center: myLatLng, 
}) 
 
const marker = new google.maps.Marker({ 
  position: myLatLng, 
  title: 'Hello World!', 
}) 
 
marker.setMap(map) 

It is clearly imperative, because all the instructions needed to create the map, and create the marker and attach it to the map are described inside the code, one after the other.

A React component to show a map on a page would look like this instead:

<Gmaps zoom={4} center={myLatLng}> 
  <Marker position={myLatLng} Hello world! /> 
</Gmaps> 

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.

You have been reading a chapter from
React Design Patterns and Best Practices
Published in: Jan 2017
Publisher: Packt
ISBN-13: 9781786464538
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