
Dedicated to Richard Matthew Stallman, the man who started the free software movement in order to give software users the freedom to use the software, to study and modify the software, and to redistribute copies of it with or without modification. His work on the GNU project is highly appreciated by the open source community.
With the popularity of frameworks such as Node, React, and Angular, web developers tend to render everything on the client-side, but there are several disadvantages to this approach. To protect sensitive information and optimize response times, developers might want to add server-side rendering to their applications. This book demonstrates how a React application can be rendered on the server-side using frameworks such as Next and Redux.
The book starts with the basic introduction to JavaScript, followed by the introduction to React. Once the reader is aware of both these concepts, the Next framework is introduced. The reader will then learn how to integrate Next to a React application in order to render content on the server-side. The reader will also learn about state management using Redux, unit testing using Jest, and deployment using Docker. At the end of this book, the reader will have all the knowledge necessary to build and deploy a fully server-side rendered application with scripts for unit testing.
To learn more, start reading right away.
The completion of this book could not have been possible without the contribution of numerous people whose names may not all be cited. Their contributions are sincerely appreciated and acknowledged. However, I would like to take this opportunity to express my gratitude particularly to the following:
Louise Corrigan , Senior Editor at Apress, andJames Markham , Development Editor at Apress, who saw potential in the idea behind the book. They helped kick-start the book with their intuitive suggestions and made sure that the content quality of the book remains uncompromised.
Alexander Nnakwue , Technical Reviewer of the book, who made sure that the practical aspects of the book are up to the mark. His insightful comments have been of great help in the refinement of the book.
Nancy Chen , Coordinating Editor at Apress, who made sure that the process from penning to publishing the book remains smooth and hassle-free.
Family, friends, and mentors , who have always been supportive of my aspirations and have guided me throughout my journey.
You , who wish to refine your skills by reading this book so that you can make a difference in the lives of those around you. You encourage me to contribute toward collaborative education.
Thank you!

is a software engineer with a multinational company. He has a bachelor’s degree in computer engineering and is the author of several independently published titles, includingArtificial Intelligence ,Beginning Machine Learning in iOS ,Data Mining & Business Intelligence ,iOS Programming , andMobile Computing & Wireless Communication . He has also published a research paper titled “Remote Health Monitoring using Implantable Probes to Prevent Untimely Death of Animals” in theInternational Journal of Advanced Research in Management, Architecture, Technology and Engineering .

has a background in mechanical engineering from the University of Ibadan, Nigeria, and has been a front-end developer for over three years working on both web and mobile technologies. He also has experience as a technical author, writer, and reviewer. He enjoys programming for the Web, and occasionally, you can also find him playing soccer. He was born in Benin City and is currently based in Lagos, Nigeria.
This chapter provides insight on JavaScript fundamentals that are necessary in order to start working with React. The purpose of this chapter is to introduce you to the basic programming paradigm followed in JavaScript so that you can better understand React when it is introduced in the following chapter.
Even if you are new to JavaScript, you need not worry as this chapter shall provide you with all the knowledge you need to get started. You will begin with learning simpler concepts such as constants, variables, and control loops and will go all the way learning sophisticated topics such as rest parameters, spread syntax, HTTP requests, and promises. By the end of this chapter, you will have a thorough understanding of the language and will be able to start building web applications with JavaScript.
JavaScript is one of the most popular languages for web development, and it is essential to learn this language in order to create applications that run on web browsers. Apart from web applications, JavaScript can also be used to create desktop, mobile, as well as server-side applications using various frameworks like Meteor, React Native, and Node.js. However, we will focus on web applications for the scope of this chapter.
JavaScript was created by Brendan Eich in the year 1995 and was standardized by ECMA (European Computer Manufacturers Association) in 1997. As a result, JavaScript is also known as ECMAScript (ES) . As the web browsers developed over time, so did JavaScript with the release of ES3 in 1999, ES5 in 2009, and ES6 in 2015. After ES6, there have been minor updates to JavaScript every year, but ES6 is by far the latest major release.
Let us now set up our development environment so that we can begin with practical examples on JavaScript programming.
In order to start programming with JavaScript, I’ll be using the Visual Studio Code editor which can be downloaded from https://code.visualstudio.com/download. However, you can use any editor of your choice.

Folder Structure for Starter Workspace
Note that we have used JavaScript’s getElementById() method to fetch a section from the template and then altered its text by setting the innerHTML property. You can also use getElementsByClassName() method and getElementsByTagName() method in order to access elements by class name and tag name. Since we already set the ID property of the <div> element in our HTML template, we used getElementById() method to fetch the section. We initially stored a reference to this section in a variable and then accessed its property using the variable. This is particularly useful when we have multiple properties to alter. You might not want to go and search for the section every time you want to modify a property. Hence, it is always a good programming practice to store references in variables if you are going to need it multiple times.
Press Ctrl+Shift+P to open the Command Palette.
Type “config” and select the “Tasks: Configure Task” command to open tasks.json.
If tasks.json file does not exist, the editor will ask you to create one with default template. Go ahead with “others” template.
Replace the tasks.json file content with following code:

Launch Configuration

Output for Starter Project
Now that our development environment is up and running, let’s explore some basic JavaScript concepts.

Variable Declaration Using let and var

let vs. var
Rest parameter is a feature of JavaScript that was introduced in ES6. It lets us handle multiple function input parameters as an array. It is particularly helpful in scenarios where the number of input parameters to a function is indefinite.
ES6 is the sixth version of ECMAScript and was created to standardize JavaScript. Since it was published in 2015, it is also known as ECMAScript 2015.
The preceding piece of code will also give you an output of “25” on your HTML template. The only difference here is that only the last two input parameters will be considered as rest parameters, whereas the first two are regular parameters. One of the major benefits of rest parameter is that array operations such as filter, sort, pop, push, reverse, and so on can easily be performed on input parameters.
The preceding piece of code will give you “Watermelon” as output. This is because when we use destructuring syntax (variables in square brackets separated by commas on left and an array or object on right), JavaScript automatically extracts values from the array on the right-hand side and starts assigning them to the variables on the left-hand side. Note that the values are assigned from left to right. So, for instance, if there are two variables on the left-hand side and four array elements on the right-hand side, then the first two values from the array will be assigned to the variables and the last two values will be left out. On the contrary, if there are four variables on the left-hand side and just two array elements on the right-hand side, the values will be assigned to the first two variables and the last two variables will be undefined.
The preceding piece of code will give you “Watermelon, Grapes, Guava” as output because the rest parameter syntax will assign all the remaining array elements to the “OtherFruits” variable.
The output of the preceding code should be “20”. What we are doing here is exactly opposite of rest parameter. We are creating a single array of input elements and passing it directly into a function that takes in three different parameters. The function declaration will be similar to that of a regular function. However, notice the syntax that we are using while calling the function (the three dots before the parameter name). This is known as spread syntax and this will do all the work for us. It is identical to the syntax of rest parameter. However, if you use it while calling the function, it will work in an opposite manner. So, instead of collecting input parameters and clubbing it into an array, it will destructure the array of input parameters and assign the values to the variables mentioned in the function declaration. You can also use the rest parameter and spread syntax at the same time. The manner in which it will behave will depend on the context. Let us now look at control loops.
JavaScript provides multiple ways to iterate through loops. Let us look at each one of them with examples.
We can use break and continue operators with all kinds of JavaScript loops. The continue operator is used to skip the remaining statements from the body of the loop and skip to the next iteration, whereas the break operator is used to terminate all the remaining iterations of the loop.

for Loop in JavaScript

forEach, while, and do…while Loop in JavaScript
There are some more variations of the forEach loop such as for…in and for…of. However, the ones listed earlier are major ones and will suffice for the scope of this chapter. Let us now look at type conversion in JavaScript.

Type Conversion in JavaScript
That is it on type conversion. Let us now look at operators and functions in JavaScript.
Operators are used to modify the values in a program. The values we modify using operators are known as operands. JavaScript provides multiple categories of operators. Let us discuss each one of them in detail.
Arithmetic operators are the ones that perform mathematical operations on numeric operands. Addition (+), Subtraction (–), Multiplication (∗), Division (/), Modulus (%), Increment (++), and Decrement (--) are examples of arithmetic operators.
Comparison operators compare the value of two operands and returns a boolean value based on the truthfulness of the operator. Equality (==), Type Equality (===), Inequality (!=), Greater Than (>), Greater Than or Equal To (>=), Less Than (<), and Less Than or Equal To (<=) are examples of comparison operators.
Assignment operators are used to assign values to operands. “=” operator assigns the value of right operand to the left operand, “+=” operator adds the value of right operand to left operand and assigns it to left operand, “–=” operator subtracts the value of right operand from left operand and assigns it to left operand, “∗=” operator multiplies the value of both operands and assigns it to left operand, “/=” operator divides the value of left operand to right operand and assigns it to left operand, and lastly, “%=” operand calculates the modulus after dividing left operand by right operand and assigns it to left operand.
Logical operators are used to combine two or more conditions and find out their combined truthfulness. The operator returns a Boolean value. Logical AND (&&) and Logical OR (||) are two of the logical operators in JavaScript. NOT (!) is another logical operator that is used to negate the boolean value that is returned.
Ternary operator is made up of three parts: condition, body 1, and body 2. Condition and body 1 are separated by “?” operator, whereas both the bodies are separated by “:” operator. Body 1 will be executed if the condition is true, whereas body 2 will be executed if the condition is false.

Operators in JavaScript

Functions in JavaScript

Closures in JavaScript
Now, let us understand what is happening here. When we assign the value of the function to the “increment” variable, the function is executed once and the entire body of the inner function is assigned to the variable because that is what the function returns. Now, when you call the function using the variable name, just the inner function will be executed. This way, the variable will remain private to the function and will be initialized just once during the assignment of function to the variable, thus fulfilling our purpose of having a private counter variable which can only be modified by invoking a designated function.
That is all about closures; let us now look at arrays in JavaScript.

Storing Objects in JavaScript Arrays
arr.sort() – This method sorts the array.
arr.forEach() – This method is used to iterate over all the array elements.
arr.push(value) – This method is used to add new element to the array at the last index.
arr.pop() – This method removes the last value from the array.
arr.shift() – This method removes the first value from the array and shifts the remaining values by one index.
arr.unshift(value) – This method adds a new element to the array at the first index and shifts the remaining values by one index.
Array.isArray(arr) – This method returns true if “arr” is an array.
arr.toString() – This method converts an array to string of values.
arr.join(separator) – This method is similar to the toString method, but you can specify a separator for the values.
arr1.concat(arr2) – This method is used to concatenate two arrays: arr1 and arr2.
arr.splice(position, deletecount, value1, value2,…) – This method is used to add new set of values to an array at specific position. The first parameter specifies to position at which the values need to be added, the second parameter is the count of elements to be deleted from the array, and the remaining parameters are the values that need to be added to the array.
arr2 = arr1.slice(firstindex, lastindex) – This method is used to create a new array from an existing array. The parameters specify the start and end index for the values that need to be fetched for the new array. If you do not specify the lastindex, JavaScript will take all the remaining values.

Arrays in JavaScript
That is all about arrays; let us now look at arrays in classes and modules in JavaScript.
We use “extends” keyword to inherit the properties and methods of the base class in the child class. We can use “super” keyword to access members of the base class inside the child class. Outside the class, we can access members of both base class and child class using the object of the child class. The preceding piece of code should give you “dog” as output in the browser console. When we create an object of “Dog” class, its constructor gets invoked which, in turn, invokes the constructor of “Animal” class and sets the “type” property value to “dog”. Then, when we try to invoke method “getType()”, it searches both parent and child class for this method and invokes it if found. Note that if you do not define any constructor in the child class, the parent constructor gets invoked automatically, but if you define a constructor in the child class, you need to call the parent class constructor manually by using the “super” keyword. That is all about classes. Let us now talk about modules.
You can export multiple objects from a file and import multiple objects from different files in a similar manner as shown in the preceding example. Note that in order to use modules in your project, you will also have to register the index.js script in your html file as “module” type instead of “text/JavaScript”. The preceding code should ideally print “dog” in your browser console. However, if you are using chrome browser, you are bound to get an error due to CORS policy. This means that you cannot import modules from other cross-origin files without a CORS header, which is not possible if you are running your app from local file system. The solution to this problem is to run your app from a server. To do so, we will create a local server using node.js.
After updating the “package.json” file, run the “npm install” command from the terminal to install dependency that we just added to the json file. A folder will be created in your project directory by the name “node_modules”. This folder will contain files for all the project dependencies. Now that we have added a development server to our project dependency and installed it, we can launch our application using “npm start” command in the terminal. Notice that the CORS policy error that we were facing earlier during the modules example is now gone and we see “dog” as output in the browser console, as expected. This is because our application is now running on the local server and not on the file system. Notice that the URL in the browser has been changed to “localhost” from file path. Also note that the server is now listening for changes in your project files. This means that as soon as you make any changes in the project files and save it, it will automatically be reflected in the browser and you do not need to manually refresh the browser every time you change a file.
getElementById(‘elementID’) – This method returns a single element having same ID as specified in the input parameter.
getElementsByClassName(‘className’) – This method returns a list of elements having same className as specified in the input parameter. Note that unlike the getElementById method, this method can return multiple elements because ID is unique for an element whereas class name is not.
getElementsByTagName(‘tagName’) – This method returns a list of elements having same className as specified in the input parameter. Since tag name is not unique to an element, this method can return multiple elements.

Accessing DOM Elements in JavaScript

DOM Modification in JavaScript
Note that an attribute by the name “isheader” is added to the element and its value is set to “true”. This is done with the help of setAttribute() method. Also, a border is added to the header section because of the use of style.border property in JavaScript code. There are several other properties of DOM elements that can be modified. More information can be found at https://developer.mozilla.org.

Reference Error in JavaScript

Error Handling in JavaScript
The preceding piece of code should print “ERROR: Custom Developer Error!” in the browser console. That is all about error handling in JavaScript. Let us now look at HTTP requests and promises.
Instantiate an object of XMLHttpRequest().
Bind a function to the state change event of request object. The code in this function will monitor the request for success or failure and perform operations on the returned data.
Create a connection to the HTTP resource using the request object.
Send the request.

XMLHttpRequest in JavaScript
“$” symbol is a constant in JQuery and is defined as static. We use this symbol to access the get method. The first parameter to this method is a string containing the URL to which the request is being sent. The second parameter is a function that will be executed if the request succeeds. The third parameter is optional and might contain data that needs to be sent along with the request. In the preceding example, we have used an arrow function that will log the response data to the browser console. The output of the preceding code should be similar to Figure 1-18. Even though this seems like a good way to deal with HTTP requests, it is not the ideal way. The get() method returns a promise which helps us work with the request in a much better way.
Promise constructor takes in a function with two arguments. These two arguments are again functions that are called for success and failure, respectively. In the preceding example, we create promise with an anonymous function. This function has two arguments: resolve and reject. In the body of the anonymous function, we are calling “resolve” function with a timeout of 100 milliseconds and passing “Resolved” as a value to the promise. Thus, the promise will be in success state and will store the message that we passed as a response. If we call “reject” function instead of resolve, the promise will be in error state.
That is all about creating a promise. Now, consider the scenario where you want to perform some operation based on success or failure of a promise. In that case, you will have to settle a promise using then() function. then() is a function in the promise object that takes in two arguments. The first argument is a function with one parameter which gets executed when the promise is in success state. The second argument is a function with one parameter which gets executed when the promise is in failure state. The parameter of these functions will contain the value that was returned during the resolution of the promise.
In the preceding piece of code, if you resolved the promise, the output on your browser console should be “Success: Resolved”, and if you rejected the promise, it should be “Error: Rejected”. Note that you might have to wait for a while before the promise is settled because you will be dealing with asynchronous operations here.
That is all about promises. With the end of this topic, we also come to the end of this chapter. In the next chapter, we will use the JavaScript concepts that we learned so far in order to learn about React.js, a JavaScript-based library.
JavaScript is the most important language for web development, and it is necessary to create applications that run on web browsers.
Constants are identifiers in JavaScript whose values remain same throughout the program, whereas variables are identifiers whose values are prone to change.
Variables are defined using either “let” or “var” keyword. It is recommended to use “let” keyword because variables defined using “let” are scoped and strictly checked for inappropriate usage.
Rest parameter helps us club multiple function input parameters into a single array. On the other hand, spread syntax is the exact opposite of rest parameter and helps us destructure an input array into multiple variables.
Control loops such as for, forEach, while, and do...while are used to work with iterations in JavaScript.
Type conversion is a provision built in JavaScript that can be used to explicitly convert member of one data type to another.
Various arithmetic, comparison, assignment, logical, and ternary operators are provided in JavaScript that can be used to modify the values of operands.
Functions are pieces of code that can be written once and utilized multiple times in a program.
Classes and modules help us get the essence of object-oriented programming in JavaScript. Modules help us organize our code into files and share the code across the project using export and import keywords.
We can access and modify HTML elements of our web page using JavaScript's document object.
Errors in JavaScript can be handled using try-catch block. “finally” block can also be used optionally. Custom errors can be generated using the “throw” keyword.
XML http requests can be used to fetch data from remote server or APIs. However, get() method of JQuery library is much more convenient to do so.
While working with asynchronous requests, promises can be used to conveniently deal with success and error states of the response.
React.js is an open source JavaScript library created by Facebook in May 2013. It is used for building user interfaces. The best part about React is that it uses a declarative style of programming rather than an imperative style. While the former one specifies the compiler what to do, the latter one also has to specify how to do it. Thus, programming with React results in less code.
In this chapter, we will understand the underlying principles of React, one at a time. We will also see how each principle works in practice. If you have studied the previous chapter, this chapter should not be difficult to comprehend. If you have not, I recommend you to once go through the previous chapter.
In order to start programming with React, I’ll be using the Visual Studio Code editor which can be downloaded from https://code.visualstudio.com/download. However, you can use any editor of your choice.
Node.js is an open source, cross-platform runtime environment that helps us write JavaScript applications and execute it. We installed node.js during the previous chapter while we created a local server for working with cross-origin requests for module imports in JavaScript. If you have not yet installed node.js, you can download and install it from https://nodejs.org/. Once it is installed, you can open a terminal in your editor and run “node -v” command to check if the node.js has installed correctly. If yes, the terminal will display the installed version number of node.js.
Node.js runtime has thousands of modules that are readily available for use. These modules are nothing but pre-written JavaScript applications that can be reused in your code. These modules can be added to your code using npm (Node Package Manager). npm is shipped along with node.js and should already be installed in your system if you have installed node.js. You can execute “npm -v” command in the terminal. If installed correctly, this command will display the version of npm installed in your system.
Another way is to manually create a folder for your project and add a “package.json” file with a list of all the dependencies. You can then use the “npm-install” command to install all the dependencies into the “node_modules” folder in your project folder. Once the dependencies are installed, you can start referencing the dependencies in your JavaScript and HTML files.

