React Basics
React Basics
React Introduction
ReactJS, also known as React, is a popular JavaScript library for building user
interfaces. It is also referred to as a front-end JavaScript library. It was developed by
Facebook and is widely used for creating dynamic and interactive web applications. In
this article, we’ll explore the key concepts of React.
What is React?
React is a JavaScript library for building user interfaces (UIs) on the web. React is a
declarative, component based library that allows developers to build reusable UI
components and It follows the Virtual DOM (Document Object Model) approach,
which optimizes rendering performance by minimizing DOM updates. React is fast and
works well with other tools and libraries.
Prerequisite of React
For learning React first you have a clear understanding of HTML, CSS and JavaScript.
As React is a JavaScript library and uses most of its concept so you really have to
understands the major concepts of it.
HTML and CSS
JavaScript and ES6
JSX (Javascript XML) & Babel
Node+Npm
Git and CLI (Command Line Interface).
History of React
React was invented by Facebook developers who found the traditional DOM
slow. By implementing a virtual DOM, React addressed this issue and gained
popularity rapidly.
The current stable version of ReactJS is 18.2.0, released on June 14, 2022.
The library continues to evolve, introducing new features with each update.
How does React work?
React operates by creating an in-memory virtual DOM rather than directly
manipulating the browser’s DOM. It performs necessary manipulations within this
virtual representation before applying changes to the actual browser DOM. React is
efficient, altering only what requires modification.
Features of React
React is one of the most demanding JavaScript librarys because it is equipped with a
ton of features which makes it faster and production-ready. Below are the few
features of React.
1. Component-Based Architecture
React provides the feature to break down the UI into smaller, self-contained
components. Each component can have its own state and props.
5. Performance
As we discussed earlier, react uses virtual DOM and updates only the modified parts.
So, this makes the DOM to run faster. DOM executes in memory so we can create
separate components which makes the DOM run faster.
6. Components
React divides the web page into multiple components as it is component-based. Each
component is a part of the UI design which has its own logic and design as shown in
the below image. So the component logic which is written in JavaScript makes it easy
and run faster and can be reusable.
1. Initialization
This is the stage where the component is constructed with the given Props and default
state. This is done in the constructor of a Component Class.
2. Mounting Phase
Constructor: The constructor method initializes the component. It’s where
you set up initial state and bind event handlers.
render(): This method returns the JSX representation of the component. It’s
called during initial rendering and subsequent updates.
componentDidMount(): After the component is inserted into the DOM, this
method is invoked. Use it for side effects like data fetching or setting timers.
3. Updating Phase
componentDidUpdate(prevProps, prevState): Called after the component
updates due to new props or state changes. Handle side effects here.
shouldComponentUpdate(nextProps, nextState): Determines if the
component should re-render. Optimize performance by customizing this
method.
render(): Again, the render() method reflects changes in state or props
during updates.
4. Unmounting Phase
componentWillUnmount(): Invoked just before the component is removed
from the DOM. Clean up resources (e.g., event listeners, timers).
2.React Environment Setup
Note: Everything is explained in 01_React_TLO_Install_Setup
3.React Fundamentals
Table of Content
1. React JSX
2. ReactJS Babel Introduction
3. ReactJS Virtual DOM
4. React JS React DOM
5. ReactJS Lists
6. React Forms
7. ReactJS Keys
8. ReactJS Refs
9. ReactJS Rendering Elements
10. React Conditional Rendering
3.1.React JSX
React JSX is a syntax extension of JavaScript for writing React Code in a simple way.
Using JSX it is easier to create reusable UI components with fewer lines of code in a
template-type language with the power of JavaScript.
What is JSX ?
JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript.
React JSX helps us to write HTML in JavaScript and forms the basis of React
Development. Using JSX is not compulsory but it is highly recommended for
programming in React as it makes the development process easier as the code
becomes easy to write and read.
JSX creates an element in React that gets rendered in the UI. It is transformed into
JavaScript functions by the compiler at runtime. Error handling and warnings become
easier to handle when using JSX
This is called JSX (JavaScript XML), it somewhat looks like HTML and also uses a
JavaScript-like variable but is neither HTML nor JavaScript. With the help of JSX, we
have directly written the HTML syntax in JavaScript.
Why JSX ?
It is faster than normal JavaScript as it performs optimizations while
translating to regular JavaScript.
It makes it easier for us to create templates.
Instead of separating the markup and logic in separate files, React
uses components for this purpose. We will learn about components in detail
in further articles.
As JSX is an expression, we can use it inside of if statements and for loops,
assign it to variables, accept it as arguments, or return it from functions.
Expressions in JSX
In React we are allowed to use normal JavaScript expressions with JSX. To embed any
JavaScript expression in a piece of code written in JSX we will have to wrap that
expression in curly braces {}. The below example specifies a basic use of JavaScript
Expression in React.
In the above program, we have embedded the javascript expression const name =
“Learner”; in our JSX code. We can use conditional statements instead of if-else
statements in JSX.
Attributes in JSX
JSX allows us to use attributes with the HTML elements just like we do with normal
HTML. But instead of the normal naming convention of HTML, JSX uses the camelcase
convention for attributes.&
Example 3: This example has a custom attribute with the <h2> tag and we are using
className attribute instead of class.
Specifying attribute values:
JSX allows us to specify attribute values in two ways:
Wrapping elements or Children in JSX
Consider a situation where you want to render multiple tags at a time. To do this we
need to wrap all of these tags under a parent tag and then render this parent element
to the HTML. All the subtags are called child tags or children of this parent element.
Example: In this example we have wrapped h1, h2, and h3 tags under a single div
element and rendered them to HTML:
Note: JSX will throw an error if the HTML is not correct or if there are multiple child
elements without a parent element.
Comments in JSX:
JSX allows us to use comments as it allows us to use JavaScript expressions. Comments
in JSX begin with /* and ends with */. We can add comments in JSX by wrapping them
in curly braces {} just like we did in the case of expressions. The below example shows
how to add comments in JSX:
In order to manually setup babel in React with webpack follow the below steps.
Step 1: Create the folder where you want the application and navigate to it using the
command:
After following the above steps the dependencies in package.json will look like:
Step 5: Create the files named index.html, App.js, index.js,
webpack.config.js, .babelrc
Step 6: Write the following code in webpack.config.js file
Step 7: Inside the scripts section of package.json file add the following code
{
"name": "my-app",
"version": "1.0.0",
"description": "",
Step 9: To run the application, type the following command in a web browser
Features of Babel:
Babel-Plugins: The Plugins are configuration details for Babel to transpile
the code that supports a number of plugins, which could be used
individually, provided the environment is known.
Babel-Presets: Babel presets have a set of plugins that instruct Babel to
transpile in a specific mode. provided the environment is known.
Babel-Polyfills: During instances when methods and objects, cannot be
transpiled, We can make use of babel-polyfill to facilitate the use of features
in any browser.
Babel-CLI: The Command-line interface of Babel has a lot of commands
where the code can be easily compiled on the command line. It also has
features like plugins and presets to be used along with the command making
it easy to transpile the code at once.
3.3.ReactJS Virtual DOM
React JS Virtual DOM is an in-memory representation of the DOM. DOM refers to the
Document Object Model that represents the content of XML or HTML documents as a
tree structure so that the programs can be read, accessed and changed in the
document structure, style, and content.
What is DOM?
DOM stands for ‘Document Object Model’. In simple terms, it is a structured
representation of the HTML elements that are present in a webpage or web app. DOM
represents the entire UI of your application. The DOM is represented as a tree data
structure. It contains a node for each UI element present in the web document. It is
very useful as it allows web developers to modify content through JavaScript, also it
being in structured format helps a lot as we can choose specific targets and all the
code becomes much easier to work with.
Example:
When writing the above code in the console or in the JavaScript file, these things
happen:
The browser parses the HTML to find the node with this id.
It removes the child element of this specific element.
Updates the element (DOM) with the ‘updated value’.
Recalculates the CSS for the parent and child nodes.
Update the layout.
Finally, traverse the tree and paint it on the screen(browser) display.
Recalculating the CSS and changing the layouts involves complex algorithms, and they
do affect the performance. So React has a different approach to dealing with this, as it
makes use of something known as Virtual DOM.
Virtual DOM
React uses Virtual DOM exists which is like a lightweight copy of the actual DOM(a
virtual representation of the DOM). So for every object that exists in the original DOM,
there is an object for that in React Virtual DOM. It is exactly the same, but it does not
have the power to directly change the layout of the document.
Manipulating DOM is slow, but manipulating Virtual DOM is fast as nothing gets
drawn on the screen. So each time there is a change in the state of our application, the
virtual DOM gets updated first instead of the real DOM.
React maintains two Virtual DOM at each time, one contains the updated Virtual DOM
and one which is just the pre-update version of this updated Virtual DOM. Now it
compares the pre-update version with the updated Virtual DOM and figures out what
exactly has changed in the DOM like which components have been changed. This
process of comparing the current Virtual DOM tree with the previous one is known
as ‘diffing’. Once React finds out what exactly has changed then it updates those
objects only, on real DOM.
React uses something called batch updates to update the real DOM. It just means that
the changes to the real DOM are sent in batches instead of sending any update for a
single change in the state of a component.
We have seen that the re-rendering of the UI is the most expensive part and React
manages to do this most efficiently by ensuring that the Real DOM receives batch
updates to re-render the UI. This entire process of transforming changes to the real
DOM is called Reconciliation.
This significantly improves the performance and is the main reason why React and its
Virtual DOM are much loved by developers all around.
The diagrammatic image below briefly describes how the virtual DOM works in the
real browser environment.
Keys are used in React to identify which items in the list are changed, updated, or
deleted. We will learn about keys in more detail in our ReactJS keys Notes.
3.5.React Forms
Forms in React JS are really important for login, signup, or user interaction to the web
page. In HTML the form data is usually handled by the DOM itself but in the case of
React Forms data is handled by the react components.
React Forms
In React Forms, all the form data is stored in the React’s component state, so it can
handle the form submission and retrieve data that the user entered. To do this we use
controlled components.
React forms are used to interact with the user and provides additional functionality
such as preventing the default behavior of the form which refreshes the browser after
the form is submitted.
Controlled Components
In simple HTML elements like input tags, the value of the input field is changed
whenever the user type. But, In React, whatever the value the user types we save it in
state and pass the same value to the input tag as its value, so here DOM does not
change its value, it is controlled by react state. These are known as Controlled
Components.
Forms in React can be easily added as a simple react element. Here are some examples
3.6.ReactJS Keys
React JS keys are a way of providing a unique identity to each item while creating the
React JS Lists so that React can identify the element to be processed.
What is a key in React?
A “key” is a special string attribute you need to include when creating lists of elements
in React. Keys are used in React to identify which items in the list are changed,
updated, or deleted.
Keys are used to give an identity to the elements in the lists. It is recommended to use
a string as a key that uniquely identifies the items in the list.
Output: You can see in the below output that the list is rendered successfully but a
warning is thrown to the console that the elements inside the iterator are not assigned
keys. This is because we had not assigned the key to the elements we are returning to
the map() iterator.
Uniqueness of Keys:
We have told many times while discussing keys that keys assigned to the array
elements must be unique. By this, we did not mean that the keys should be globally
unique. All the elements in a particular array should have unique keys. That is, two
different arrays can have the same set of keys.
Now, we are going to see how we can use refs in our code which will help you to
understand the use case of refs better.
Example
In this example, we use the target value of event e, for getting the value.
Refs Current Properties
The current property value of refs depends on the ref target. Look at the table below,
to understand the difference.
Conclusion
React refs are useful to interact with the DOM structure of components. They can
directly access and manipulate the DOM elements. This guide teaches the purpose of
refs in React, how to create refs, and how to use refs in React with examples.
Now, in order to render a simple React Element to the root node, we must write the
following in the App.js file.
Output
Now, you have created your first ever React Element and also have rendered it in
place, but React was not developed to create static pages, the intention of using React
is to create a more logical and active webpage. In order to do so, we will need to
update the elements. This next section will guide us through the same.
In the above example, we have created a function showTime() that displays the
current time, and we have set an interval of 1000ms or 1 sec that recalls the function
each second thus updating the time in each call. For simplicity, we have only shown
the timespan of one second in the given image.
In the example of displaying the current time, at each second we call the render
method, and the virtual DOM gets updated and then the differentiator checks for the
particular differences in Browser DOM and the Virtual DOM and then updates only
what is required such as in the given example the time is the only thing that is getting
changed each time not the title “Welcome to Learning React!” thus React only updates
the time itself making it much more efficient than conventional DOM manipulation.
Open your react project directory and edit the Index.js file from src folder:
// Message Component
// Message Component
function Message(props)
{
if (props.isLoggedIn)
return <h1>Welcome User</h1>;
else
return <h1>Please Login</h1>;
}
// Login Component
function Login(props) {
return <button onClick={props.clickFunc}>Login</button>;
Explanation:
In the above output, you can see that on clicking the Login button the message and
button get’s changed and vice versa.
We can use the logical && operator along with some condition to decide what will
appear in output based on whether the condition evaluates to true or false. Below is
the syntax of using the logical && operator with conditions:
If the condition provided in the above syntax evaluates to True then the elements
right after the && operator will be a part of the output and if the condition evaluates
to false then the code within the curly braces will not appear in the output.
logical && operator Example:
Below example is used to illustrate the above-mentioned approach Open your react
project directory and edit the Index.js file from src folder:
Explanation:
You can clearly see in the above output that as the condition (counter == 5) evaluates
to true so the <h1> element is successfully rendered on the screen.
3. Conditional Rendering using ternary operator
In JavaScript we have a short syntax for writing the if-else conditions due to which the
code becomes shorter and easy to read. If the boolean returns true then the element
on left will be rendered otherwise element on the right will be rendered
As websites grow larger and go deeper into components, it becomes heavier. This is
especially the case when libraries from third parties are included. Code Splitting is a
method that helps to generate bundles that are able to run dynamically. It also helps
to make the code efficient because the bundle contains all required imports and files.
Bundling and its efficiency: Bundling is the method of combining imported files with a
single file. It is done with the help of Webpack, Rollup, and Browserify as they can
create many bundles that can be loaded dynamically at runtime.
With the help of code splitting, ‘lazy load’ can be implemented, which means just using
the code which is currently needed.
The default way of importing is as follows:
When Babel is being used, it has to be made sure that Babel is not transforming the
import syntax, but can parse it dynamically. This can be done using babel-plugin-
syntax-dynamic-import.
React.lazy and Suspense.
As both React.lazy and Suspense are not available for rendering on the server yet now,
it is recommended to use loadable-components for code-splitting in a server-rendered
app. React.lazy is helpful for rendering dynamic import as a regular component.
Before:
After:
The Bundle will be loaded on its own which contains the Component when this
component is rendered first.
The Lazy component should then be rendered inside Suspense Component which
helps to reflect some fallback content meanwhile the lazy component loads.
The fallback prop can accept any element of React which will be rendered while
waiting for the loading of the Component. The Suspense Component can be placed
anywhere above the lazy component. Moreover, multiple lazy components can be
wrapped with a single Suspense Component.
Error Boundaries
Error Boundaries are React components that help when some modules fail to load due
to any issue, an error will be triggered. These errors can be handled properly and
provide a good experience to the user by the use of a suitable error page.
It can be difficult to implement code-splitting in code, the bundles can be split evenly,
which will improve the experience for the user.
Here you can see the example code for this.
Named Exports
React.lazy currently supports only default exports. An intermediate module that re-
exports as default has to be created if one wants to import a module that uses named
exports. This ensures the working of tree shaking and prevents the pulling in of unused
components.
4.2. React Components
In React, components serve as independent and reusable code blocks for UI elements.
They represent different parts of a web page and contain both structure and behavior.
They are similar to JavaScript functions and make creating and managing complex
user interfaces easier by breaking them down into smaller, reusable pieces.
A UI is broken down into multiple individual pieces called components. You can work
on components independently and then merge them all into a parent
component which will be your final UI.
You can see in the below image we have broken down the UI of GeeksforGeeks’s
homepage into individual components.
Components in React return a piece of JSX code that tells what should be rendered on
the screen.
Types of Components in React
In React, we mainly have two types of components: Functional and Class based.
Class Component must include the line “extends React.Component” to pass data from
one class component to another class component. We can use JavaScript ES6 classes
to create class-based components in React.
Syntax for Class Components:
The components we created in the above two examples are equivalent, and we also
have stated the basic difference between a functional component and a class
component. We will learn about more properties of class-based components in further
tutorials.
While class-based components can achieve the same result, they are generally less
efficient compared to functional components. Therefore, it’s recommended to not use
class components for general use.
Rendering React Components
Rendering Components means turning your component code into the UI that users
see on the screen.
React is capable of rendering user-defined components. To render a component in
React we can initialize an element with a user-defined component and pass this
element as the first parameter to ReactDOM.render() or directly pass the component
as the first argument to the ReactDOM.render() method.
Example
This example renders a component named Welcome to the Screen.
Props
Props(short for properties) are a way to pass data from the parent
component to the child component.
Props are like function arguments, you can use them as attributes in
components.
Example:
Components in Components
We can call components inside another component
Example
The above code will give the same output as other examples but here we have called
the Greet component inside the Welcome Component.
Conclusion
Components in React allow developers to divide the page UI into many small parts.
These parts work independently and can be used multiple times just like functions.
This tutorial introduces you to the concept of components. We have discussed types of
components and their purpose in web development. This guide will help you
understand web UI and how can you create visually appealing web UI.
4.3. ReactJS | Components – Set 2
In our previous article on ReactJS | Components we had to discuss components, types
of components, and how to render components. In this article, we will see some more
properties of components.
Filename- App.js:
The above code works well to create a form. But let us say now we need some other
form with three input fields. To do this we will have to again write the complete code
with three input fields now. But what if we have broken down the Form component
into two smaller components, one for the input field and another one for the button?
This could have increased our code reusability to a great extent. That is why it is
recommended to React to break down a component into the smallest possible units
and then merge them to create a parent component to increase the code modularity
and reusability. In the below code the component Form is broken down into smaller
components Input and Button.
Till now, we have worked with Components with only static data. That is, we are
writing data directly inside a Component. What if, we want to pass some data to our
Components? React allows us to do so with the help of another property called props.
We will learn about props in detail in our next article.
4.4. ReactJS Pure Components
Generally, In ReactJS, we use shouldComponentUpdate() Lifecycle method to
customize the default behavior and implement it when the React component should
re-render or update itself.
In simple words, If the previous value of the state or props and the new value of the
state or props are the same, the component will not re-render itself. Pure
Components restricts the re-rendering when there is no use for re-rendering of the
component. Pure Components are Class Components that
extend React.PureComponent.
Extending React Class Components with Pure Components ensures the higher
performance of the Component and ultimately makes your application faster, While in
the case of Regular Component, it will always re-render either value of State and Props
changes or not.
While using Pure Components, Things to be noted are that, In these components, the
Value of State and Props are Shallow Compared (Shallow Comparison) and It also
takes care of “shouldComponentUpdate” Lifecycle method implicitly.
So there is a possibility that if these State and Props Objects contain nested data
structure then Pure Component’s implemented shouldComponentUpdate will return
false and will not update the whole subtree of Children of this Class Component. So
in Pure Component, the nested data structure doesn’t work properly.
In this case, State and Props Objects should be simple objects and Child Elements
should also be Pure, means to return the same output for the same input values at any
instance.
4.5. ReactJS Functional Components
Functional Component is one way to create components in a React Application.
React.js Functional Components helps to create UI components in a Functional and
more concise way. In this article, we will learn about functional components in React,
different ways to call the functional component, and also learn how to create the
functional components. We will also demonstrate the use of hooks in functional
components.
1. Call the function by using the name of the function followed by the Parentheses.
Functional Components
Functional components are some of the more common components that will come
across while working in React. These are simply JavaScript functions. We can create a
functional component to React by writing a JavaScript function.
Syntax:
Syntax:
In the above example, for functional components, we use hooks (useState) to manage
the state. If you write a function component and realize you need to add some state to
it, previously you had to convert it to a class component. Now you can use a Hook
inside the existing function component to manage the state and no need to convert it
into the Class component. Hooks are a new addition to React 16.8. They let you use
state and other React features without writing a class. Instead of Classes, one can use
Hooks in the Functional component as this is a much easier way of managing the state.
Hooks can only be used in functional components, not in-class components.
Functional components run from top to The class component is instantiated and
bottom and once the function is returned it different life cycle method is kept alive
can’t be kept alive. and is run and invoked depending on the
phase of the class component.
React lifecycle methods (for example, React lifecycle methods can be used
componentDidMount) cannot be used in inside class components (for example,
functional components. componentDidMount).
Hooks can be easily used in functional It requires different syntax inside a class
components to make them Stateful. component to implement hooks.
Example Example: