Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Introduction To React

Uploaded by

sfsd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Introduction To React

Uploaded by

sfsd
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

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.

• It is also a popular choice for building SPA (single-page applications).


• It was first used by Facebook in 2011. Later, when Facebook acquired
Instagram, they too wanted to use React.
• Back in 2011, Jordan Walke, a software engineer at Facebook, created
this library to handle the increasing number of updates.
Step-by-Step Process to Set Up ReactJS Development
Environment

1. Install Node.js and npm


 node -v
 npm –v
2. Install create-react-app using npm
ReactJS installation is to download the create-node-app package using
npm (node package manager).

 npm install -g create-react-app


3. Create a project using create-react-app
Create a new folder on your desktop and rename it to React. Open
command prompt through this folder and run the following command:
 create-react-app myapp
4. Change to that folder
Test the React app
 npm start
You can open this folder and see all the subfolders and files created for creating
the ReactJS app using the create-react-app command.

How to Create project in React

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.

src is one of the main folder in react project.

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

// vaue of variable x is changed

x = 3;

console.log(x); // 3

const x = 5;

x = 10; // Error! constant cannot be changed.

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,

let sum = 44;

console.log(sum); // 44

// program to print variables values

// storing values

const greet = 'Hello';

const name = 'Jack';

console.log(greet + ' ' + name);

JavaScript Operator Types

Here is a list of different operators you will learn in this tutorial.

• Assignment Operators

• Arithmetic Operators

• Comparison Operators

• Logical Operators

• Bitwise Operators

• String Operators

• Other Operators
let x = 5;

let y = 3;

// addition

console.log('x + y = ', x + y); // 8

// subtraction

console.log('x - y = ', x - y); // 2

// multiplication

console.log('x * y = ', x * y); // 15

// division

console.log('x / y = ', x / y); // 1.6666666666666667

// remainder

console.log('x % y = ', x % y); // 2

// increment

console.log('++x = ', ++x); // x is now 6

console.log('x++ = ', x++); // prints 6 and then increased to 7

console.log('x = ', x); // 7

// decrement

console.log('--x = ', --x); // x is now 6

console.log('x-- = ', x--); // prints 6 and then decreased to 5

console.log('x = ', x); // 5

//exponentiation

console.log('x ** y =', x ** y);


JavaScript ES6 (also known as ECMAScript 2015 or ECMAScript 6) is the newer version of JavaScript
that was introduced in 2015.

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,

1. Variables creation using let and const


2. Template String
3. Arrow functions
4. Rest and spread operator
5. Destructuring
6. Arrow function : find() and findindex()
7. Classess
8. And much more
// variable declared using let

let name = 'Sara';

// can be accessed only inside

let name = 'Peter';

console.log(name); // Peter

console.log(name); // Sara

JavaScript const

The const statement is used to declare constants in JavaScript. For example,

// name declared with const cannot be changed

const name = 'Sara';

Once declared, you cannot change the value of a const variable.

JavaScript Arrow Function

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

let x = (x, y) => x * y;

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

Default Parameter Values

In the ES6 version, you can pass default values in the function parameters. For example,

function sum(x, y = 5) {

// take sum

// the value of y is 5 if not passed

console.log(x + y);

sum(5); // 10

sum(5, 15); // 20

It It preprocessor for JavaScript/ECMAScript.

It is mainly used to convert ES6+ code into a backwards compatible version of JavaScript that can be
run by older browsers.

import React from 'react';


import logo from './logo.svg';
import './App.css';

function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />

<h1> welcome to react.js application </h1>


Learn React

</header>
</div>
);
}

export default App;


Babel

 It It preprocessor for JavaScript/ECMAScript.

 It is mainly used to convert ES6+ code into a backwards compatible version of JavaScript that
can be run by older browsers.

Essential JavaScript(ES6) for React

 Let

 const

 Functions and Arrow Functions

 Objects

 Arrays and array methods

 Destructuring

 Template literals

 Ternary Operators

 ES Modules and Import / Export Syntax


Components
Components represents a part of the user interface.

 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.

 E.g root component usually name as App component in your application

 Same component can be use with different properties to display different information.

 A Components can contains other components also.

 Component code usually placed in a JavaScript file .e.g App.js

Components come in two types,


 functional components (stateless)

 Class components and (stateful)


functional components
 A functional component is basically a JavaScript function that returns a React element (JSX).

 The first, most important and recommended component type in React is a functional
component.

 You need to export the component in order to use it somewhere else.