create-react-app
If you look at the file explorer, you will see an “index.html” file in the “public” folder and lots of .js files in the “src” folder. These JavaScript files are the true essence of react. They create components and render them on the browser. Since we are going to learn about react components one by one, we can delete all the files in the “src” folder for now. Note that as soon as you delete the files, you will start getting a not-found error for the “index.js” file. This is because “create-react-app” has a dependency on react-scripts which uses a webpack configuration file to specify an entry point for the application as “index.js”. So when we delete the files, it will no longer be able to find an entry point into the application and will throw an error. To resolve this error, we will add an empty “index.js” file for now. If you look at the browser screen after adding the file, you will notice that the output will be a blank window but there will be no errors.
Components are a major backbone of React. They are similar to functions, take in props (input), output UI elements, and can be reused as and when required in other files. Even though they are similar to functions, you need not invoke them. They can be used like HTML elements (<ComponentName/>).
Its reactive nature is another important concept in React. This relates to data binding. Data in a react component comes from props, which are component input. When this data changes, the UI changes as well. This is handled automatically by React.
Another great concept of React is that HTML is generated using JavaScript. And this is justified because when your application receives data from the server, you need to process that data before presenting it. You can either use HTML to do this or you can use JavaScript, which is a way better option. Now that you are using JavaScript to process the data, you might as well present it using JavaScript. That’s exactly what React does.
This brings us to the next concept of React: the virtual DOM. Since HTML is generated using JavaScript, React would not have access to the DOM before it is generated; hence, it keeps a virtual representation of the views and then uses it to compare the changes in UI.
Let us now look at some more concepts of React which are necessary to understand in order to build a React application.
Traditionally, when your application contains multiple pages and you click a link to navigate to another page, a new request is sent to the server and the browser then loads the new page when a response is received from the server. This process is very time- and resource-consuming. It can be improved with the implementation of single-page applications (SPAs). This is something popularized by client-side rendering provided by JavaScript frameworks such as React. In SPAs, you only load the page once. Later on, when the user requests a new page, JavaScript interprets the request, asynchronously gets data from the server, fetches the UI component that needs to be updated, and updates the section of the page with new data without reloading the entire page.
Due to the asynchronous nature of such requests, the user might have to wait for a while before the UI changes. However, user experience can be enhanced by using attractive loaders. A major benefit of SPAs is that resources that remain constant throughout the application (such as stylesheets and scripts) need not be reloaded every time a request is made, resulting in quicker response time. However, search engines have trouble indexing the SPAs. This is why if your application needs indexing, relying entirely on client-side rendering is not a good idea. Another point that you need to keep in mind is that unlike most server-side programming languages, JavaScript does not have a built-in mechanism to handle memory leaks. It is your responsibility to take care of memory issues because if existent, they might exhaust the browser memory and significantly decrease the speed of your application. In the later part of this book, we will see how to tackle these issues by implementing server-side rendering in React applications.
If the method returns true, React will update the UI for the component. If the state object is mutable, the value of “this.props.myProp” will immediately be modified when the state changes and there will be no trace of previous value to compare. Since the state object is immutable, a new object (nextProps) will be created when you modify the state which will hold the new value. Due to this, React can easily compare new values with the old ones before updating the UI.
Note that immutability has some disadvantages as well. For example, you have to make sure that you use methods like setState() to modify objects like the state object in React. If not used carefully, Immutability might hurt the performance of your application.
The output of the preceding function depends on time and, hence, will be different every time you invoke it. These kinds of functions are impure functions. Not all functions can be pure. Sometimes, you might want to get some inputs from the outside world or make some changes to the external environment. In such cases, we use impure functions.
In React, a component is referred to as a pure component if its output depends only on its props (function inputs). If the state of the component is involved in computing its output, the component is said to be impure.
In the preceding example, we are passing a paragraph tag while rendering the generic button component. We are not passing this as a property inside the props. So the question is where will props store it? React has a simple explanation for this. Anything written between the opening and closing tag of a component is stored in a special property: props.children. One thing to note is that simply passing the children elements while invoking the component is not enough. React will only render the children elements if we have used a placeholder for the props.children property. That’s it about composition in React. If the picture is a bit blurry to you right now, don’t worry. Things will get clear as we move forward into the chapter. Let us now look at component types in React.
When we installed React to our project using the “create-react-app” command at the beginning of this chapter, it created multiple JavaScript files under the “src” folder for our project, most of which we deleted. We also cleaned up the index.js file which was the starting point of our application. We will create a new JavaScript file for our component in the “src” folder. We will then import this component in index.js file and render the newly created component. We will create a component with an input box, a button, and a label. On the press of a button, the component should override the label text with the text in the input box.
To do this, we will have to render these elements to the browser. As discussed earlier, React renders HTML to the browser using JavaScript. We will see two different approaches to do this – one using JavaScript and the other using JSX.
While using JavaScript, we use two major methods to create and render a component – createElement() and render().
The “type” argument can either be a tag name such as “div” or “p” or it can be a React component.
The “props” argument can be used to specify any property values such as “id” or “name” for the element in the form of a JavaScript object.
The “…children” argument specifies the child elements of the element that we are creating. It can be in the form of a number, text, or another React element.
The “element” argument is the element that you created using the React.createElement() method. You can store the output of the createElement() method in a variable and pass it as the “element” argument.
The “container” argument is the parent element within which you wish to render the current element. You can use JavaScript’s document.getElementById(), document.getElementsByClassName(), or document.getElementsByTagName() to fetch the parent element and pass it as “container” argument.

Creating Elements Using JavaScript and JSX
Now that you are familiar with the JavaScript approach of creating and rendering elements, let us look at a better approach.
As you see, the JSX approach gives us the same output as the JavaScript approach but has a way better developer experience. Thus, we will use JSX to create our first react component.
There are two ways you can create a component in React – one using functions and another using class. A major difference between the two is the syntax. Function components are created using plain JavaScript functions that take in props as an input parameter and return a react component. On the other hand, class components are created using JavaScript class syntax and need to extend from React.Component class. A major benefit of using class components is that you can use React’s state object which is provided by React.Component class. Since function components are plain JavaScript functions, you cannot use the state object in function components. We will learn about the concept of state later in the chapter.

First React Component
Props are nothing but values that are passed to React components with the help of HTML attributes while invoking them using JSX. Passing props is not necessary unless you are using them in the component. However, React recommends that you always pass props in order to ensure compatibility with future changes. Props that are passed to a component can be accessed using “this.props.propName” syntax. One thing to note is that if you are using class syntax to create a component and you have defined a constructor function, it is always advisable to pass props to the constructor function as well as React.Component class via super() method. Consider the following example:
React props are read-only and you will not be able to modify their value.
In the preceding example, we are passing a simple string as props and displaying it on a label, but you can also pass variables and objects by wrapping them in curly brackets.
So far, we have learned how to create react components using JSX and render it to the browser. This is enough to create static web sites. However, React is well known for the creation of user interactive interfaces, one that reacts to user events. To build such interfaces, it is necessary to understand how React manages state. Now, you might wonder that we already built a react application that reacts to the user’s button click event in order to update a label. We did this using JavaScript’s built-in event handler. React, on the other hand, has a better way of managing this, which is by using state.
State is an object that contains a set of properties that controls the behavior of the component. The values of these properties might change over the lifetime of the component. Instead of re-rendering the entire view every time some value changes, we can store this value inside the state object, and whenever the state object gets updated, React will partially update the view. The components that use the state object are Stateful components and the ones that do not are Stateless components. As discussed earlier, since state object is available by extending from React.Component class, it can only be used in class components and not in function components.
Note that Stateless components are also known by the name Presentational components and Stateful components as Container components.
The output of the preceding code should be similar to Figure 2-3. We are doing the same thing that we did in our first React application. We have a textbox, a label, and a button. On the click of the button, the text entered in the textbox should reflect on the label. However, the major difference here is that we are using React’s built-in state object to store the initial label value, and instead of directly updating the label, we will update the state object while React will handle the changes in the view.
We have initialized the state object in our class constructor. Note that we have extended the React.Component class to our class. This is where the state object comes from. Before initializing the state object in the constructor, it is necessary to call the super() method that will allow us to access members of the React.Component class in our class. The JSX code that the component returns is the same as the one that we wrote earlier while creating our first React app. The only difference is that the value of the label is now bound to the state object property using the curly braces. Doing this helps React in understanding that it needs to change the value of the label when the state object changes.
While working with the state object, keep in mind that it is case-sensitive. So, if you write “State” instead of “state”, React will consider it as a normal JavaScript object instead of the built-in state object.
The other difference that you will notice is in the UpdateText() method which executes on the click event of the button. Instead of directly updating the label, unlike last time, we now use the setState() method to update the property value of the state object. The setState() method is provided by the React.Component class to modify the state object and can be accessed using “this” keyword. When the state changes, React will automatically update the label value in the view. This is the benefit of using the state object.
You should always use the setState() method while modifying the state object instead of directly updating the value using the assignment operator. Because when this method is called, React compares the new virtual DOM with the existing one and makes necessary changes to the UI. If you directly update the values using the assignment operator, React will never know about the changes in the virtual DOM and it will not be reflected on the UI.
One of the major benefits of using state is that it enables the creation of interactive components. For instance, if a user is interacting with one particular component on a screen with multiple components, react will only make changes to that particular component and the other components will completely be isolated to those changes.
Another thing to know about the state object is that it is immutable. So, when you modify the value of the state object using the setState() method, a new copy of the object is created. This allows a comparison between the previous state and the new state. That is how React keeps track of changes and updates the UI.
Even though the state object is similar to the props object, a significant difference between the two is that unlike props object, the state object is private to a component and is completely controlled by the component. When you pass down props to a component, it cannot modify them because they are read-only. But in the case of the state object, the component has the complete liberty to make any kind of changes.
Despite all these benefits, one might opt against using the state object. It is up to you to decide whether you want to build a stateful component or a presentational component. That is it about the state object. Let us now look at the lifecycle of a React component.

