Why to choose React

Komal Pal
11 min readMay 13, 2020

--

Earlier I simply just used to take notes of various courses for a quick recall with a pen and paper but now I thought it would be wise enough to write a blog for whatever was discovered,

so here’s first one for that….

Some features of React:

  • Its compositional model
  • Its declarative nature
  • The way data flows through a Component
  • And that React is really just javascript

1. What is Composition:

to combine simple functions to build more complicated ones” as per wikipedia

Composition is just combining simple functions together to create complex functions. There are a couple of key ingredients here that we don’t want to lose track of. These ingredients are:

  • simple functions
  • combined to create another function

Composition is built from simple functions. Let’s look at an example:

function getProfileLink (username) {
return 'https://github.com/' + username
}

Similarly, the getProfilePic function is also just a single line:

function getProfilePic (username) {
return 'https://github.com/' + username + '.png?size=200'
}

These are definitely simple functions, so to compose them, we’d just combine them together inside another function:

function getProfileData (username) {
return {
pic: getProfilePic(username),
link: getProfileLink(username)
}
}

Now we could have written getProfileData without composition by providing the data directly:

function getProfileData (username) {
return {
pic: 'https://github.com/' + username + '.png?size=200',
link: 'https://github.com/' + username
}
}

There's nothing technically wrong with this at all; this is entirely accurate JavaScript code. But this isn't composition. There are also a couple of potential issues with this version that isn't using composition. If the user's link to GitHub is needed somewhere else, then duplicate code would be needed. A good function should follow the "DOT" rule:

Do One Thing

This function is doing a couple of different (however minor) things; it's creating two different URLs, storing them as properties on an object, and then returning that object. In the composed version, each function just does one thing:

  • getProfileLink – just builds up a string of the user's GitHub profile link
  • getProfilePic – just builds up a string the user's GitHub profile picture
  • getProfileData – returns a new object

React & Composition

React makes use of the power of composition, heavily! React builds up pieces of a UI using components. Let’s take a look at some pseudo code for an example. Here are three different components:

<Page />
<Article />
<Sidebar />

Now let’s take these simple components, combine them together, and create a more complex component (aka, composition in action!):

<Page>
<Article />
<Sidebar />
</Page>

Now the Page component has the Article and Sidebar components inside. This is just like the earlier example where getProfileData had getProfileLink and getProfilePic inside it.

Further Research

Source: Udacity Nanodegree

2. What is Declarative Code:

Imperative Code

A lot of JavaScript is imperative code. According to the dictionary, “imperative” means:

expressing a command; commanding

When JavaScript code is written imperatively, we tell JavaScript exactly what to do and how to do it. Think of it as if we’re giving JavaScript commands on exactly what steps it should take. For example, I give you the humble for loop:

const people = ['Amanda', 'Farrin', 'Geoff', 'Karen', 'Richard', 'Tyler']
const excitedPeople = []
for (let i = 0; i < people.length; i++) {
excitedPeople[i] = people[i] + '!'
}

If you’ve worked with JavaScript any length of time, then this should be pretty straightforward. We’re looping through each item in the people array, adding an exclamation mark to their name, and storing the new string in the excitedPeople array. Pretty simple, right?

This is imperative code, though. We’re commanding JavaScript what to do at every single step. We have to give it commands to:

  • set an initial value for the iterator — (let i = 0)
  • tell the for loop when it needs to stop - (i < people.length)
  • get the person at the current position and add an exclamation mark — (people[i] + '!')
  • store the data in the ith position in the other array - (excitedPeople[i])
  • increment the i variable by one - (i++)

Another Real world example:

The example of keeping the air temperature at 71º? In my old car, I would turn the knob to get the cold air flowing. But if it got too cold, then I’d turn the knob up higher. Eventually, it would get too warm, and I’d have to turn the knob down a bit, again. I’d have to manage the temperature myself with every little change. Doesn’t this sound like an imperative situation to you? I have to manually do multiple steps.

Declarative Code

