Tag: ES6

Understanding React Pure Components

Many people are confused by the difference between a Functional Component and a Pure Component. Most of them think that they are the same, but this is not true. When you use a React Pure Component, We need to import PureComponent from React:

    import React, { PureComponent } from 'react';

If your React component’s render method is “pure” (that means it renders the same result, given the same props and state), you can use this function to improve the performance of your application. A Pure Component performs a shallow comparison for the props and nextProps objects as well as the state and nextState objects. Pure components do not include the shouldComponentUpdate(nextProps, nextState) method, and if you try to add it, you’ll get a warning from React.

In this article, you’ll learn to create a basic example to understand how Pure Components works. To begin, you need to install the Chrome extension React Developer Tools to do a simple debug in your application. Download React Developer Tools from https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi.

Building your React application

First, create your React application using create-react-app. Once that is done, you can proceed to create your first React component.

Before you install create-react-app, remember that you need to download and install Node from www.nodejs.org. You can install it for Mac, Linux, and Windows.

Install create-react-app globally by typing this command in your Terminal:

  npm install -g create-react-app

Alternatively, you can use a shortcut:

  npm i -g create-react-app

Now build your first React application by following these steps:

  1. Create your React application with the following command:
create-react-app my-first-react-app
  1. Go to the new application with cd my-first-react-appand start it with npm start.
  2. The application should now be running at http://localhost:3000.
  3. Create a new file called js inside your src folder:
import React, { Component } from 'react';



class Home extends Component {

render() {

return <h1>I'm Home Component</h1>;

  }

}



export default Home;

File: src/Home.js

  1. You may have noticed that you are exporting your class component at the end of the file, but it’s fine to export it directly on the class declaration, like this:
import React, { Component } from 'react';

    export default class Home extends Component {

render() {

return<h1>I'm Home Component</h1>;

      }

    }

File: src/Home.js

  1. Now that you have created the first component, you need to render it. So, open the jsfile, import the Home component, and add it to the render method of the App component. If you are opening this file for the first time, you’ll probably see a code like this:
import React, { Component } from 'react';

import logo from './logo.svg';

import './App.css';

class App extends Component {

render() {

return (
 Welcome to React
);       
}     
}     
export default App;

To get started, edit src/App.js               and save to reload.

File: src/App.js

  1. Now change this code a bit. You need to import your Home component and then add it to the JSX. You also need to replace the <p> element with your component, like this:   
import React, { Component } from 'react';

import logo from './logo.svg';



// We import our Home component here...

import Home from './Home';

import './App.css';

class App extends Component {

render() {

return (

Welcome to React
{/* Here we add our Home component to be render it */}

);} } export default App;

File: src/components/App.js

  1. Now, create the Numbers component:
// Dependencies

import React, { Component } from 'react';
// Components
import Result from './Result';

// Styles

import './Numbers.css';



class Numbers extends Component {

state = {

numbers: '', // Here we will save the input value

results: [] // In this state we will save the results of the sums

};

handleNumberChange = e => {

const { target: { value } } = e;



// Converting the string value to array

// "12345" => ["1", "2", "3", "4", "5"]

const numbers = Array.from(value);

// Summing all numbers from the array

 // ["1", "2", "3", "4", "5"] => 15

const result = numbers.reduce((a, b) => Number(a) + Number(b), 0);



// Updating the local state

this.setState({

numbers: value,

results: [...this.state.results, result]

});
}

render() {
return (
  {/* Rendering the results array */}
              {this.state.results.map((result, i) => (                               ))}

)       }     }   export default Numbers;

File: src/components/Numbers/Numbers.js

  1. Then, create the Result component (as a Class Component):
import React, { Component } from 'react';



class Result extends Component {

render() {

return<li>{this.props.result}</li>;

      }

    }



 export default Result;

File: src/components/Numbers/Result.js

  1. Finally, create the styles:
.Numbers {

      padding: 30px;

    }

.Numbers input[type=number]::-webkit-inner-spin-button,

    .Numbers input[type=number]::-webkit-outer-spin-button {

      -webkit-appearance: none;

      margin: 0;

    }



 .Numbers input {

      width: 500px;

      height: 60px;

      font-size: 20px;

      outline: none;

      border: 1px solid #ccc;

      padding: 10px;

    }



.Numbers ul {

      margin: 0 auto;

      padding: 0;

      list-style: none;

      width: 522px;

    }



 .Numbers ul li {

      border-top: 1px solid #ccc;

      border-left: 1px solid #ccc;

      border-right: 1px solid #ccc;

      padding: 10px;

    }



.Numbers ul li:first-child {

      border-top: none;

    }