The Lifecycle of a React Component
The three major phases of the React component lifecycle are mounting, updating, and unmounting.
constructor(props) – The constructor is the first method that is called when a component is instantiated. This is the place where the initial state of the component is set and methods are bound. If you do not have to initialize the state and bind any methods, you do not need to implement a constructor for your component. However, if you do implement the constructor, the first thing that you always need to do is call the parent constructor from your constructor using the super(props) method. This will allow your component to inherit the properties of React.Component class. If you do not do this, then you will not be able to access “this.props” object in your constructor. One important thing to note is that the constructor is the only place where you can directly assign value to the state object using the assignment operator. At all other places, you need to use the setState() method.
Note It is always recommended that you pass props to the constructor of your component as well as the parent class, even if you are not using any props value. This will ensure compatibility with future changes.
render() – This is the only required method in a React component. It examines the “state” and “props” object in order to return HTML to the DOM. Note that this function should be pure, meaning that it should return the same output every time it is invoked and should not tamper with the state of the component. If you need to perform operations that might modify the component state, such code should be written in componentDidMount() method instead.
componentDidMount() – This method is invoked immediately after a component is mounted to the DOM tree. The operations that require the elements to be present on the DOM should be performed here. For instance, if you need to load data from a remote resource, this method would be a good place to initiate a network request. If your component needs to subscribe to some events, you can write that code here. However, make sure that you do not forget to unsubscribe the subscriptions in the componentWillUnmount() method. Also, if you want to update the state of the component, setState() method should be invoked from here.
getDerivedStateFromProps(props, state) – This is the first method to be invoked when a component gets updated. If the state needs to be updated, this method should return an object, else it should return null. This method is used in scenarios where the state needs to be updated depending on the updates to the props object.
shouldComponentUpdate(nextProps, nextState) – This method returns a Boolean value to let React know whether the view should be re-rendered. It returns “True” by default so React will re-render the view on every state change. You can use this method for performance optimization. Whether or not the view needs updating can be decided manually by comparing this.props with nextProps and this.state with nextState.
render() – This is the same as the one that is called when a component is mounted for the first time. However, in this case, render() method will not be invoked if shouldComponentUpdate() method returns “False”.
getSnapshotBeforeUpdate(prevProps, prevState) – This method is invoked just before the updated values are committed to the DOM tree. It gives us a chance to capture any information related to the current state of the component. The value returned by this method will be passed as a parameter to the componentDidUpdate() method.
componentDidUpdate(prevProps, prevState, snapshot) – This method is invoked immediately after the DOM has been updated. It will not be invoked if shouldComponentUpdate() method returns “False”. This is a good place to initiate a network request if necessary. For instance, you might want to post the updated data values to some remote data server. To do so, you can compare prevProps with this.props to determine whether the values have changed and initiate a POST request depending on the result of the comparison.
componentWillUnmount() – This method is invoked just before the component is about to be removed from the DOM tree. This is a good place to perform cleanup operations. For instance, you might want to unsubscribe from any events that the component subscribed to during componentDidMount() method or cancel any network requests that are in the pipeline.
Now that you have a thorough understanding of the lifecycle of React components, let us study about Hooks in React.
We have discussed earlier in this chapter that there are certain functionalities, such as state object and lifecycle methods, provided by React.Component class which can only be used within class components. With the introduction of Hooks in React 16.8, this is no longer the case.
Don’t call Hooks inside loops, conditions, or nested functions. Only call Hooks at the top level of your function component.
Don’t call Hooks from regular JavaScript functions. Only call them from React function components or custom Hooks.
Hooks do not work inside class components. They can only be used within function components.
React provides a few built-in hooks to start with. However, developers can write their own custom hooks and use them in their applications. In the following section, we will learn about the two of the most used React hooks – State Hook and Effect Hook, both of which comes built in to React.
When you render this component using ReactDOM.render() method in your index.js file, you should get browser output similar to Figure 2-3. We first import the useState() method from the React library, then we declare constants “outputValue”, which will store the label text, and “setOutputValue”, which will be the method that updates the state. To get the values for these two constants, we invoke the useState() method with initial value as an input parameter.
We invoke the setOutputValue() method with the new value as an input parameter whenever we want to update the state value, in this case, on button click.
You will notice that we have not manually updated the view from the code. We have just updated the value of our state object. It is important to note that this is a function component and we are not extending the Component class. Despite this, we are able to use the state object provided by the Component class and React automatically re-renders the view as soon as the state object is modified. This is the power of State Hook provided by React. Let us now look at one more built-in Hook in React that is widely used.
Effect Hook lets you perform side effects in a function component. This means that if you want to perform some operations based on the lifecycle events of a react component, Effect Hook is the ideal one to use.
Operations such as initiating a network request for data, subscribing to events, and manually updating the DOM are known as side effects because such operations might affect other components and cannot be performed during rendering.
In the preceding example, we are importing the useEffect() method from the React library and invoking this method in our component with an anonymous function as an input parameter. React will execute this function every time the component is rendered. Hence, you will see an alert every time you update the value of the label. Now, you might wonder that this solves our problem of performing subscription operations when the component is mounted or updated, but what about the cleanup or unsubscribe operations that we need to perform when a component is about to be unmounted?
On executing this code, you will notice that you see two alert boxes, one after the other. The first one indicates that the component has been mounted, and the second one tells you that the component is about to be unmounted.
Hence, to summarize, you pass an anonymous function to the useEffect() method. Anything you write in this function body will be executed when a component is rendered. Anything that is returned by this function will be executed when the component is about to be unmounted from the DOM tree.
What we are doing here is that we are invoking the useEffect() Hook that displays an alert whenever a component is updated. We know that a Hook can call another Hook. So, we will now create a custom Hook that will take an input argument and will display the alert for us whenever the calling component is updated. I have created a new folder “Hooks” under the “src” folder that will contain all my custom Hooks. You can follow the structure of your choice. Let us create a new file “useChangeAlert.js” for our Hook. It will contain the following code:
We have created a simple JavaScript function that will display an alert with the input parameter as a message whenever the calling component is updated. This will act as our custom Hook. Note that we have used React’s built-in useEffect() hook to know when the calling component is re-rendered. Let us now consume this custom Hook in our component. Look at the following piece of code that goes in your MyComponent.js file:

Custom Hooks in React
On updating either of the values and clicking their respective buttons, you will see an alert box with their respective alert messages along with the new label values. This is how stateful logic is shared across React components using custom Hooks. Let us now learn how to work with data in React components.

Working with Data in React
I have applied some basic CSS to the elements so do not worry if your output is not exactly similar to mine. You can customize your styling using your own CSS. We are using a combination of JSX and JavaScript in this component. We use JavaScript’s array.map() function to iterate on our data array and execute the JSX code for each element in the data array. This is how we work with data in React components. Now, let us learn about fetching data from a remote server using asynchronous JavaScript calls.
data – This is an object that will store the data that we fetch from remote API. Initially set to an empty object.
error – This is an object that will store the details of any error that occurs during the data operation. Initially set to null.
isLoaded – This is a Boolean property that will tell us whether the data has been loaded into the data object or not. Initially set to false.

AJAX Request in Progress
then() method is an extension to the get() method and will be executed if the promise is fulfilled by the get() method. Hence, in this method, we have written the code that we want to execute if the network request is successful. We have filled the data object with the data that is returned by the get request and set the isLoaded property to true.

Error During AJAX Request

Successful AJAX Request
That’s it, you have successfully created a data-oriented React application. You can play around with other APIs available in the public domain. For instance, you can take input from the user and fetch details for a specific GitHub user by passing username as a parameter to the API call. The more you play around, the better you will understand it.
Let us now look at how to add styling to our React application.
If you have executed the previous GitHub Users application code, you must have noticed that your output slightly differs from Figure 2-9. That is because I have added some CSS to my application code in order to add styling to the elements, which might be missing from your code.
There are various ways to style your React components. Some of them are discussed in the following section.
Inline CSS is the least preferred way of styling your React components because it makes the code structure very messy and unreadable. A better way of using CSS is to create a separate stylesheet and import it in your component file or root application file. That is the approach I have followed for our previous example. The following is the stylesheet I have written for the GitHub Users example:
This is a much better approach as compared to inline CSS and results in a much better code structure as well as lesser code size due to the reusability of the stylesheet.
SASS is the most popular option when it comes to styling React applications. It stands for Syntactically Awesome Style Sheets and is a preprocessor that compiles the input into CSS code. The newer version of SASS is known by the name SCSS (Sassy CSS) and has a slightly different syntax as compared to SASS. Both SASS and SCSS are similar to CSS stylesheets but are much powerful with support for CSS variables and mathematical operations.
SASS has a loose syntax that uses indentation instead of curly braces to indicate nesting of selectors and newlines instead of semicolons to separate properties. These stylesheets have “.sass” file extension.
SCSS, on the other hand, is closer to CSS syntax with the use of curly brackets to indicate nesting of selectors and semicolons for separation of properties. This is why every CSS stylesheet is a valid SCSS stylesheet with identical interpretation. These stylesheets have “.scss” file extension. Consider the following example that demonstrates SASS and SCSS:
You can also pass a parameter to a Mixin as follows:
Once this is installed in your project, you can start using SASS and SCSS without any further configuration. All you need in this case is a “.sass” or “.scss” file and you are good to go.
There are many other ways to add styling to your application such as Styled Components, Less, CSS Modules, and so on. However, in my opinion, SASS and SCSS are better than the other approaches.
That’s it about styling. Let us now look at Babel and Webpack.
Babel is a JavaScript compiler that has solved a very big problem for the entire community of developers – backward compatibility. We all have faced issues with browsers like Internet Explorer and Edge not being able to support the latest JavaScript functionalities. For instance, arrow functions introduced in ES6 are supported by most of the modern browsers but not by IE 11. In such cases, Babel comes to the rescue. It takes code written in one standard, and it compiles it to code written in another standard. However, Babel is not going to compile anything by itself. We will have to install several plugins to support a particular feature in older browsers.
Webpack, on the other hand, is a module bundler that handles bundling and minification of our application files. It goes through our application and creates a list of all the modules that our application is dependent on in order to function correctly. Then it creates a pluggable bundle or package which contains the minimum number of files required for our application. It generally requires a webpack.config.js file where we specify the entry point for our application and other relevant information regarding the application output.
Now let’s create the following script.js file to test whether babel is working correctly or not:
@babel/preset-env – Converts ES6, ES7, and ES8 code to ES5
@babel/preset-react – Transforms JSX to JavaScript
A loader lets us customize the behavior of the webpack when it loads certain files. We can define a loader by setting the module property to an array of rules in the webpack.config file. In this case, we have set the “loader” property of the rule to babel-loader which will tell the webpack to convert the JSX code to JavaScript code. The “test” property allows us to specify what kind of files we want to run the loader on. We specify a pattern for files that end with “.js”. We can use the “exclude” property to exclude a set of files. In our case, we exclude the node_modules folder since we do not want babel to scan those files.
The code snippets that you have seen in this topic are not enough to create a full-fledged React application. There are lots of other webpack configurations that you need to do. However, if you have created your application using the “create-react-app” command, everything is pre-configured and you need not worry about configuring webpack.
That is it. Webpack is now set to identify JSX code and compile it to JavaScript code using babel. With that, we come to the end of this chapter. Let us summarize what we have learned.
React.js is an open source JavaScript library that is used for building user interfaces.
React generates HTML using JavaScript. It renders everything in form of Component.
Components in React are similar to JavaScript functions. They take in input parameters and output UI elements. Components can be used like HTML elements.
When the state of a component changes, the UI changes automatically.
Changes in UI are compared using virtual DOM since the actual DOM is not accessible until UI is rendered.
Single-page applications, Immutability, purity, and composition are some of the important concepts related to React.
“create-react-app” command can be used to create a starter application in React. To do so, you will need Node.js environment and Node Package Manager (npm) installed in your system.
You can either create React components using traditional JavaScript syntax or use the modern JSX syntax which is much closer to HTML.
There are two approaches to create a React component – classes and functions.
The class component allows you to extend React.Component class and inherit React lifecycle methods as well as the state object. To do so in function components, you need Hooks.
You can use the State Hook to create a stateful function component, whereas to step into lifecycle methods of React in a function component, you can use Effect Hook. You can also create custom Hooks that suit your application requirements.
The lifecycle of a React component includes mounting, updating, and unmounting.
render() method gets invoked every time a component is updated or when it mounted for the first time.
componentDidMount() method tells us that the component has been mounted, and componentDidUpdate() method tells us that the component has been updated.
componentWillUnmount() method gets invoked just before a component is about to be unmounted from the DOM.
You can fetch data for your application from a remote resource using the Axios library for AJAX calls. You can use JavaScript’s array.map() function to iterate on an array data.
componentDidMount() is the ideal place to initiate network requests for getting data.
SASS and SCSS are the most popular alternatives to style your React application.
Babel is a JavaScript compiler that is used to add backward compatibility to your code.
Webpack is a module bundler that handles bundling and minification of your application files.
In the previous chapter, we learned about a JavaScript framework called React.js and how to create a client-side rendered application using the React.js framework. In this chapter, we will learn about a framework called “Next.js” that is used to build applications that are rendered on the server-side.
We will learn about the features of Next.js framework, routing in an application built using Next.js, dynamically loading the content, and configuring webpack and Babel, among other things. We will also create an interactive Next.js application from scratch as a part of this chapter.
Subsequently, we will learn how to integrate frameworks such as Redux for state management and GraphQL for API queries to our Next.js application. Let us get started.
Clients who do not have JavaScript enabled in their browsers might not be able to view the content.
We might simply want to render certain content on the server-side due to security reasons, which is not possible in a plain React.js application.
Rendering everything on the client-side significantly increases the loading time of the application.
It is difficult for search engines to index single-page applications built using plain React.js.
All these problems can be solved with the help of server-side rendering. Next.js is a framework that provides us just that. Every time a request is received, it dynamically generates a page at runtime with the help of a server. It is used by leading companies such as Netflix, Docker, GitHub, Uber, Starbucks, and many more. Let us look at the features of the Next.js framework.
Hot reloading – Every time a change is detected on a page, Next.js reloads the page so that the change is immediately reflected.
Page-based routing – URLs are mapped to the “pages” folder on the file system for you to use it without any configuration. However, dynamic routes are supported as well.
Automatic code splitting – Pages are loaded with just the code that they need which results in faster loading.
Page prefetching – You can use the “prefetch” prop on the <Link> tag while linking pages in order to prefetch pages in the background.
Hot module replacement (HMR) – You can replace, add, or remove modules from an application on runtime using HMR.
Server-side rendering (SSR) – You can render the page from the server-side instead of generating the entire HTML on the client-side. This results in a shorter loading time for content-rich pages. SSR also ensures that your pages are easily indexable by search engines.
Let us look at these features in action by getting started with our own Next.js application.
In order to get started with your own Next.js application, it is necessary that you have Node.js installed on your system. You must have installed it while practicing React.js examples during the previous chapter. If you have not, you can download and install it from https://nodejs.org/. Once it is installed, you can open a terminal in your editor and run “node -v” command to check if the node.js has installed correctly. If yes, the terminal will display the installed version number of Node.js. We will be using npm (Node Package Manager) to initialize our application and install dependencies to our project. npm comes bundled along with Node.js and should already be installed in your system if you have installed Node.js. You can execute “npm -v” command in the terminal. If installed correctly, this command will display the version of npm installed in your system.
I’ll be using the Visual Studio Code editor which can be downloaded from https://code.visualstudio.com/download. However, you can use any editor of your choice.

