Introduction To React
Introduction To React
React is the most popular front-end JavaScript library in the field of web
development. React is a JavaScript library created for building fast and
interactive user interfaces for web and mobile applications. It is an open-
source, component-based, front-end library responsible only for the
application’s view layer. React gained popularity due to some of its salient
features - can be used for the development of both web and mobile apps,
unidirectional data flow, reusable components, creation of dynamic
applications, and many more.
React is one of the most popular front-end JavaScript libraries in the field of
web development. It is mainly maintained by Facebook and a large community
of developers. A number of large, established companies (Netflix, Instagram,
Airbnb, to name a few) use it to build their user interfaces and UI components.
Features of React.JS
• JSX - It is an extension of ReactJS, which is not mandatory to be used but
very beneficial if used since it is very easy to use.
• Component: Components are similar to pure javascript functions, and they
serve to simplify the code by separating the functionality into reusable
independent code. Components can be used as functions and as classes.
Components also have a state, and props, which simplify lives. The status of
each prop is preserved within a class.
• Virtual DOM: React generates a virtual DOM, which is an in-memory data-
structure cache. Only the final DOM updates have been updated in the
browser's DOM.
• Javascript Expressions: Curly brackets, for example, can be used to insert JS
expressions into JSX files.
Advantages of ReactJS
• ReactJS employs virtual dom, which makes use of an in-memory data-
structure cache, and only the most recent modifications are updated in
the browser's dom. This speeds up the app.
• Using the react component feature, you may design components of your
choice. The components are reusable and useful for code maintenance.
• Since Reactjs is an open-source javascript library, it is simple to learn.
• ReactJS has quickly gained popularity and is supported by Facebook and
Instagram. Many well-known companies, including Apple and Netflix, use
it.
• Since Facebook maintains the library of ReactJS, it is well-managed and
up-to-date.
• ReactJS may be used to create sophisticated user interfaces for both
desktop and mobile apps.
node.js
https://nodejs.org
install Create-React-App
npm install -g create-react-app
create-react-app demo-project
npm start
Folder Structure
The React application automatically creates required folders, as shown below.
my-app/
README.md
node_modules/
package.json
public/
index.html
favicon.ico
src/
App.css
App.js
App.test.js
index.css
index.js
logo.svg
.gitignore
This file is used by source control tool to identify which files and folders should
be included or ignored during code commit
package.json
This file contains dependencies and scripts required for the project.
Most importantly, you can check the current version of the React that you are using.
It has all the scripts to start, build, and eject our React app.
node_modules
This folder will contain all react js dependencies.
All the packages installed by NPM or Yarn will reside inside the node_modules folder.
public folder
The public folder contains index.html. As react is used to build a single page
application, we have this single HTML file to render all our components. Basically, it's
an HTML template. It has a div element with id as root and all our components are
rendered in this div with index.html as a single page for the complete react app.
src folder
In this folder, we have all the global javascript and CSS files. All the different
components that we will be building, sit here.
index.js
This is the top renderer of your react app. In the index.js file, we
import React, ReactDOM, and the CSS file.
index.js is the file that will be called once we will run the project.
App.js
App.js is a component that will get loaded under index.js file. If we do any
change in app.js file HTML component and save it it will reflect in
localhost://3000
Introduction to JavaScript
JavaScript is a popular programming language that has a wide range of applications.
JavaScript was previously used mainly for making webpages interactive such as form validation,
animation, etc. Nowadays, JavaScript is also used in many other areas such as server-side
development, mobile app development and so on.
console.log('hello world');
// 5 is assigned to variable x
let x = 5;
console.log(x); // 5
x = 3;
console.log(x); // 3
const x = 5;
console.log(x)
JavaScript console.log()
All modern browsers have a web console for debugging. The console.log() method is used to write
messages to these consoles. For example,
console.log(sum); // 44
// storing values
• Assignment Operators
• Arithmetic Operators
• Comparison Operators
• Logical Operators
• Bitwise Operators
• String Operators
• Other Operators
let x = 5;
let y = 3;
// addition
// subtraction
// multiplication
// division
// remainder
// increment
// decrement
//exponentiation
ECMAScript is the standard that JavaScript programming language uses. ECMAScript provides the
specification on how JavaScript programming language should work.
ECMAScript 6
The next big update occurred in 2015 when ECMAScript 6 (ES6) or ECMAScript 2015 (ES2015) was
officially released. ES6 features modernized JavaScript.
And beyond
There have been four more updates since that time: ECMAScript 2016, 2017, 2018, and 2019. The
name ES.Next is given to the upcoming version, which is still in revision and proposal.
JavaScript let
JavaScript let is used to declare variables. Previously, variables were declared using the var keyword.
To learn more about the difference between let and var, visit JavaScript let vs var.
The variables declared using let are block-scoped. This means they are only accessible within a
particular block. For example,
console.log(name); // Peter
console.log(name); // Sara
JavaScript const
In the ES6 version, you can use arrow functions to create function expressions. For example,
// function expression
let x = function(x, y) {
return x * y;
}
// function expression using arrow function
JavaScript Classes
JavaScript class is used to create an object. Class is similar to a constructor function. For example,
class Person {
constructor(name) {
this.name = name;
Keyword class is used to create a class. The properties are assigned in a constructor function.
class Person {
constructor(name) {
this.name = name;
}
const person1 = new Person('John');
console.log(person1.name); // John
In the ES6 version, you can pass default values in the function parameters. For example,
function sum(x, y = 5) {
// take sum
console.log(x + y);
sum(5); // 10
sum(5, 15); // 20
It is mainly used to convert ES6+ code into a backwards compatible version of JavaScript that can be
run by older browsers.
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
</header>
</div>
);
}
It is mainly used to convert ES6+ code into a backwards compatible version of JavaScript that
can be run by older browsers.
Let
const
Objects
Destructuring
Template literals
Ternary Operators
Components are independent and reusable bits of code. They serve the same purpose as
JavaScript functions, but work in isolation and return HTML.
A component is an independent, reusable bit of code which divides the UI into smaller
pieces. For example, if we were building the UI of React website using Reactjs we can break
its UI into smaller parts
Instead of building the whole UI under one single file like HTML, we can divide all the
sections (marked with red) into smaller independent pieces. In other words, these are
components. Each component will go into its own JavaScript file.
Same component can be use with different properties to display different information.
The first, most important and recommended component type in React is a functional
component.
function HelloWorld() {
import './App.css';
function App() {
return (
<div className="App">
<HelloWorld/>
</div>
);
Code:
};
As HelloWorld is exported here, we can import this component into another file (which will
be App.js in our case) and use it as shown below.
return (
<div className="App">
<header className="App-header">
<HelloWorld />
</header>
</div>
);
};
In short, a functional component is a JavaScript function or ES6 function which takes props as
arguments and returns a JSX.
Class Components
Just as we have functions, we also have classes in JavaScript. Class components are ES6
classes that return JSX. The same HelloWorld function can be converted to a class
component.
Class components start with class keyword that extends the Component constructor from
React and has a render method which returns a JSX.
render () {
return (
<div>
<h1>Welcome</h1>
</div>
App.js
import './App.css';
function App() {
return (
<Welcome/>
);
render() {
}
What are Props?
A Prop is a way that components communicate. React uses props to transfer data from one
component to another component.
But remember that props only transport data in a one-way flow (only from parent to child
components). It is not possible for props to pass data from a child to parent, or to
components at the same level.
Now let’s go back to our App component and pass props from an App to its child
(HelloWorld.js in our case).
First, we need to define a prop on the HelloWorld Component and assign a value to it.
What is a Constructor?
In JavaScript the constructor is a method used to initialize an object's state in a class. It is
automatically called during the creation of an object in a class.
The concept of a constructor is the same in React. The constructor in a React component is called
before the component is mounted. We use that to define a state object inside a class component.
We can change our existing class component to use state and props by changing the code
JSX
JavaScript XML
const Hello=()=>{
return (
<div>
<h1>Hello</h1>
</div>
// return React.createElement('div',null,'Welcome')
return React.createElement('div',null,'Welcome')
Props
Props are arguments passed into react component
React pops are like function arguments in JavaScript and attribtes in HTML
render()
{ //this.props.name ="abc"
return(
<div>
<h1>Hello {this.props.name}</h1>
</div>
)
import './App.css';
function App() {
return (
<div className="App">
</div>
);
return (
<div>
<p>{props.children} </p>
</div>
function Profile(props) {
return (
<div>
<p>{props.children} </p>
</div>
App.js
import './App.css';
import Profile from './Profile';
function App() {
return (
<div className="App">
<Profile name="Raj">
</Profile>
<Profile name="Simran">
</Profile>
<Profile name="Arun">
</Profile>
<Profile name="Harshad">
</Profile>
</div>
);
function App() {
return (
<div className="App">
<header className="App-header">
<p>
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
conditional operators
import React, { Component } from
'react';
//Logical OR || Operator
Destructing
import React from 'react';
return(
<div>
<legend>Personal Details</legend><br/>
Name : {props.personalinfo.name}<br/>
address : {props.personalinfo.address}<br/>
zipcode : {props.personalinfo.zipcode}<br/>
city : {props.personalinfo.city}<br/>
contactnumber : {props.personalinfo.contactnumber}<br/>
<legend>Proffessional Detail</legend><br/>
occupation : {props.proffessionalinfo.occupation}<br/>
designation : {props.proffessionalinfo.designation}<br/>
salary : {props.proffessionalinfo.salary}<br/>
</div>
App.js
const personalinfo =
{
name: "xyz",
address: "150 seattle",
zipcode: "111111",
city: "wc",
contactnumber: "999999999"
}
const proffessionalinfo =
{
occupation : "business",
designation : "CEO",
salary : "50k"
}
return (
<div className="App">
<img src={logo} className="App-
logo" alt="logo"/>
<Employee
personalinfo={personalinfo}
proffessionalinfo={proffessionalinfo} >
</Employee>
</div>
);
}
Handling events in react is very crucial because changes made on event helps the user to
interact with our application.
Handling events in react is very much similar to how we handle events in DOM elements. If
you are familiar with handling events in javascript, then handling events in react would be a
cakewalk for you.
React Events
An event is an action that is fired as a result of user actions or the action taken by the
system. For example, clicking a mouse button, loading a web page, pressing a key, window
resizing, and other interactions are called events.
React has its own system for handling events which is quite similar to how we handle events
in DOM elements.
React allows us to pass arguments in the event handler. So let’s take a look at how you would
pass arguments while handling events in react.
Components Lifecycle
The components in React go through certain stages and follow a cycle in the same way as
everything else in the world does. We all are born, followed by the process of growing up,
and then we die. Similarly, the React components go through the following stages: they are
created/mounted, followed by growing or updating, and then unmounted. This is known as
the React components lifecycle.
React provides certain lifecycle methods at different phases of a component’s life. React
implicitly calls the relevant methods based on which phase the component is in. These
methods help us make it easier to manipulate the component.
The react components lifecycle can be categorized into four parts, they are:
1. Initialization
2. Mounting
3. Updating
4. Unmounting
Initialization Phase
The initialization method is the phase in which the component is created. Inside the
constructor method, the state and props are set up, resulting in the launch of the
component’s journey.
Mounting Phase
This stage comes right after the initialization stage is completed. In this phase, the React
component is mounted on DOM (Document Object Model). In other words, the React
component is created and inserted into the DOM. The component renders for the first time
in this phase.
1. componentWillMount()
2. componentDidMount()
componentWillMount()
This method is invoked just before a component is mounted on the DOM, or when the
render method is called. After the invocation of this method, the component will get
mounted on the DOM.
Here, we must note that we cannot update the state with API(Application Programming
Interface) response. Avoid making API calls or changing data using this.setstate inside this
method since this method is called before the render method. As it is not mounted on the
DOM, updating the data with API response cannot be done.
componentDidMount()
This method is invoked right after the component gets mounted on the DOM. Calling the
render method before the execution of the componentDidMount method lets us access the
DOM. Inside this method, we can make API calls and update the state with the API response.
Just like the componentWillMount method, this method will be called only once in a
lifecycle.
Updating Phase
This is the third stage of a component’s lifecycle. This phase comes after the mounting phase
of the component is completed. In the updating phase, the state of the component is
changed.
The main goal of this phase is to make sure that whenever a user event occurs, the state and
props of the component will get updated. User events may be simple events like clicking,
typing, etc. The data of the component is updated as a response to such user events. As a
result, the component gets re-rendered. Three methods are available in this phase, they are:
1. shouldComponentUpdate()
2. componentWillUpdate()
3. compnentDidUpdate()
shouldComponentUpdate()
We use this method to know if a component’s output is not affected by the current change in
state or props. In other words, this method is used to decide whether the component should
be updated or not. It is invoked before rendering when new props or states are being
received. By default, it returns a true value. This method is mainly used for performance
optimization. It receives arguments nextProps and nextState to check whether to re-render
by comparing with the current prop value.
componentWillUpdate()
componentDidUpdate()
Unmounting phase is the final stage in the lifecycle of a component in ReactJS. In this phase,
the component gets unmounted from the DOM. The method available in this phase is
componentWillUnmount().
componentWillUnmount()
This method provides us with a function to unmount the components. It is invoked before
unmounting of the component occurs. After its execution, the component will be removed
from the DOM.
import React from "react";
constructor(){
super()
console.warn("constructor")
componentDidMount() {
console.warn("componentDidMount");
render() {
console.warn("render")
return(
<div>
</div>
React comes with an internal mechanism for validating props data type to make sure that values
passed through props is valid. React components uses a special property called “propTypes” to
setup data type validation.
Although, we are allowed to define components without PropTypes. But, with PropTypes we
can avoid unexpected bugs or glitches to the users. The PropTypes is provided with props
and their respective PropTypes for type-checking. When a prop is passed in with an invalid
type or fails the prop type, a warning is passed into the JavaScript console.
The React.PropTypes object contains a list of validators for basic data types –
React Lists
function Greet(props) {
Greet.propTypes = {
name: PropTypes.string.isRequired
Greet.defaultProps = {
name: "Ramesh"
import './App.css';
function App() {
return (
<Greet/>
);
setCount(count+1);
setCount(count-1);
return (
<div>
<button onClick={increment}>increment</button>
<button onClick={decrement}>descrement</button>
</div>
useEffect
//useEffect
import React, {useState, useEffect } from "react";
useEffect( () => {
console.log("Effect executed") ;
},[count]);
return (
<div>
</div>
Map in react.js
The map method manipulates the items in an array and displays individual items. It
generates a new array by invoking a function on each member of the calling array. It is one of
the standard methods in the JavaScript library.
The map function, in simple terms, produces a new array from an existing one. The map
method basically runs a function for each item in the array. The objects returned by this
method are stored in the new array.
return (
<div>
<ul>
{renderListOfUserNames(userNames)}
</ul>
</div>
);
Hooks
useState
constructor(props) {
super(props)
this.state= {
count :0
}
}
incrementCount=()=> {
this.setState( {
count: this.state.count +1
})
render() {
return (
<div>
<button onClick={this.incrementCount}>Incrment</button>
</div>
import './App.css';
function App() {
return (
<div className="App">
<MyComponent/>
</div>
);
}
export default App;
useEffect
useContext
useReducer
useState
The State Hook allows us to easily create stateful function components. The hook takes an
argument, which sets our initial state.
The State Hook allows us to easily create stateful function components. The hook takes an
argument, which sets our initial state. It also returns an array of two values: the current state
and a function that we can use to update it. Through array destructuring, we can set the
names of these values ourselves:
useEffect
Where class components have lifecycle methods, function components have the Effect Hook.
This hook lets you include side effects such as data fetching, subscriptions and updates to the
DOM.
In a class component, effects are organised by when they occur during the lifecycle of the
component. Hooks instead let us group effects by relation. By default, effects will run after
every render, in the order they are specified.
side effects cleanups
Side effects happen a lot in React applications (in web applications generally. These effects include
making asynchronous API calls, updating the DOM, creating sockets, etc. These side effects can
happen when a button is clicked, when a form is submitted, or when a component mounts.
The useEffect hook in React gave functional components the power to do stuff when a component
mounts or when some props or state changes. This hook also allows you to cleanup when the
component unmounts.
What are side effects cleanups? Why should you cleanup them? How do you cleanup
them?
WHY SHOULD YOU CLEANUP WHEN A COMPONENT UNMOUNTS?
Memory leaks in JavaScript occur when a piece of memory is occupied unnecessarily. This means
that a portion of memory that should be available for use (should be accessible by a part of the
application) is not available. Instead of being unavailable for a good cause (such as being used by
another part of the application), it isn't.
When a component performs some side effects, the component indeed needs the side effects, so
memory isn't wasted. It's a good cause. But if the component "forgets" the side effect and unmounts,
it causes a leak. The side effect occupies some memory, but there's no component using it.
In some cases, Garbage Collection manages memory and clears up such memory usage. But if the
side effects "keep working", it will keep using that memory. A good example is a WebSocket
connection created by a component that unmounts later on. Since the connection keeps working, it
will be a memory leak (it is constantly connected and waiting for events).
With many needless things happening in the background, there is more memory usage. This is still
linked to the memory leaks situation. The more the memory usage, the lesser the available memory
to do other things, thereby affecting the user experience on your application. Responses may be
delayed, interactions may be delayed, and things like that.
3. TO PREVENT UNEXPECTED ERRORS IN OUR APPLICATIONS
Sometimes, these are also necessary to avoid bugs in our applications. A great example of such bugs
is when you are trying to "do something afterward" when a side effect completes, such as updating
the state from a component that has unmounted.
Let's see a quick code example. Say we have two components, App.js and Random.js like this:
// Random.js
useEffect(() => {
console.log("got here")
setTimeout(() => {
setState(1)
}, 3000)
}, [])
return <>Random</>
// App.js
setTimeout(() => {
setShow(false)
}, 1000)
}, [])
The App component has a show state such that when true, the Random component shows on the
screen. On mount, the App component sets a timeout if one second, which updates the show state
to false afterwards, thereby unmounting the Random component.
The Random component, on the other hand, has a state state, and on mounting, with a timeout of
three seconds, updates the state state.
But after one second, this Random component unmounts, which means on the third second where
the component oughts to update the state component, it won't exist. Running this gives this error:
So far, we have seen how and when to run a side effect. It is also essential that we clean up the side
effect to take care of the application's performance. Every side effects are different. So, the cleanup
strategy for the side effect will differ.
For example, if you have a side effect of running a timer using the setTimeout function, you need to
clean it up by invoking the clearTimeout function. But how do we do it?
To clean up a side effect, you must return a function from the callback function we pass to the
useEffect hook. You must place the side effect clean-up logic inside the returned function.
COPY
useEffect(() => {
// Side Effect
return () => {
}[props, state]);
The cleanup function gets invoked every time after the initial render to clean up the previous side
effect, and then the subsequent side effect runs.
Just like the name implies, the useEffect cleanup is a function in the useEffect Hook that allows us to
tidy up our code before our component unmounts. When our code runs and reruns for every render,
useEffect also cleans up after itself using the cleanup function.
The useEffect Hook is built in a way that we can return a function inside it and this return function is
where the cleanup happens. The cleanup function prevents memory leaks and removes some
unnecessary and unwanted behaviors.
Note that you don’t update the state inside the return function either:
useEffect(() => {
effect
return () => {
cleanup
}, [input])
Why is the useEffect cleanup function useful?
As stated previously, the useEffect cleanup function helps developers clean effects that prevent
unwanted behaviors and optimizes application performance.
However, it is pertinent to note that the useEffect cleanup function does not only run when our
component wants to unmount, it also runs right before the execution of the next scheduled effect.
In fact, after our effect executes, the next scheduled effect is usually based on the
dependency(array):
Therefore, when our effect is dependent on our prop or anytime we set up something that persists,
we then have a reason to call the cleanup function.
Let’s look at this scenario: imagine we get a fetch of a particular user through a user’s id, and, before
the fetch completes, we change our mind and try to get another user. At this point, the prop, or in
this case, the id, updates while the previous fetch request is still in progress.
It is then necessary for us to abort the fetch using the cleanup function so we don’t expose our
application to a memory leak.
Let’s say we have a React component that fetches and renders data. If our component unmounts
before our promise resolves, useEffect will try to update the state (on an unmounted component)
and send an error that looks like this:
Warning Error
According to React’s official documentation, “React performs the cleanup when the component
unmounts. However… effects run for every render and not just once. This is why React also cleans up
effects from the previous render before running the effects next time.”
The cleanup is commonly used to cancel all subscriptions made and cancel fetch requests. Now, let’s
write some code and see how we can accomplish these cancellations.
What are Components in ReactJS?
React components are the building blocks that make any React app. You take any React
app and it will have many components. You can consider it as a JavaScript class or
function that accepts inputs i.e. properties(props) and returns a React element that
describes how a section of the UI (User Interface) should appear.
ReactJS components allow you to break up the user interface into separate bits and
each bit can then be reused and handled independently.
It is easier to build an UI using individual pieces called components. When you work on
them independently, you can also merge the components to create the final UI.
render(){
return
Welcome Message!
You can create a functional component in React by writing a JavaScript function and
they may or may not receive data as parameters.
Example:
function Welcome(props) {
return
Hello, {props.name};
const Car=()=> {
return
render() {
return
Hi, I am a Car!
;
Simply put, JSX allows you to write concise HTML/XML-like structures in the same file
as you write JavaScript code. It is quite easy to create a JSX template in React. But this
does not mean that it is a simple language. It is a strong language with the power of
Javascript.
Instead of separating the markup and logic into separate files, React uses
components for this purpose.
The concept of mixing HTML and JavaScript in the same file is a debatable topic for
many, but you should use it if you find it helpful.
ReactJS JSX provides a concise and familiar syntax for defining a tree structure with
attributes that do not require learning a template language or unlearning JavaScript.
Both template language and JavaScript are useful for programmers creating large
applications.
For example, if you want to execute the expression: 2+2, the code will be:
const myelement = < h1 >React is {2 + 2} times better with JSX< /h1 >;
If you want to insert a large block of HTML, you need to write the text in a
parenthesis ().
React elements are produced as a result of using JSX.
JSX works on XML rules.
Once compiled, JSX expressions turn into regular JavaScript function calls.
ReactJS components allow you to break up the user interface into separate bits and
each bit can then be reused and handled independently.
It is easier to build an UI using individual pieces called components. When you work on
them independently, you can also merge the components to create the final UI.
Example:
const Democomponent=()=>
return
Welcome Message!
Example:
render(){
return
Welcome Message!
You can create a functional component in React by writing a JavaScript function and
they may or may not receive data as parameters.
Example:
function Welcome(props) {
return
Hello, {props.name};
In the first quarter of 2019, Hooks were introduced to the ReactJS with the React v16
8.0. With this, the functional components found some additional capabilities which
allowed these to work similar to class components.
Hence, the arrival of Hooks in ReactJS has made it easier to write React functional
components in modern apps. To be precise, Hooks allows developers to make use of
the states without having to write class components.
Events
function Greet() {
function eventHandler() {
return (
<div className="App">
<h1>Welcome to TCR</h1>
<button onClick={eventHandler}>Greeting</button>
</div>
);
eventHandler = () => {
render () {
return (
<div>
</div>
eventHandler = (name)=>{
};
render() {
return (
<div>
</div>