function HelloWorld() {

return <h1>Hello World</h1>;

export default HelloWorld;

import logo from './logo.svg';

import './App.css';

import HelloWorld from './HelloWorld';

function App() {

return (

<div className="App">

<HelloWorld/>

</div>

);

export default App;


 Alternatively, you can also create a functional component with the arrow function
syntax(ES6).

 Code:

const HelloWorld = () => {

return <h1>Hello world</h1>;

};

 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.

import HelloWorld from "./HelloWorld";

const App = () => {

return (

<div className="App">

<header className="App-header">

<HelloWorld />

</header>

</div>

);

};

export default App;

 In short, a functional component is a JavaScript function or ES6 function which takes props as
arguments and returns a JSX.

 Components should always start with a capital letter.

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.

import React from 'react'

class Welcome extends React.Component {

render () {

return (

<div>

<h1>Welcome</h1>

</div>

export default Welcome

App.js

import './App.css';

import Welcome from './Welcome';

function App() {

return (

<Welcome/>

);

export default App;


class HelloWorld extends React.Component {

render() {

return <h1>Hello World</h1>;

}
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

 Extension to the JavaScript language syntax

 HTML like syntax extension and JavaScript

 Write XML-like code for elements and components.

 JSX tags have a tag name , attributes and children

import React from "react";

// with JSX example

const Hello=()=>{

return (

<div>

<h1>Hello</h1>

</div>

export default Hello


import React from "react";

// without JSX example

const Welcome =()=> {

// return React.createElement('div',null,'Welcome')

return React.createElement('div',null,'Welcome')

export default Welcome

Props
 Props are arguments passed into react component

 Props are passed to components via HTML attributes

 Props stands for properties

 React pops are like function arguments in JavaScript and attribtes in HTML

 Props are read-only

import React from "react";

//props in class component

class Welcome extends React.Component

render()

{ //this.props.name ="abc"

return(

<div>

<h1>Hello {this.props.name}</h1>

</div>
)

export default Welcome

import './App.css';

import Welcome from './Welcome';

function App() {

return (

<div className="App">

<Welcome name="Raj" />

<Welcome name="Simran" />

<Welcome name="Arun" />

</div>

);

export default App

import React from "react";


function Profile(props) {

return (

<div>

<h2> Your Name is {props.name} </h2>

<p>{props.children} </p>

</div>

export default Profile

import React from "react";

function Profile(props) {

return (

<div>

<h2> Your Name is {props.name} </h2>

<p>{props.children} </p>

</div>

export default Profile

App.js

import './App.css';
import Profile from './Profile';

function App() {

return (

<div className="App">

<Profile name="Raj">

<p> Branch : Computer Science </p>

</Profile>

<Profile name="Simran">

<p> Branch : Information Tech. </p>

</Profile>

<Profile name="Arun">

<p> Branch : Automobile </p>

</Profile>

<Profile name="Harshad">

<p> Branch : Computer Science </p>

</Profile>

</div>

);

export default App;

import logo from './logo.svg';


import './App.css';

function App() {

return (

<div className="App">

<header className="App-header">

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

<p>

Edit <code>src/App.js</code> and save to reload.

</p>

<a

className="App-link"

href="https://reactjs.org"

target="_blank"

rel="noopener noreferrer"

>

Learn React

</a>

</header>

</div>

);

export default App;

conditional operators
import React, { Component } from
'react';

//Logical And && Operator


export default class JSXComponent1
extends Component {
render() {
let user = true;
let isAdmin = true;
let result;
if (user && isAdmin) {
result = 'Conditrion is truthy';
}
return (
<div className="row">
{
result
}
</div>
);
}
}

//Logical OR || Operator

import React, { Component } from


'react';

export default class JSXComponent2


extends Component {
render() {
let user = false;
let isAdmin = true;
let result;
if (user || isAdmin) {
result = 'Conditrion is truthy';
} else {
result = 'Conditrion is false';
}
return (
<div className="row">
{
result
}
</div>
);
}
}

Destructing
import React from 'react';

const Employee = (props) => {

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>

export default Employee;

App.js

import logo from './logo.svg';


import './App.css';
import Employee from './Employee';
function App() {

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>
);
}

export default App;


Handling Events in React
 The event handler determines what to do whenever an event is triggered. The event could
be a button click, a keyboard keypress, or a hovering mouse cursor.

 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.

1. Handling events in function component


2. Handling events in class component

Arguments Passing to Event Handler


 Let’s say that you want to customize the message displayed on clicking the button , you want
to display the name of the user. You want to change it for every user so you need a way to
pass arguments to event handlers.

 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.

 There are two methods in this phase, they are:

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()

After the shouldComponentUpdate method is executed, componentWillUpdate method is called.


This method is invoked before re-rendering the component. This method also receives
arguments nextProps and nextState. There may arise situations where you might want to
perform some calculations before re-rendering the component. After updating the state and
props such calculations can be included inside this method.

componentDidUpdate()

 This method is invoked after re-rendering the component. The componentDidUpdate


method is executed after the component gets updated on the DOM. This method receives
arguments prevProps and prevState.
Unmounting Phase

 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";

//life cycle methods of Component

class Greet extends React.Component {

constructor(){

super()

console.warn("constructor")

componentDidMount() {

console.warn("componentDidMount");

render() {

console.warn("render")

return(

<div>

<h1> Life Cycle Methods</h1>

</div>

export default Greet;


Props Validation

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 –

 PropTypes.any:- the prop can be of any data type

 PropTypes.bool:- the prop should be a boolean

 PropTypes.number:- the prop should be a number

 PropTypes.string:- the prop should be a string

 PropTypes.func:- the prop should be a function

 PropTypes.array:- the prop should be an array

 PropTypes.object:- the prop should be an object

 PropTypes.symbol:- the prop should be a symbol

 PropTypes.instanceOf :- the prop should be an instance of a particular JavaScript class

 PropTypes.isRequired :- the prop should be provided

 React Lists

 In React, you will render lists with some type of loop.

 The JavaScript map() array method is generally the preferred method.


import React from 'react';

import PropTypes from 'prop-types';

function Greet(props) {

return <h1>Hello, {props.name}!</h1>;

Greet.propTypes = {

name: PropTypes.string.isRequired

Greet.defaultProps = {

name: "Ramesh"

export default Greet;

import './App.css';

import Greet from './Greet';

function App() {

return (

<Greet/>

);

export default App;


import React, {useState} from 'react'

export default function Counter () {

const [count, setCount] = useState(0);

const increment =() => {

setCount(count+1);

const decrement =() => {

setCount(count-1);

return (

<div>

<p> Count:{count} </p>

<button onClick={increment}>increment</button>

<button onClick={decrement}>descrement</button>

</div>

useEffect

//useEffect
import React, {useState, useEffect } from "react";

export default function ExampleComponent() {

const [count,setCount] = useState(0);

useEffect( () => {

console.log("Effect executed") ;

document.title = `Count : ${count}`;

},[count]);

return (

<div>

<p> Count : {count} </p>

<button onClick={()=> setCount(count+1)}>Increment</button>

</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.

const userNames = ['Jesse', 'Tom', 'Anna']


function App() {

const renderListOfUserNames = (names) => {

return names.map(name => <li>{name}</li>)

return (

<div>

<ul>

{renderListOfUserNames(userNames)}

</ul>

</div>

);

export default App;

Hooks

useState

import React, { Component } from "react";

class MyComponent extends Component {

constructor(props) {

super(props)

this.state= {

count :0

}
}

incrementCount=()=> {

this.setState( {

count: this.state.count +1

})

render() {

return (

<div>

<h1>Count : {this.state.count} </h1>

<button onClick={this.incrementCount}>Incrment</button>

</div>

export default MyComponent

import './App.css';

import MyComponent from './MyComponent';

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?

 To avoid memory leaks


 To optimize our applications for a good user experience
 To prevent unexpected errors in our applications

1. TO AVOID MEMORY LEAKS

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).

2. TO OPTIMIZE OUR APPLICATIONS FOR A GOOD USER EXPERIENCE

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

import { useEffect, useState } from "react"

export default function Random() {

const [state, setState] = useState(0)

useEffect(() => {

console.log("got here")

setTimeout(() => {

setState(1)

}, 3000)

}, [])

return <>Random</>

// App.js

import { useState, useEffect } from "react"

import Random from "./Random"

export default function App() {

const [show, setShow] = useState(true)


useEffect(() => {

setTimeout(() => {

setShow(false)

}, 1000)

}, [])

return <div>{show && <Random />}</div>

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:

6. Side Effect Cleanup

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 () => {

// Side Effect Cleanup

}[props, state]);

A few points to note,

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.

The cleanup function gets invoked when the component unmounts.

What is the useEffect cleanup function?

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):

// The dependency is an array

useEffect( callback, dependency )

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.

When should we use the useEffect cleanup?

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

To fix this error, we use the cleanup function to resolve it.

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.

Types of Components in React


React components are of two types: Class components and Functional components.

 Functional Components in ReactJS:


Functional components are like JavaScript functions. You can create a functional
component in React by just writing a JavaScript function. It is not necessary that these
functions will receive data as parameters. They may or may not.

 Class Components in ReactJS:


There’s a little more complexity involved when it comes to class components. While the
functional components are not aware of the other components in your program, the class
components have that awareness and can work with each other. You can transfer data
from one class component to another.

class Democomponent extends React.Component


{

render(){

return

Welcome Message!

Understanding Functional Components in ReactJs?


You will often come across functional components while working in React. A functional
component in React is like a JavaScript/ES6 function that returns a React element
(JSX).

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};

Difference between Functional and


Class Components in ReactJs

What are Functional Components in ReactJS?


They are the most common type of component in React. You can create a functional
component simply by writing in JavaScript.

Syntax for functional components:

const Car=()=> {

return

Hi, I am also a Car!


;
}

What are Class Components in ReactJS?


It is a regular ES6 class that extends the component class of the React library. These
components are made of simple classes.

Syntax for class components:

class Car extends React.Component {

render() {

return

Hi, I am a Car!
;

ReactJS Functional Components V/s Class


Components Comparision
JSX

What is JSX in ReactJS?


JSX is the abbreviation used for JavaScript XML. It is an HTML-like syntax extension of
JavaScript. It is used by React so that HTML-like text can be written in React in
Javascript code.

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.

If we talk of speed, JSX is faster than JavaScript. Here’s why:

 JSX performs optimizations while translating to regular 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.

Characteristics of JSX in ReactJS


 Using JSX is not mandatory, but its usage makes it easier for programmers to
develop React applications.
 In JSX, you can write expressions in curly braces { }. The expression can be any
JS expression or React variable, or property. JSX will execute the expression in
the braces and return the result.

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.

Advantages of Using JSX in React


 It is easy to write HTML text in React using JSX.
 HTML tags can easily be converted to React JS elements.
 The programming language becomes faster than when you use JavaScript.
 You can put HTML elements in DOM without using appendChild() or
createElement().
 XSS (cross-site-scripting) attacks, also known as injection attacks, can be
prevented with the use of JSX.
 You can detect most of the errors during the compilation time only.
 Being an expression, JSX can be used inside ‘if statements’ and ‘for loops’. It is
also possible to assign this expression to variables and accept it as arguments.

Disadvantages of Using JSX in React


While there are many pros of using JSX in React JS, a few drawbacks could be:

 If the HTML is not correct, JSX will show you an error.


 If you do not wrap the HTML text in a top element, JSX will give an error.
 JSX will also give an error if the elements are not appropriately closed.

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.

Types of Components in React


React components are of two types: Class components and Functional components.

 Functional Components in ReactJS:


Functional components are like JavaScript functions. You can create a functional
component in React by just writing a JavaScript function. It is not necessary that these
functions will receive data as parameters. They may or may not.

Example:

const Democomponent=()=>

return

Welcome Message!

 Class Components in ReactJS:


There’s a little more complexity involved when it comes to class components. While the
functional components are not aware of the other components in your program, the class
components have that awareness and can work with each other. You can transfer data
from one class component to another.

Example:

class Democomponent extends React.Component

render(){
return

Welcome Message!

 Pure components in ReactJS :


When functions return the same output on being given the same input in JavaScript,
they are called Pure Components. Simply put, a pure component in react returns the
same data for the same input. In pure functions, the output only depends on the input
arguments.

Consider for example, this.

function Add(num1, num2){

return num1 + num2;

Understanding Functional Components in ReactJs?


You will often come across functional components while working in React. A functional
component in React is like a JavaScript/ES6 function that returns a React element
(JSX).

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};

Introduction of React Hooks for Functional


Components
As discussed earlier, the functional components are created using the JavaScript
functions. These components accept props and show the output as a React element.

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

import React from "react";

//function component event handling

function Greet() {

function eventHandler() {

alert('Good Evening Student ...!!!');

return (

<div className="App">

<h1>Welcome to TCR</h1>

<button onClick={eventHandler}>Greeting</button>

</div>

);

export default Greet;


import React from "react";

//class component event handling

// use this keyword

class Welcome extends React.Component {

eventHandler = () => {

alert("welcome to event handler ");

render () {

return (

<div>

<h1>Welcome to Events in React </h1>

<button onClick={this.eventHandler}>Click me</button>

</div>

export default Welcome

import React from "react";

export default class Message extends React.Component {

eventHandler = (name)=>{

alert(`Welcome to Events ${name}`);

};
render() {

return (

<div>

<h1>Good Evening Everyone </h1>

<button onClick={()=>this.eventHandler("Raj")}>Clik me</button>

</div>

You might also like