Next.js Application Startup
Notice the sleek and user-friendly design of this error page. This is how Next.js handles errors. It can also handle other errors such as 500 – Internal Server Error. The cause of the 404 error is that there are no pages in our application. On application launch, Next.js tries to find the “index.js” file in the pages and renders it by default. In our case, since it is not able to find it, we are greeted with a 404 error. Let us now create our first page. Add “index.js” file to the “pages” folder with the following code:

First Page in Next.js
Let us now test if the content is really getting rendered on the server-side. If you right-click the page and view the page source, you will notice that the HTML content generated in code is directly getting filled into the root HTML tags. This is because everything is being rendered on the server-side. If you do the same for an application built using plain React.js, you will notice just the root HTML tags in the page source and not the content generated by the code. This is because, in a React.js application, the content is rendered on the client-side after the page gets loaded. Thus, we can be assured the Next.js renders our pages on the server-side.
In the next section, we will create another page for our application and see how to navigate between pages using Next.js routing.
So far, we have had only one page, but an application might have multiple pages and easy navigation between those pages is an important aspect of any application. Let us create an “About” page with the following code:

Second Page in Next.js
Now, to establish a link between the two pages, you might think of creating an anchor tag with the page URL passed to the “href” attribute. Let us do that and see what’s happening:
If you run the app, you will see a link to the “About” page. However, if you click the link, you will notice that the entire page gets reloaded. This is because the anchor tag sends a new request to the server and the routing will happen server-side. This might result in performance issues so you might want to keep the routing to the client-side.
Next.js provides <Link> component for creating links for client-side routing. It is a wrapper that works with any component that accepts “onClick” prop. Hence, we will use it with an empty anchor tag. Consider the following change in the code:

Routing in Next.js
Most scenarios of client-side routing break the browser navigation buttons. However, Next.js has full support for the History API so it won’t break your browser navigation buttons.
The History API lets you interact with the browser history, trigger the browser navigation methods, and change the address bar content. It is especially useful in single-page applications where you never really change the page, just the content is changed. A stack is maintained. Every time the user navigates within the same web site, the URL of the new page is placed at the top of the stack. Whenever the user triggers the browser navigation buttons, the pointer of the stack is adjusted and the appropriate content is rendered.
That is it about routing in Next.js. Let us now look at dynamic pages in Next.js.
Most of the real-time applications have content that is generated dynamically. Hence, we cannot rely on static pages in a practical scenario. Let's see how to generate dynamic content for our application. First of all, we will create a file, DynamicRouter.js, that will create links based on the props. Consider the following code:

Dynamic Links in Next.js
Let us now create a page that will dynamically display content based on the parameter it receives. We will then set these three links to navigate to this dynamic page with different parameters. Consider the following code for the new page:

Dynamic Page in Next.js
If you notice the URL that gets generated, you will see that the query parameters are displayed on the address bar. You might want users to see a clean URL that does not display the query parameters. This is possible in Next.js by using the “as” attribute of the “Link” component. Whatever you pass to the “as” attribute will be displayed in the address bar. Let us try this:

Custom URL for a Next.js Page
That is it about dynamic pages in Next.js. Let us now learn how to deal with multimedia content in a Next.js application.
At times you might want to add multimedia content such as images and videos to your application. Generally, it is preferred to add URLs to such content in the CSS itself so that it is easy to maintain. Let us add images next to the links on the index page. I have downloaded three images and added them to the “static/Images” folder at the root of our application. Next.js provides something called JSS (CSS in JS) which allows us to define styles directly inside JSX code. Let us add the following code to “index.js” file to add images using CSS:
Now that we have defined the styles, we might want to use these styles on our page. To do so, we need to pass the class name from “index.js” file as a prop to the <Link> component and use it in “DynamicRouter.js” file to create a <div> for the image and set the class name for it. Consider the following changes to code:

Multimedia Content in Next.js
Once installed, you will have to add a config file “next.config.js” to the root of your application with the following code:
If you save the changes and go to the browser window, you will see output similar to Figure 3-8. All other multimedia content including videos can be rendered to your application in a similar manner. Let us now see how to get data from a remote server in a Next.js application.
Once it is installed, we can use its get() method in our page to fetch the data from a remote endpoint. However, things will change a little bit in a Next.js application. Previously, we performed the AJAX call in the component’s componentDidMount() method. But in this case, we will use a special method, getInitialProps(), provided by Next.js which helps us set the props for a component. We will initiate our Axios request in the getInitialProps() method . Consider the following page that uses GitHub’s public API to get a list of GitHub users and display them in our application:

Error in Axios Request

Successful Axios Request
If your output is a bit different than the one in Figure 3-10, do not worry. There is one thing that is still missing from your code. I have added some styles to the “style.css” file that we created earlier and imported it in our page. Do the same, and you are good to go with the styling. You can refer to the following stylesheet code:
That’s it. You can now fetch data from any remote endpoint and use it in your application.
Let’s try to add some user interaction to our application. We will get the GitHub user id as text input from the browser and will display user details for that particular GitHub user. To do so, we will need to get the initial data from props and set it in our state object using constructor, just like we did in the previous chapter for a traditional React application. The only difference here is that the props will come from getInitialProps() method.
We need to transfer the props to the state object because props object is not editable and, hence, we cannot directly use it for data operations.
When an id is entered from the browser, we will make an API call to fetch user details and modify the data in the state object. As soon as the state object changes, React will re-render the UI. Consider the following code:
getInitialProps() method gets the initial list of Github users and returns the data that is set as props for the page. These props can be accessed using “this.props” and are not editable.
constructor() method initializes the state object with the values passed as props. This state object will be updated every time we fetch GitHub user details for a specific user requested.
GetUser() method handles the click event of the button and makes an API call every time the user requests details for a specific GitHub user. The user id for the GitHub is fetched from the input textbox and is sent as a parameter to the API call. The state object is updated with the data returned by the API call. As soon as the state object is updated, React re-renders the view.
render() method checks the state object and renders the UI with user details if the request is successful or an error message if there is an error in the request.

Interactive Next.js Application

GitHub User Not Found
That is it. We have just created an interactive application that renders the content on the server-side using Next.js and React.js. Let us now learn how to manage the state of our application using Redux.

Redux Architecture
The view triggers an Action which in turn updates the Store with the help of Reducers. The Store then implicitly sends the updated data back to the View.
Actions pass the information to the Reducer, and then based on the information received, the Reducer decides what data to update in the Store.
A Store can be visualized as an application-level State object. Change in this object will trigger View updates.
Actions are the special methods that update the application State whenever a change in the View triggers these methods.
Unlike the traditional MVC pattern, the data flow here is unidirectional. This means that the Store cannot trigger any Actions. Only the View can trigger Actions. This significantly reduces the possibility of infinite loops.
Single source of truth – The state of the entire application resides in a single Store object.
State is read-only – The only way to change a State is by triggering an Action. Views do not have the privilege to directly update the State. They trigger an Action which tells the Reducer to update the State. This makes sure that all the changes to the State happen one by one, centrally, so that they are traceable for debugging purposes.
Changes are made with pure functions – To specify how the State is modified by Actions, pure Reducers are written. These are functions that take in current State and Action as input and return the next State as output. Remember the concept of purity that we studied in the previous chapter as a Basic Concept of React? That is exactly what Reducers adhere to. Since they got to be pure functions, make sure that they return a new State object instead of modifying the existing one.
A pure function never modifies the values of input parameters. It rather returns a new object every time it is invoked. Also, no matter how many times you invoke a pure function, it will always return the same output for the same set of input parameters. Lastly, a pure function depends only on its input parameters and never modifies anything outside of its scope.
Let us learn about Store, Reducers, and Actions in a bit more detail.
store.getState() – This method returns the current state.
store.dispatch(action) – Update the State by dispatching the action. The Reducer function associated with the Store will be called with the current State and the action. Its return value will be considered as the next state. The change listeners will also be immediately notified as soon as the State changes.
store.subscribe(listener ) – It is used to add a change listener to the State. You can pass a function as a parameter. This function will be called every time an action is dispatched. You can use the getState() method in the listener to get the updated State value.
unsubscribe() – This method is used when you no longer want to call your listener method when the State changes. This method is returned when you subscribe to a listener so you might want to save it in a variable during subscribing in order to be able to unsubscribe. Consider the following code snippet:
Redux does not have a strict rule set for defining your Actions. This means that, other than the “type” property, how you structure your Action is completely up to yourself. You can define the “value” property directly in the Action object instead of defining it inside the “payload” property. In fact, you can define your own properties and values. But it is one of the recommended approaches to define all your properties within the “payload” property.
Reducers are functions that specify how the State changes depending on the type and payload of the information dispatched by the Actions. These functions take in current State and Actions as input parameters, generate a new State after processing the information, and return this new State as output. Now, even though the State of our entire application is a single Store object, we might want to write multiple Reducers to modify this object. Redux gives you the flexibility to do that. Instead of writing a single Reducer function that deals with all the scenarios, you can write one small Reducer for each scenario. This will help us minimize code complexity.
Since all the Actions are executed sequentially, we will never face a scenario where multiple reducers are trying to modify the State at the same time.
Once this is done, we will create two separate folders – “Actions” and “Reducers”. Let us modify our “index.js” file in the “pages” folder. We will have an input textbox, a button, and a label. On click of the button, the State should be updated with the value in the input textbox and the label should update itself with the State value. Some initial value will be set for the State. Consider the following code:

Redux Demo
We have installed five new dependencies in total. Other dependencies that we already have are react, react-dom, next, axios, and @zeit/next-css. After installing the new dependencies, my “package.json” looks as follows:
If you are creating a new application from scratch, make sure you update your “package.json” as mentioned in the preceding snippet and run “npm install” command from terminal to update the dependencies. It is time to create our first Action. I have created an “Actions” folder in the root directory of our application that will contain our action. Consider the following code:
Here, we are defining an InitialState, which is a plain JavaScript object, and an Action that will update the State value with input text on button click. We will use the InitialState object directly in our Reducer function as well as while creating the Store for the first time. We will see that later. However, to update the State, we will have to dispatch an Action to the Reducer. To do so, we have created a method, changeState(), that will be called on button click. This method dispatches our Action.
For the Action that we are dispatching, we have defined a mandatory “type” property that determines the type of Action being performed and a “text” property which sends the new data to the reducer. It is time to create our Reducer function that will actually update the Store based on the data received from the Action. I have created a “Reducers” folder in the root directory of our application that will contain our reducer. Consider the following code:
As discussed earlier, Reducers take in two input parameters – current State and Action. While defining our Reducer, we assign “InitialState” as the default value for our first input parameter, state. If the reducer is triggered on an empty State, the initial state value defined in our “InitialState” object will be set to the State.
“InitialState” is being imported from our Actions file and is the same object that we created earlier.
If the type of the Action is “ChangeLabel”, the reducer will know that the State value needs to be updated with the data dispatched by the Action. In such a case, the Reducer function creates a new object, assigns the current State value to that object, and replaces the value of “text” property with the new value dispatched by the Action. This new object will be returned by the Reducer and will be considered as the new State of the application. React will automatically update the View as soon as it detects a change in the State. Hence, as soon as the Reducer is executed, the View will reflect the changes in State. We do not have any other Actions defined so we will just return the State object, as it is received, in case the type of the Action is not “ChangeLabel”. It is now time to write the code that will create our Store for the first time. I have created a “Store” folder in the root directory of our application that will contain our Store initialization code. Consider the following code:
Here, we have again used the “InitialState” object that we created in our Actions file, this time, to initialize the Store with the initial application State when it is being created for the first time. createStore() is a method provided by the “redux” library in order to create and initialize a Redux Store for the first time.
There should only be a single store in your app.
reducer (Function) – This is the Reducer function that we created for our Store. It returns the next application State, given the current state and an action.
initialState (any) – This is the initial State of our application. It is a plain JavaScript object that we created in our Actions file.
enhancer (Function) – You can optionally specify some functions that use third-party code to enhance your application. In our case, we have used the “thunkMiddleware” provided by the “redux-thunk” library. This middleware helps us write asynchronous logic that interacts with our Store. With a basic Redux Store without this Middleware, we will only be able to perform synchronous updates to the Store by dispatching an action. We will use applyMiddleware() provided by “redux” library to convert “thunkMiddleware” to an enhancer.
Note that the store is not yet created. We have just defined and exported the “initStore” function that can be invoked in order to create the Store.
You must have noticed that we have created everything that is required in order to perform State management using Redux. It is time to inject the Redux functionality in our application lifecycle. To do so, we will have to use “react-redux” library that we installed as one of the dependencies earlier. It is the official React binding for Redux. It helps React components read data from a Redux store and dispatch actions to the store to update the data. Since we need our State object to be available throughout the entire application, we will have to inject it in a component the rest of the components inherit from. This parent component can be referred to as a Higher-Order Component (HOC). In Next.js, we can create a special component “_App.js” which wraps all the pages and can be used to share something that is common throughout the application. We will use this “_App” component to inject Redux to the application lifecycle. Add the "_App.js" file to the “Pages” folder with the following code:
Here, we have created a component wrapped in a special withRedux()() wrapper provided by “next-redux-wrapper” library that we installed as one of the dependencies earlier. As the first input to this wrapper, we pass the method that creates the initial store, which in our case is “initStore” from “Store/store.js”. The second input to this wrapper is our Higher-Order Component (HOC).
The component extends from “App” component provided by “Next” library. This is the component that Next.js uses in order to initialize Pages. Since we are overriding the default initialization of our Pages, we will have to write the getInitialProps() method in our Component and make it call the Page’s getInitialProps() method. It takes in two arguments – “Component” and “ctx”. “Component” is the Page Component and “ctx” is the context. If the Page’s getInitialProps() method returns any data, we return that data from our HOC’s getInitialProps() method , else we return an empty object.
Then we write the render() method of our HOC. We already have Component and PageProps in the Props object. Component is the Page Component for the Page that is being rendered, and PageProps is the Props that we have in that Page. Since we are wrapping our HOC in a Redux wrapper, the Store object is also created and passed down to the render() method when getInitialProps() method is executed. We have already specified the method which will create the initial Store. The same will be used to create the Store and pass it down to the HOC props. We will use the destructuring syntax to fetch the values for Component, pageProps, and store from the props object.
We will use the <Provider> component provided by “react-redux” library to wrap our Page Component. We will pass the Store object to this component which will be available to all our container components. Within this component, we will put the Page Component and pass the page props to it. Page Component will dynamically keep changing depending on the Page that is being rendered.
This is how you inject Redux to the Next.js lifecycle using a Higher-Order Component (HOC). Let us now consume our store in our index page and dispatch an Action on button click. You will have to make the following modification to the “index.js” file:
The code written in "_App.js" gets executed when the page is first requested from the browser.
redux-wrapper creates the Store object with initial values and injects it into the Page. initStore() method is used to create the Store for the first time. We have defined this method in “Store/store.js” and provided a reference to it in the HOC.
The HOC in "_App.js" renders the Page Component. The control is now transferred to the code written in “Pages/index.js” file.
“connect()()” wrapper injects the State data into the page via props. A method to update the State value is also passed as props. The page then renders like a normal Next.js Page. You will see the initial State value displayed on the label.
As soon as you type some text and click the button, the changeState() method which is defined in “Actions/action.js” will be invoked.
This method will dispatch an Action of type “ChangeLabel” with the text that you entered in the input textbox as data.
The control will now be transferred to the Reducer method written at “Reducers/reducer.js”. After checking the type of the Action, the Reducer will update the “text” property in State with the data dispatched by the Action.
As soon as the State object is changed, React will re-render the Views and update all the fields whose data has been modified. Thus, the label on the UI that is bound to the “text” property of the State will be re-rendered and you will see the updated value on the UI.
Note that we are not using React’s built-in State object anywhere directly in the Pages. All the State management here is done by Redux. That is it about working with Redux. Let us now learn about GraphQL and how it is used in a Next.js application.

GraphQL Query Variables
Figure 3-15 perfectly depicts the concept of GraphQL. An API might return multiple parameters, but we might not need all of those parameters for our application. In such cases, we can send the names of the parameters that we need as query variables and the API will return just that many parameters.
req – An instance of the incoming request. You can use this object to identify the request type, input parameters, request headers, and URL from which the request is generated, among other things.
res – An instance of the outgoing response. You can use this parameter to set the status code, headers, and data of the response.
Let us start with a basic Next.js application with just the index page. We will create the “Pages/api” folder and add our first API, “TestAPI.js ” file with the following code:
What we are doing here is that we define a static data object and send it in response. We pass this data in the response's end() method. This method signals to the server that the response headers and the response body have been set and the server should consider this response as complete. We can consume this API by visiting the URL “http://localhost:*/api/testapi” in the browser. Alternatively, we can consume this API in our index page. Let us do it using the following code:

Next.js API Response
We will now have to modify our API a little bit. We will define a schema for our data. This schema will specify the type of data that we will be returning from the API. We will then pass the schema, GraphQL query, and the data object to GraphQL which will filter the data for us as per the query received. Consider the following code for the API:

GraphQL API Response
That is it about GraphQL. With the end of this topic, we come to the end of the chapter. Let us summarize what we have learned.
Next.js is a framework that helps us render applications on the server-side.
It solves problems such as higher loading time, poor indexing capabilities, and security vulnerabilities that are associated with client-side rendering.
It provides features such as hot reloading, page-based routing, automatic code splitting, page prefetching, hot module replacement, and server-side rendering.
Next.js provides <Link> component that helps add links to our application. When we navigate to such links, no additional server requests will be made for the resource. This is due to the client-side routing capabilities of Next.js.
Since it uses the History API, client-side routing in Next.js does not break the browser back button.
We should add media files in the “static” folder in the root directory of our application. The best approach to add multimedia content to our application is to add URLs to such content in CSS files.
Next.js provides JSS (CSS in JS) which allows us to define styles directly inside JSX code. We will have to use @zeit/next-css library (or any other CSS loader) in our application to write styling code in separate CSS files.
We can use getInitialProps() method in our page to pass props to the component. We can make Axios API calls within this method to fetch data for our page from a remote server. Data passed as props can be used to initialize the State object in the constructor.
Redux can be used in Next.js application in order to manage the State at an application level. It imitates the MVC architecture using Actions, Reducers, and Store.
We use Higher-Order Component (HOC) to inject Redux into the Next.js lifecycle.
GraphQL can be used in Next.js APIs to provide the client with the ability to query data for fields that they require in the response.
In the previous chapter, we learned how to create a server-side application using the Next.js framework. However, we might want to create an application that is partially rendered on the client-side and partially on the server-side so that we can leverage the benefits of both client-side rendering and server-side rendering. In this chapter, we will create a client-side rendered React application and learn how to integrate server-side rendering into the application using Next.js framework. Along the way, we will also learn the importance of server-side rendering, styling our application, adding Bootstrap to our application, and some other topics. Mostly we will be using the things that we have already learned previously in order to create a functional application.
In the previous chapter, we discussed the problems associated with client-side rendering . The major problem is faced during the development of a single-page application (SPA). Although SPAs provide amazing user experience, all of it is browser-based. Instead of navigating from one page to another, the user stays on the same page and the content on the page is dynamically changed based on the user interaction. These changes are made by the browser using the JavaScript code that is written on the client-side.