.Numbers ul li:last-child {

      border-bottom: 1px solid #ccc;

    }

File: src/components/Numbers/Numbers.css

How React Pure Component works…

If you run the application, you will see this:

  1. You have used an input with the number type, which means you’ll only accept numbers if you start writing numbers (1, then 2, then 3, and such). You will see the results of the sum on each row (0 + 1 = 1, 1 + 2 = 3, 3 + 3 = 6):

Now, inspect the application using React Developer Tools. You need to enable the Highlight Updates option:

After this, start writing multiple numbers in the input (quickly), and you will see all the renders that React is performing:

As you can see, React is doing a lot of renderings. When the highlights are red, it means the performance of that component is not good. Here’s when React Pure Components will help you. Migrate your Result component to be a Pure Component:

import React, { PureComponent } from 'react';



class Result extendsPureComponent {

render() {

return <li>{this.props.result}</li>;

      }

    }



   export default Result;

File: src/components/Numbers/Result.js

Now if you try to do the same with the numbers, see the difference:

With the Pure Component React, you do less renders in comparison to a Class Component. Probably, you may now think that if you use a Stateless component instead of a Pure Component, the result will be the same. Unfortunately, this won’t happen. If you want to verify this, change the Result component again and convert it into a Functional Component.:

import React from 'react';



const Result = props => <li>{props.result}</li>;



 export default Result;

File: src/components/Numbers/Result.js

See what happens with the renders:

As you can see, the result is the same as the Class Component. This means that using a Stateless Component will not help you improve the performance of your application all the time. If you have components that you consider are pure, consider converting them into Pure components.

If you found this article interesting, you can explore Carlos Santana Roldan’s React Cookbook to be on the road to becoming a React expert. React Cookbook has over 66 hands-on recipes that cover UI development, animations, component architecture, routing, databases, testing, and debugging with React.

How to Work with the Latest JS features in React

Working with the latest javascript features in React

React is mainly written with modern JavaScript (ES6, ES7, and ES8). If you want to take advantage of React, there are some modern JS features that you should master to get the best results for your React applications.

In this article, you’ll learn the essential JS features so that you are ready to start working on your first React application.

How to do it

In this section, you’ll see how to use the most important JS features in React:

  • let and const: The new way to declare variables in JavaScript is using let or const. You can use let to declare variables that can change their value but in a block scope. The difference between let and var is that let is a block scoped variable that cannot be global, and with var, you can declare a global variable, for example:
var name = 'Carlos Santana';

let age = 30;



console.log(window.name); // Carlos Santana

console.log(window.age);  // undefined
  • The best way to understand block scope is by declaring a forloop with var and let. First, use var and see its behavior:
for (var i = 1 ; i <= 10; i++) {

console.log(i); // 1, 2, 3, 4... 10

    }



console.log(i); // Will print the last value of i: 10
  • If you write the same code with let, this will be the result:
for (let i = 1 ; i <= 10; i++) {

console.log(i); // 1, 2, 3, 4... 10

    }



console.log(i); // Uncaught ReferenceError: i is not defined

  • With const, you can declare constants, which means that the value can’t be changed (except for arrays and objects):
const pi = 3.1416;

pi = 5; // Uncaught TypeError: Assignment to constant variable.
  • If you declare an array with const, you can manipulate the array elements (add, remove, or modify elements):
constcryptoCurrencies = ['BTC', 'ETH', 'XRP'];



// Adding ERT: ['BTC', 'ETH', 'XRP', 'ERT'];

cryptoCurrencies.push('ERT');



    // Will remove the first element: ['ETH', 'XRP', 'ERT'];

cryptoCurrencies.shift();



// Modifying an element

cryptoCurrencies[1] = 'LTC'; // ['ETH', 'LTC', 'ERT'];
  • Also, using objects, you can add, remove, or modify the nodes:
const person = {

name: 'Carlos Santana',

age: 30,

email: 'carlos@milkzoft.com'

    };



// Adding a new node...

person.website = 'https://www.codejobs.com';



// Removing a node...

deleteperson.email;



// Updating a node...

person.age = 29;
  • Spread operator:The spread operator (…) splits an iterable object into individual values. In React, it can be used to push values into another array, for example when you want to add a new item to a to-do list utilizing setState:
this.setState({

items: [

...this.state.items, // Here we are spreading the current items

        {

task: 'My new task', // This will be a new task in our Todo list.

        }

      ]

    });
  • Also, the Spread operator can be used in React to spread attributes (props) in JSX:
render() {

const props = {};



      props.name = 'Carlos Santana';

props.age = 30;

props.email = 'carlos@milkzoft.com';



return<Person{...props}/>;

    }
  • Rest parameter:The rest parameter is also represented by …. The last parameter in a function prefixed with … is called the rest parameter. The rest parameter is an array that will contain the rest of the parameters of a function when the number of arguments exceeds the number of named parameters:
functionsetNumbers(param1, param2, ...args) {

// param1 = 1

 // param2 = 2

// args = [3, 4, 5, 6];

console.log(param1, param2, ...args); // Log: 1, 2, 3, 4, 5, 6

    }



setNumbers(1, 2, 3, 4, 5, 6);
  • Destructuring: The destructuring assignment javascript feature is the most used feature in React. It is an expression that allows you to assign the values or properties of an iterable object to variables. Generally, with this, you can convert your component props into variables (or constants):   
// Imagine we are on our <Person> component and we are

    // receiving the props (in this.props): name, age and email.

render() {

      // Our props are:

      // { name: 'Carlos Santana', age: 30, email:

'carlos@milkzoft.com' }

console.log(this.props);

const{ name, age, email } = this.props;



      // Now we can use the nodes as constants...

console.log(name, age, email);



return (

<ul>

<li>Name: {name}</li>

<li>Age: {age}</li>

<li>Email: {email}</li>

</ul>

      );

}



// Also the destructuring can be used on function parameters

const Person = ({ name, age, email }) => (

<ul>

<li>Name: {name}</li>

<li>Age: {age}</li>

<li>Email: {email}</li>

</ul>

    );
  • Arrow functions: In Javascript ES6 provides a new way to create functions using the => These functions are called arrow functions. This new method has a shorter syntax, and the arrow functions are anonymous functions. In React, arrow functions are used as a way to bind the this object in your methods instead of binding it in the constructor:
    class Person extends Component {

showProps = () => {

        console.log(this.props); // { name, age, email... }

      }

render() {

return (       
// Consoling props: 
{this.showProps()}
);       }     }
  • Template literals: The template literal is a new way to create a string using backticks (` `) instead of single quotes (‘ ‘)   or double quotes (” “). React uses template literals to concatenate class names or render a string using a ternary operator:
render() {

const { theme } = this.props;



return (
<div>Some content here...</div>
);     }
  • Map: The map()method returns a new array with the results of calling a provided function on each element in the calling array. Map use is widespread in React and mainly used to render multiple elements inside a React component.For example, it can be used to render a list of tasks:
render() {

const tasks = [

{ task: 'Task 1' },

{ task: 'Task 2' },

{ task: 'Task 3' }

      ];



return (

<ul>

          {tasks.map((item, key) =><likey={key}>{item.task}</li>}

</ul>

      );

    }
  • assign(): The Object.assign()method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object. This method is used mainly with Redux to create immutable objects and return a new state to the reducers:
export default functioncoinsReducer(state = initialState, action) {

switch (action.type) {

caseFETCH_COINS_SUCCESS: {

const { payload: coins } = action;



returnObject.assign({}, state, {

coins

          });

        }



default:

return state;

      }

    };
  • Classes: JavaScript classes, introduced in ES6, are mainly a new syntax for the existing prototype-based inheritance. Classes are functions and are not hoisted. React uses classes to create class Components:
import React, { Component } from 'react';



class Home extends Component {

render() {

return<h1>I'm Home Component</h1>;

      }

    }



export default Home;
  • Static methods: Static methods are not called on instances of the class. Instead, they’re called on the class itself. These are often utility functions, such as functions to create or clone objects. In React, they can be used to define the PropTypes in a component:
import React, { Component } from 'react';

import PropTypes from 'prop-types';

import logo from '../../images/logo.svg';



class Header extends Component {

staticpropTypes = {

title: PropTypes.string.isRequired,

url: PropTypes.string

      };



render() {

const {

title = 'Welcome to React',

url = 'http://localhost:3000'

        } = this.props;



return (

<header className="App-header">

<a href={url}>

<imgsrc={logo}className="App-logo"alt="logo"/>

</a>

<h1 className="App-title">{title}</h1>

</header>

        );

      }

    }



export default Header;
  • Promises:The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. Use promises in React to handle requests using axios or fetch; also, you can use Promises to implement server-side rendering.
  • async/await: The async function declaration defines an asynchronous function, which returns an AsyncFunction This can also be used to perform a server request, for example, using axios:
Index.getInitialProps = async () => {

consturl = 'https://api.coinmarketcap.com/v1/ticker/';

const res = awaitaxios.get(url);



return {

coins: res.data

      };

    };

If you found this article interesting, you can explore React Cookbook, which covers UI development, animations, component architecture, routing, databases, testing, and debugging with React. React Cookbook will save you from a lot of trial and error and developmental headaches, and you’ll be on the road to becoming a React expert.