In contrast to imperative code, we’ve got declarative code. With declarative code, we don’t code up all of the steps to get us to the end result. Instead, we declare what we want done, and JavaScript will take care of doing it. This explanation is a bit abstract, so let’s look at an example. Let’s take the imperative for loop code we were just looking at and refactor it to be more declarative.

With the imperative code we were performing all of the steps to get to the end result. What _is_ the end result that we actually want, though? Well, our starting point was just an array of names:

const people = ['Amanda', 'Farrin', 'Geoff', 'Karen', 'Richard', 'Tyler']

The end goal that we want is an array of the same names but where each name ends with an exclamation mark:

["Amanda!", "Farrin!", "Geoff!", "Karen!", "Richard!", "Tyler!"]

To get us from the starting point to the end, we’ll just use JavaScript’s .map() function to declare what we want done.

const excitedPeople = people.map(name => name + '!')

That’s it! Notice that with this code we haven’t:

  • created an iterator object
  • told the code when it should stop running
  • used the iterator to access a specific item in the people array
  • stored each new string in the excitedPeople array

…all of those steps are taken care of by JavaScript’s .map() Array method.

React is Declarative

We’ll get to writing React code very soon, but let’s take another glimpse at it to show how it’s declarative.

<button onClick={activateTeleporter}>Activate Teleporter</button>

It might seem odd, but this is valid React code and should be pretty easy to understand. Notice that there’s just an onClick attribute on the button...we aren't using .addEventListener() to set up event handling with all of the steps involved to set it up. Instead, we're just declaring that we want the activateTeleporter function to run when the button is clicked.

Declarative Code Recap

React is declarative because we write the code that we want, and React is in charge of taking our declared code and performing all of the JavaScript/DOM steps to get us to our desired result.

Further Research

Source: Udacity Nanodegree

To be precise it simply updates what is changed rather than updating whole page or screen

Unidirectional Data Flow:

Data-Binding In Other Frameworks

Front-end frameworks like Angular and Ember make use of two-way data bindings. In two-way data binding, the data is kept in sync throughout the app no matter where it is updated. If a model changes the data, then the data updates in the view. Alternatively, if the user changes the data in the view, then the data is updated in the model. Two-way data binding sounds really powerful, but it can make the application harder to reason about and know where the data is actually being updated.

Further Research

source: Udacity Nanodegree

React’s Data-flow

Data moves differently with React’s unidirectional data flow. In React, the data flows from the parent component to a child component.

Data flows down from parent component to child component. Data updates are sent to the parent component where the parent performs the actual change.

In the image above, we have two components:

  • a parent component
  • a child component

The data lives in the parent component and is passed down to the child component. Even though the data lives in the parent component, both the parent and the child components can use the data. However, if the data must be updated, then only the parent component should perform the update. If the child component needs to make a change to the data, then it would send the updated data to the parent component where the change will actually be made. Once the change _is_ made in the parent component, the child component will be passed the data

Data Flow in React Recap

In React, data flows in only one direction, from parent to child. If data is shared between sibling child components, then the data should be stored in the parent component and passed to both of the child components that need it.

React is “just Javascript”:

const shelf1 = [{name: 'name1', shelf: 'a'},{name: 'name2', shelf: 'a'}];
const shelf2 = [{name: 'name3', shelf: 'b'},{name: 'name4', shelf: 'b'}];
const allBooks = [...shelf1, ...shelf2];

const filter = books => shelf => books.filter(b => {
return b.shelf === shelf;
});

const filterBy = filter(allBooks);
const booksOnShelf = filterBy('b');

Simply a refresher on ES6 course for javascript.

Over the past couple of years, functional programming has had a large impact on the JavaScript ecosystem and community. Functional programming is an advanced topic in JavaScript and fills hundreds of books. It's too complex to delve into the benefits of functional programming . But React builds on a lot of the techniques of functional programming. However, there are a couple of important JavaScript functions that are vital to functional programming that we should look at.

These are the Array's .map() and .filter() methods.

Array’s .map() Method

If you’re not familiar with JavaScript’s Array .map() method, it gets called on an existing array and returns a new array based on what is returned from the function that's passed as an argument. Let's take a look:

const names = ['Karen', 'Richard', 'Tyler'];const nameLengths = names.map( name => name.length );

Let’s go over what’s happening here. The .map() method works on arrays, so we have to have an array to start with:

const names = ['Karen', 'Richard', 'Tyler'];

We call .map() on the names array and pass it a function as an argument:

names.map( name => name.length );

The arrow function that’s passed to .map() gets called for each item in the names array! The arrow function receives the first name in the array, stores it in the name variable and returns its length. Then it does that again for the remaining two names.

.map() returns a new array with the values that are returned from the arrow function:

const namths = names.map( name => name.length );

So nameLengths will be a new array [5, 7, 5]. This is important to understand; the .map() method returns a new array, it does not modify the original array.

This was just a brief overview of how the .map() method works. For a deeper dive, check out .map() on MDN.

.map() Quiz

Use the provided music data array and the .map() method to create a new array that contains items in the format:

<album-name> by <artist> sold <sales> copies

Store the new array in an albumSalesStrings array. So the first item in the albumSalesStrings array should be "25 by Adele sold 1731000 copies"

Here’s Ans to above ques : Ans.js

Here’s the output: output.jpg

Array’s .filter() Method

JavaScript’s Array .filter() method is similar to the .map() method:

  • it is called on an array
  • it takes a function as an argument
  • it returns a new array

The difference is that the function passed to .filter() is used as a test, and only items in the array that pass the test are included in the new array. Let's take a look at an example:

const names = ['Karen', 'Richard', 'Tyler'];const shortNames = names.filter( name => name.length < 6 );

Just as before, we have the starting array:

const names = ['Karen', 'Richard', 'Tyler'];

We call .filter() on the names array and pass it a function as an argument:

names.filter( name => name.length < 6 );

Again, just like with .map() the arrow function that's passed to .filter() gets called for each item in the names array. The first item (i.e. 'Karen') is stored in the name variable. Then the test is performed - this is what's doing the actual filtering. It checks the length of the name. If it's 6 or greater, then it's skipped (and not included in the new array!). But if the length of the name is less than 6, then name.length < 6 returns true and the name _is_ included in the new array!

And lastly, just like with .map() the .filter() method returns a new array instead of modifying the original array:

const shortNames = names.filter( name => name.length < 6 );

So shortNames will be the new array ['Karen', 'Tyler']. Notice that it only has two names in it now, because 'Richard' is 7 characters and was filtered out.

This was just a brief overview of how the .filter() method works. For a deeper dive, check out .filter() on MDN.

.filter() Quiz

Use the provided music data array and the .filter() method to create a new array that only contains albums with names between 10 and 25 characters long. Store the new array in a variable called results.

here’s the code

here’s the output

Combining .map() And .filter() Together

What makes .map() and .filter() so powerful is that they can be combined. Because both methods return arrays, we can chain the method calls together so that the returned data from one can be a new array for the next.

const names = ['Karen', 'Richard', 'Tyler'];const shortNamesLengths = names.filter( name => name.length < 6 ).map(  name => name.length );

To break it down, the names array is filtered, which returns a new array, but then .map() is called on that new array, and returns a new array of its own! This new array that's returned from .map() is what's stored in shortNamesLengths.

.filter() First!

On a side note, you’ll want to run things in this order (.filter() first and then .map()). Because .map() runs the function once for each item in the array, it will be faster if the array were already filtered.

.filter() and .map() Quiz

Using the same music data, use .filter() and .map() to filter and map over the list and store the result in a variable named popular. Use .filter() to filter the list down to just the albums that have sold over 1,000,000 copies. Then chain .map() onto the returned array to create a new array that contains items in the format:

<artist> is a great performer

The first item in the popular array will be 'Adele is a great performer'.

Here’s the code

Here’s the output

React is Just JavaScript Recap

React builds on what you already know — JavaScript! You don’t have to learn a special template library or a new way of doing things.

Two of the main methods that you’ll be using quite a lot are:

It’s important that you’re comfortable using these methods, so take some time to practice using them. Why not look through some of your existing code and try converting your for loops to .map() calls or see if you can remove any if statements by using .filter().

--

--