Client-Side Rendering of a Single-Page Application
Do not confuse the server used for client-side rendering with the server used for server-side rendering. The web server used here can be referred to as a “Thin Server”. This is because, in the case of client-side rendering, all the logic is written in the form of JavaScript code which will be processed by the browser. The server acts as a pure data API and just delivers the JavaScript code to the browser. On the other hand, in the case of server-side rendering, the server processes all the logic and delivers a ready-to-render HTML page to the browser.
Adopting this approach might take a significant amount of time and result in poor user experience due to all the waiting-while-the-page-loads. This is where the server-side rendering steps in. We can prepare the initial page on the server-side and serve it to the user’s browser which can then easily download the page and render it. This way, the initial application loading can be performed with a single web request. We have already learned how to use Next.js for server-side rendering in the previous chapter. Further in this chapter, we will see how to use both client-side rendering and server-side rendering to create a fully functional application. Let us start by creating a simple React application.
On executing the application using “npm-start” command, you should see “Hello from React.” printed on your browser window. Our starter React application is up and running. Let us now do this with the help of a React component.
Our component file will reside in the “src/Components” folder in the root directory of our application. Let us add the “App.js” file in the “Components” folder with the following code:
We will also need to make some changes to our “index.js” file in order to render the component instead of directly rendering the JSX code. Update the “index.js” file as per the following code:
If you run the application and visit the browser, you should see “Hello from React.” printed on the window. So far, we have not displayed the time on the browser. Let us do that using React props.
We will simply pass the current time as props to the App component. The component will fetch the value from the props and render it to the browser. It is pretty simple. Let’s do that by modifying our code as per the following:
As you can see, we have passed the time string as props to the component, which is then rendered to the browser. However, the React will not update the DOM yet because we have passed a static time string and React does not know yet when the time changes. To implement this functionality, we will have to write some JavaScript code to update the time stored in the “props” as the actual time passes. But we cannot do that because “props” are read-only. Hence, we will have to use the “state” functionality provided by the React lifecycle.

Current Directory Structure
You will have to make the following changes in the code:
As you can see, we are no longer passing the time string as props to the component. We set the state property to the current time in the constructor of our class component. Then we render it to the browser using the render method. The only difference here is that instead of fetching the value from “props”, we now fetch it from the “state”. Using the “state” property is necessary because as we discussed earlier, “props” are read-only and we cannot modify them directly.
Next, we had to find a way to update the state property with change in time. To do so, we created an interval using JavaScript’s setInterval() method. We did this in the componentDidMount() method of the React lifecycle in order to make sure that the interval is set only once the component is mounted to the DOM.
If you have created a function component, you can use React hooks to hook to the React lifecycle method componentDidMount(). You can go back to Chapter 2 of this book in order to see React hooks in working.
If you have created a function component, you can use React hooks to hook to the React lifecycle method componentDidMount().
The interval calls the tick() method every one second which will eventually update the “state” object with the new time. As soon as the State is modified, React re-renders the view. Hence, the user sees a digital clock on the browser that ticks every second. We might want to clear the timer that we created when the component was mounted in the componentWillUnmount() method in order to avoid memory leaks in case the component is removed from the DOM.
That is it. Our application is completely functional. We have achieved this entirely by the approach of client-side rendering using React. Let us see how to add server-side rendering to this application using Next.js framework.
If you try to launch the application, you will run into an error stating that the “Pages” directory is not found. We will have to create it and add our “app.js” file to that directory because that is where Next.js loads the pages from. We can delete our “index.js” file (which contains the code for rendering our components) because Next.js will take care of the rendering for us. We can also delete the “src” and “public” folders because they are of no use to us. For simplicity, we can rename “app.js” file in the “Pages” directory to “index.js” because, as we learned in the previous chapter, Next.js follows a page-based routing and it looks for “index.js” page on application startup. Now if you launch the application, you will see an identical timer to the one created using client-side rendering. If you want to verify that the content is being rendered on the server-side, you can right-click the page and view the page source. You will notice the presence of HTML code for the timer instead of an empty <div> tag. This tells us that the timer is not being generated using client-side JavaScript but is being generated on the server-side. However, the page is not being reloaded every second. This means that the update in the state is being handled by React on the client-side. This is exactly as we wanted it to be, initial application rendering on the server-side and other DOM changes on the client-side. Now that our application is up and running, let us add some styling to it.
Once installed, we will have to add a config file “next.config.js” to the root of our application with the following code:
This config file acts as an entry point to the webpack configuration of our application that is, by default, hidden by the Next.js framework. Once configured, we can create a stylesheet for our application and import it to our page along with other imports. Consider the following stylesheet that I have created in the “Resources” folder:

Current Directory Structure

Digital Clock Using Next.js and React
We can also add Bootstrap to our application in order to add responsiveness to our application. Let us see how to do that.
On the successful execution of this command, you shall see the bootstrap module added to our “node_modules” folder. Since we have already installed the Zeit CSS loader and configured it in our application, we will directly be able to import the bootstrap CSS file in our page and use the classes provided by the Bootstrap framework. Refer to the following code in order to understand how it is done:
If you need to apply CSS globally in your application, you should create a Higher-Order Component (HOC) that wraps all your components and then import the CSS file in the HOC. This will spare you the trouble of having to import CSS file in every component that you create. We learned how to create a HOC in the previous chapter while learning about Reducers in Redux. If you do not remember, you can go back and have a look.

Digital Clock with Bootstrap
With this, we come to the end of this chapter. You can add some more pages to the application, establish links between them, and play around with the bootstrap classes. The more you explore, the more you will learn. Let us summarize what we have learned in this chapter.
Server-side rendering is very useful while loading a single-page application for the first time. It results in better user experience due to lesser wait time. Subsequent DOM changes can be made on the client-side.
A simple client-side React application can be created using a function component. We can pass props to the component, and it can then render the prop data to the browser window.
Since props are read-only, we cannot directly modify them. A better approach is to use React’s state object if we are dealing with props that need to be modified during the page lifecycle.
componentDidMount() is a React lifecycle method that can be used by class components to trigger events when the component is mounted to the DOM. In our case, we have used this method to modify the state object with updated time every second.
To move the rendering to the server-side, we use the Next.js framework.
Since Next.js takes care of the rendering of our component, we need not worry about it. We can simply move our client-side code to a Next.js page and it will be rendered on the server-side.
We can add custom CSS and Bootstrap in our application using an external loader.
In previous chapters, we learned how to create web applications using libraries such as React and Next.js. We now know how to develop an application using these libraries. What next?
Once an application is developed, it is important for us to know that it works as expected. To do so, we can write automated unit tests to verify that every component of our application is appropriately doing its job. That is exactly what we are going to learn in this chapter. We will use the Jest framework to perform unit testing on our React application.
As a developer, writing unit tests might seem to be delivering very minimal value while adding a lot of work to your already cramped schedule. However, it will help you reduce your workload in the long run when your application scales up in size, providing a very effective way to detect errors and loopholes in your code.
There are many other JavaScript testing frameworks in the market such as Mocha and Jasmine. However, we will go with the Jest framework due to its increasing popularity and utility. We will learn how to install and set up Jest in our application, then we will create a basic unit test to familiarize ourselves with the concept of Jest, and eventually, we will learn about Matchers and Enzymes that will help us test our React component. Let us start by setting up the Jest framework.
That’s it. Jest is now successfully installed. Let us write our first test using Jest.
Let us first create a simple JavaScript file that contains some basic functions. I have added a file called “functions.js” to the root directory of our application with the following code:
This file contains a simple “add” function that takes in two numbers as input and returns their sum as output. Note that we have used simple JavaScript syntax to export the list of functions as a module. Avoid using ES6 syntax because Jest expects the files to be plain JavaScript while they are imported. Now that we have created a JavaScript function, let us test it using Jest. We will add our test files in the “tests” directory. It is a good practice to name the test file as the same JavaScript file you are testing, with ".test.js" suffix. Consider the following test file that contains the code to test the “add” function:
In the code for the test, we simply call the “test()” function that takes in two input parameters – the first one being a description of the test and the second one being the actual test function.
In the test function, we use the “expect()” function that takes in the function that we are testing and evaluates it, in our case, the “add()” function.
We import the list of functions from "functions.js" using JavaScript’s “require()” method because in order to call the “add()” function, we will have to import it from the file in which it is defined.
We use a Matcher, in this case, the “toBe()” function, on the “expect()” function in order to compare the evaluated value with the expected value. We pass the expected value as an input parameter to the Matcher. We will learn more about Matchers in the next topic.

First Test Using Jest (Success)
It is possible to write multiple tests in a single file.
The “Test Suites” denotes the number of test files, whereas the “Tests” denotes the combined number of tests in those files. In the preceding example, if we change the expected value to something else, let us say “4”, the test execution will fail. Let us try that. Consider the following changes to “function.test.js” file:

First Test Using Jest (Failure)
Now that we have learned how to write tests for JavaScript functions using Jest, let us delve a little deeper and learn about different Matchers that we can use for testing our code.
Matchers are function used by Jest in order to compare the evaluated value with the expected value. In the previous example, we used the “toBe()” Matcher provided by Jest. Note that we use the “expect()” function in order to evaluate the actual value. This function returns an expectation object on which we call our Matcher function to compare it with the expected value. Let us have a look at all the Matchers that are provided by Jest.
toBe(expectedValue) – This is the exact equality matcher. It checks if the value returned by the “expect()” function exactly matches the “expectedValue”.
toEqual(expectedValue) – This is similar to the “toBe()” matcher, except the fact that it is used to compare the value of an object. It recursively checks every property of an object.
Let us look at an example in order to understand the common Matchers in working. Consider the following changes to “functions.test.js” file:
To demonstrate the utility of the “toBe()” Matcher, we use the same “add()” function that we tested during the previous example. The function returns “5” and the “toBe()” Matcher asserts it to be true since it is the value that we are expecting.

Common Matchers in Jest
If you want to try more scenarios, you can change the expected value in the preceding example and notice that the test fails.
You can use the “Jest” extension by “Orts” if you are using Visual Studio Code editor. It provides IntelliSense for Jest and is also very helpful in debugging tests that you write.
toBeNull() – Matches null values
toBeUndefined() – Matches values that are undefined
toBeDefined() – Matches values that are not undefined
toBeTruthy() – Matches the values that evaluate to true
toBeFalsy() – Matches the values that evaluate to false
Let us look at an example in order to understand truth Matchers in working. The following new tests need to be added to the “functions.test.js” file:
We have written two new tests in the preceding example, one to test the truthiness of “null” and the other to check the truthiness of the number zero. The null value should evaluate to null, defined, and not true. On the other hand, the number zero should evaluate to not null, defined, and false. If you use any number other than zero, it should evaluate to true.

Truth Matchers in Jest
toBeGreaterThan(value) – Asserts if the actual value is greater than the provided value.
toBeGreaterThanOrEqual(value) – Asserts if the actual value is greater than or equal to the provided value.
toBeLessThan(value) – Asserts if the actual value is less than the provided value.
toBeLessThanOrEqual(value) – Asserts if the actual value is less than or equal to the provided value.
toBeCloseTo(value) – Asserts if the actual value is close to the provided value. This is specially used while dealing with floating-point values. In such cases, the precision of the expected value and the actual value might differ, so the “toBe()” Matcher (exact equality) would not work.
Let us look at an example in order to understand comparison Matchers in working. The following are the new tests added to the “functions.test.js” file:

Comparison Matchers in Jest
toMatch(regex) – Asserts if the computed string matches the provided regular expression
Consider the following example:

String Matcher in Jest
toContain(item) – Asserts if the computed iterable contains the provided item
Consider the following example:

Iterable Matchers in Jest
toThrow(expectedException) – Asserts if the evaluated piece of code throws the given exception
To test this Matcher, we will go back to our “function.js” file and define a function that throws an error. We will then add a test in the “functions.test.js” file which will invoke the function and assert the exception. Consider the following example:

Exception Matcher in Jest
That is it. We have covered most of the commonly used Jest Matchers. Let us now learn how to test our React components using what we have learned so far.
Once the starter application is created, you can delete all the files that are not necessary. I have deleted all the files from the “src” folder except “index.js” and all the files from the “public” folder except “index.html” and “favicon.ico”. I have also cleaned up the “index.html” file. The following is the code for your reference:
Now that we have cleaned up our starter application, let us add our List component in the “src” folder. Consider the following code:
The preceding code is for a simple function component that fetches the items from the props and displays them as a list. Now that our component is created, we might want to instruct the “index.js” file to render it on the browser. Consider the following code for “index.js” file:

List Component Using React
We have installed a specific version of the Jest framework. This is because applications initialized using “create-react-app” command have a dependency on this version of Jest. If your version of the Jest framework does not match the required version, you will get an error during the launch of the application mentioning the version that you need. You can resolve the error by installing the version that the application requires.
After installing the Jest framework, you will also have to add the test script in “package.json” file as per the following code:
While testing simple JavaScript functions, we used to simply invoke the functions in our tests and compare the evaluated value to the expected value using Jest Matchers. But you might wonder what to do in case of a react component because we cannot just invoke a component.
Note that we have also installed an adapter along with the Enzyme framework that corresponds to the version of React that we are using. We will have to configure this adapter in Enzyme before we can use the framework. To do so, we will create an “enzyme.js” file in the root directory of our application and add the following configuration code to it:
What we are doing in the preceding code is that we import “Enzyme” and “configure” from the Enzyme framework and the “Adapter” from the Enzyme Adapter. We then use the “configure()” method provided by the Enzyme framework to set the Adapter for the instance of the Enzyme that we will be using. After configuring Enzyme, we simply export it. We also import shallow and mount from the Enzyme framework and export them as they are. These are the methods that we will be using to render our React components for testing. To conclude, all the entities of the Enzyme that we need for our testing will now be imported from the file “enzyme.js” instead of directly being imported from the framework. If you try to import the modules directly from the Enzyme framework installation folder, you might run into an error because they are not configured with the Adapter.
Now that everything is configured, let us write our test for the List component. Let us write the test in “List.test.js” file in the “src” folder. Refer to the following code:
Note that we have used two different methods to render our component – shallow and mount. Let us understand the difference between the two. As the name suggests, the “shallow()” method limits the scope of rendering to the specified component and does not render its children components. On the other hand, the “mount()” method renders the entire tree of components. In this case, we do not have any children components so the rendering would be the same in both cases.

Testing List Component Using Jest
Also, we need to create a “.babelrc” file in the root directory of our application and provide the following configurations:
If you run the test after installing and configuring the babel transform plugin, the test should successfully run and the output should be similar to Figure 5-10.
That is it. We have successfully tested our React component using Jest and Enzyme. With the end of this topic, we come to the end of this chapter.
Let us summarize what we have learned.
Jest is a test framework that can be used to test applications built using JavaScript.
It is good practice to suffix your test files with “.test.js”.
While testing, the “expect()” method is used to evaluate a JavaScript function or specify a value that needs to be tested.
Jest provides various Matchers that can be used on the “expect()” method to assert if the computed value matches the expected value.
Since React components cannot be directly invoked like functions, we will have to use the Enzyme framework that provides us the functionality to render components on a representational DOM that is created for testing.
The Enzyme framework provides two main methods for rendering a component – shallow() and mount().
We can use selectors with “find()” method to look for specific content within the rendered component.
In the previous chapters, we have learned how to build and test our React application. Once we have done that, we might want to know how our application performs in a production environment. That is when deployment comes into the picture.
In this chapter, we will learn how to deploy our application using Docker containers. Let us get started by learning about the deployment process.
Firstly, we need to configure the application by setting some environment variables in our code. This will help the application identify the environment in which it is running and behave accordingly.
We will then need to install Docker on our system to containerize our application.
Once the configuration is done and Docker is installed, we need to build a Docker image of our application. We will learn more about Docker in the subsequent topics of the chapter.
Once we know that the Docker image works fine locally, we can deploy it to a public-facing server.
Now that we are aware of the deployment process, let us start by setting up the configuration for our application. If you do not follow or are confused about the process that we just discussed, do not worry. You will get a better understanding once we discuss each step in detail.
Environment variables are key-value pairs that can be read by our React application in order to configure the values on the runtime depending on the environment that the application is running in. It facilitates the dynamic behavior of the application. To understand this in working, we will use the GraphQL application that we developed in Chapter 3. The following is the code for your reference:
In this application, we are creating a Next.js API and consuming it on the index page of our application. While consuming the API, we are using “localhost” in the API URL. This will not work in the production environment. So, let us add environment variables and use them in code. Add a “.env” file with the following code that will contain our environment variables:
We have already used the “next.config.js” file to add our custom CSS loader to the webpack. We will use the same file to add the configuration for the “.env” file to the webpack. Add the following code to the “next.config.js” file:
Once the configuration is done, any variable that we add to the “.env” file will be available throughout the application. Let us now modify our “index.js” file to use the API URL dynamically based on the application environment. If you have worked with a Node.js application before, you would be aware that Node provides a static class “Process” that provides us access to the user environment in a property called “env”. We will use this class to determine the application environment. Consider the following changes to the “index.js” file:

Application in Development Environment
That is it about setting the environment variables. Let us now learn about Docker.

Containerized Application vs. Virtual Machine Implementation
Docker Client – This is how users communicate with Docker. It provides commands that invoke the Docker API, which can be used to communicate with Docker daemon.
Docker daemon – This is part of the Docker host that listens for API requests and manages objects such as containers and images. It can also communicate with other daemons.
Images – A Docker Image is a read-only template with a layered set of instructions that are used to create a Docker Container. We can create our own image or use the one created by others and published to the Registry.
Containers – A Docker Container is an instance of a Docker Image. We can perform operations such as start, stop, move, or delete on the container using the Docker API or CLI.
Registry – A Docker registry stores Docker images. Docker Hub is a public registry that anyone can use. Docker is configured to look for images on Docker Hub by default. You can run your own private registry as well. When you run the “docker run” or “docker pull” command, the required images are pulled from your configured registry. When you run the “docker push” command, your image is pushed to your configured registry.

Docker Architecture
There are many more things that one can learn about the Docker platform. However, we will not go into the details since this chapter is about deployment and not about Docker. Let us learn how to containerize our application.
Now, let us get back to our project. We will have to add a “Dockerfile” to the root directory of our application with the following set of instructions that will act as the Image template and will be used to create the container for our application:
Let us understand what is happening here. Firstly, we are instructing Docker to start with “alpine”, which is a generic implementation of Linux. Then we create a new source directory and switch to it. We copy the “package.json” file to the new source directory and install all the dependencies to it. Finally, we copy the files from our node application to the new source directory. Then we build the application, expose the port on which the node server runs, and start the server.
However, we will need to modify our “package.json” file. Make sure that you have the following scripts in your file:

Docker Containers
That is it. We have successfully created a container for our application. Let us now learn how to host a Docker Container.
What we are doing here is that we add a tag name to the existing container and then remove the old tag name. “e65” is the first three characters of our Image ID, which is all that we need in this case.
“msthakkar121” is my Docker ID so I have used that as a prefix. However, you need to use your respective Docker IDs.

Repositories on Docker Hub

Application in Production Environment
As you can see, the environment variable that we printed on the header on our index page is now showing “production” instead of “development”. This asserts that our application is successfully running on a production server. Note that the API data is presently not being fetched because we have not yet hosted our application on a public-facing cloud. You can use the services provided by platforms like DigitalOcean (www.digitalocean.com/) in order to host your containerized application to a public-facing cloud. However, if you have created this application for learning purposes and do not want to spend bucks on hosting services, running the production version of your application locally using Docker Desktop should suffice.
With that, we come to the end of this chapter. Let us summarize what we have learned.
Deploying our application to a production server is essential to make sure it is working as expected after deployment.
We need to define some environment variables and use them in the code to change the application behavior on runtime depending on the environment it is running on.
To containerize our application, we have used Docker.
Containerized applications interact directly with the host machine’s kernel and hence do not need a hypervisor.
Due to containerization, multiple applications targeted for different operating systems can run simultaneously on the same host machine without any hypervisor.
We specify instructions to build a Docker container in a file called “Dockerfile” which resides in the root directory of our application.
Then we use the “docker build” command to build a Docker container based on the instructions in “Dockerfile”.
The container can be tested in a locally simulated production environment using the “docker run” command.
Services like “DigitalCloud” can be used to publish our application to a public-facing cloud.