React Js Tutorial
React Js Tutorial
React has becomes one of the most Popular javascript libraries for
building user interfaces.
1. Declarative Syntax:
React uses a declarative approach to build UIs, which makes it easier to
understand and maintain code.
Developers can describe a desired state of their UI, and React takes care
of updating the DOM to match that state efficiently.
2. Component-Based Architecture:
Reacts component-based architecture encourages modular and reusable
code.
UIs are broken down into small, self-contained components, which can be
composed together to build complex interfaces.
This approach promotes code reusability, maintainability and scalability.
3. Community and Ecosystem:
React is developed and maintained by Meta formerly known as
Facebook.
React has a large and active community of developers, which means there
are plenty of resources, libraries and tools available to support
development.
This vibrant ecosystem makes it easier to find solutions to common
problems, learn new techniques, and stay up-to-date with the latest
developments in web development.
4. Unidirectional Data Flow:
React follows a unidirectional data flow, where data flows in one
direction from parent to child components.
This helps maintain a predictable state of the application and makes it
easier to debug and reason about the behavior of the UI.
5. Virtual DOM:
React uses a virtual DOM to optimize DOM manipulation. Instead to
directly updating the DOM for every state change, react compares the
virtual DOM with the previous state and computes the minimum number
of DOM updates required to reflect the changes.
This approach results in faster rendering performance and a smoother
user experience.
6. Performance:
Reacts virtual DOM and efficient reconciliation algorithm contribute to
its excellent performance, even for complex and dynamic UI’s.
Additionally, react lightweight footprint and efficient rendering makes it
suitable for building high performance web applications.
7. JSX:
React JSX syntax allows developer to write HTML like code directly
within JavaScript, which makes it easier to create and maintain UI
components.
JSX also enables the use of Javascript expressions and logic within the
markup, providing a more expressive and powerful way to build UIs.
****************************************************************
What is React?
React.js, commonly referred to as React, is an open-source JavaScript
library developed and maintained by Facebook.
It's primarily used for building user interfaces (UIs) for single-page
applications (SPAs) and web applications.
Here are some key aspects of React.js:
1. Component-Based:
React.js is based on the concept of reusable components.
Components are small, self-contained units that represent a part of the UI.
They can be composed together to build complex UIs.
This component-based architecture promotes reusability, maintainability,
and scalability of code.
2. Virtual DOM:
React.js utilizes a virtual DOM (Document Object Model) to optimize
rendering performance.
Instead of directly manipulating the browser's DOM, React creates a
lightweight virtual representation of the DOM in memory.
When changes occur, React calculates the most efficient way to update
the actual DOM, minimizing the number of manipulations and improving
performance.
3. JSX Syntax:
React introduces JSX (JavaScript XML), which is a syntax extension for
JavaScript. JSX allows developers to write HTML-like code directly
within JavaScript, making it easier to describe the UI components'
structure and behavior.
JSX is then compiled to standard JavaScript before being interpreted by
the browser.
4. Declarative Approach:
React encourages a declarative programming style, where developers
describe what the UI should look like based on the current application
state, rather than imperatively manipulating the DOM to achieve desired
outcomes.
This approach simplifies UI development and makes code more
predictable and easier to understand.
5. Unidirectional Data Flow:
React follows a unidirectional data flow, also known as one-way data
binding.
Data flows down from parent components to child components via props
(properties), and child components can communicate with parent
components via callback functions.
This architecture helps maintain a clear and predictable data flow,
reducing the likelihood of bugs and making it easier to reason about the
application's state.
6. Rich Ecosystem:
React.js has a vibrant ecosystem with a vast collection of libraries, tools,
and extensions that complement its core functionality.
These include state management libraries like Redux and MobX, routing
libraries like React Router, and UI component libraries like Material-UI
and Ant Design, among others.
****************************************************************
React Eco-system?
The React ecosystem is vast and continuously evolving, comprising a rich
collection of libraries, tools, frameworks, and resources that complement and
extend the capabilities of React.js. Here's an overview of some key components
of the React ecosystem:
1. State Management Libraries:
Redux:
A predictable state container for managing application state. It enables
centralizing application state and facilitates predictable state mutations
through reducers.
MobX:
Another state management library that makes state management simple
and scalable by using observable data structures.
Recoil:
A state management library developed by Facebook that provides a
simple and efficient way to manage application state.
2. Routing Libraries:
React Router:
The most popular routing library for React applications. It provides
declarative routing capabilities, enabling navigation and handling of URL
changes in single-page applications.
3. UI Component Libraries:
Material-UI:
A set of React components that implement Google's Material Design. It
offers a wide range of pre-designed components for building modern,
visually appealing UIs.
Ant Design:
A comprehensive UI library that offers a variety of customizable
components, including forms, layouts, navigation, and data display
components.
Bootstrap:
Although primarily associated with jQuery, Bootstrap also has a React
version that provides a collection of responsive and customizable UI
components.
Gatsby:
A static site generator for React that enables building blazing-fast
websites and applications. It leverages GraphQL for data fetching and
provides a rich plugin ecosystem for extending functionality.
5. Development Tools:
Create React App (CRA):
A toolchain provided by Facebook for creating React applications with no
build configuration. It sets up the development environment, builds the
project, and optimizes production builds automatically.
React Developer Tools:
Browser extensions (available for Chrome and Firefox) that allow
developers to inspect and debug React component hierarchies, inspect
state and props, and profile React applications for performance
optimization.
6. Testing Frameworks:
Jest:
A popular testing framework developed by Facebook for JavaScript
applications. It's commonly used for unit testing React components and
applications.
7. Styling Solutions:
Styled-components:
A library for styling React components with scoped and dynamic styles
using tagged template literals.
CSS Modules:
A CSS approach that allows scoping styles locally to individual
components by automatically generating unique class names.
GraphQL Integration:
Apollo Client: A comprehensive GraphQL client for React applications
that simplifies data fetching and management by providing features like
caching, optimistic UI, and real-time updates.
3. Boilerplate Code:
React applications often require boilerplate code for setting up build
configurations, managing dependencies, and handling routing.
While tools like Create React App can streamline project setup, managing
boilerplate code and configuration files can still be cumbersome,
especially for smaller projects.
5. SEO Challenges:
React applications rendered on the client-side may face challenges with
search engine optimization (SEO) due to the initial lack of content in the
HTML response.
While server-side rendering (SSR) can address this issue by generating
HTML content on the server, implementing SSR adds complexity to the
application and may impact performance.
6. Tooling Overhead:
While React itself is lightweight and focused on UI development,
building modern React applications often involves using a variety of tools
and libraries for tasks such as state management, routing, styling, and
testing.
Managing dependencies, keeping tooling up to date, and troubleshooting
compatibility issues can add overhead to the development process.
7. Performance Overhead:
While React's virtual DOM and efficient reconciliation algorithm
optimize rendering performance, excessive use of stateful components or
inefficient rendering patterns can still lead to performance bottlenecks,
especially in large or complex applications.
Careful optimization and performance monitoring may be required to
ensure smooth user experiences.
8. Community Fragmentation:
React's large ecosystem and community support can sometimes lead to
fragmentation, with multiple competing libraries and frameworks offering
similar functionalities.
Choosing the right tools and libraries for a project, managing
dependencies, and keeping up with the latest developments in the
ecosystem can be challenging.
Despite these disadvantages, React remains a popular choice for building
modern web applications due to its flexibility, performance, and vibrant
ecosystem. With careful planning, best practices, and ongoing learning,
developers can effectively mitigate these challenges and leverage React's
strengths to build powerful and responsive user interfaces.
****************************************************************
How to configure react application Manually?
Step 1:
o npm init
package-name: <project-name>
version: (1.0.0)
description: 'This is Demo project'
entry point: (App.js)
test command: jest
git repository:
keywords: react-demo
author: vineet tijare
license: (ISC)
About to write to E:\React Interview project\Namaste-React\react-
cdn\package.json:
{
"name": "react-cdn",
"version": "1.0.0",
"description": "'This is Demo project'",
"main": "App.js",
"scripts": {
"test": "jest"
},
"keywords": [
"react-demo"
],
"author": "vineet tijare",
"license": "ISC"
}
package.json
{
"devDependencies": {
"parcel": "^2.12.0"
}
}
****************************************************************
What is the importance of Script tag into package.json file?
It helps to configure application in such a way we can create our own
custom way how to run our application into dev, prod or other regions.
We can also configure our application into test environment.
"scripts": {
"start": "parcel index.html",
"build": "parcel build index.html",
"test": "jest"
},
****************************************************************
What is Babel?
Babel is a popular JavaScript compiler that allows developers to use next-
generation JavaScript features (ES6/ES7/ES8 and beyond), as well as
other syntax extensions like JSX (for React) and TypeScript (a typed
superset of JavaScript), while ensuring compatibility with older browsers
and environments that do not yet support these features.
Here are some key points about Babel:
1. JavaScript Compiler:
Babel is primarily known as a JavaScript compiler. It takes modern
JavaScript code as input, applies transformations, and produces
equivalent code that works in older environments.
2. Transpilation:
Babel transpiles modern JavaScript code (ES6+) to backward-compatible
versions (ES5 or earlier) that can run in older browsers or environments
that lack support for newer language features.
3. Support for Language Extensions:
In addition to compiling modern JavaScript syntax, Babel also supports
other language extensions like JSX and TypeScript.
This allows developers to use these syntax extensions in their projects
and have Babel transform them into standard JavaScript code.
4. Plugin-Based Architecture:
Babel's transformation capabilities are highly extensible and customizable
through plugins.
Plugins allow developers to enable specific transformations or even
create custom transformations tailored to their needs.
5. Integration with Build Tools:
Babel is commonly integrated into modern JavaScript build toolchains,
such as webpack, Rollup, and Parcel.
These build tools use Babel to process JavaScript files during the build
process, ensuring compatibility and optimization.
6. Developer Tooling:
Babel also provides a command-line interface (CLI) and APIs that allow
developers to use it directly in their development workflows.
It can be used to compile individual files or entire codebases, making it a
versatile tool for JavaScript development.
Overall, Babel plays a crucial role in the JavaScript ecosystem by enabling
developers to write modern, expressive code while ensuring compatibility and
broad support across different browsers and environments.
****************************************************************
What is Component in React?
In React, components are the building blocks of a user interface. They are
reusable, self-contained pieces of code that represent a part of the user
interface. Components can be thought of as custom HTML elements that
you can use in your application.
1. Functional Components:
Functional components are JavaScript functions that return JSX
(JavaScript XML) to describe what the UI should look like.
are typically used for presentational components, where the component's
only responsibility is to render UI based on the input data (props) passed
to it.
Example:
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
2. Class Components:
Class components are JavaScript classes that extend the
React.Component class. They have a render() method that returns JSX to
describe the UI.
Class components are used when you need to manage state or use
lifecycle methods.
Example:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.setState({ count: this.state.count +
1 })}>
Increment
</button>
</div>
);
}
}
In addition to these basic types, there are also other types of components
in React:
Pure Components:
Pure components are similar to functional components but come with
performance optimizations.
They automatically perform a shallow comparison of props and state to
determine if the component should re-render.
Higher-Order Components (HOCs):
HOCs are functions that take a component as input and return a new
enhanced component with additional functionality.
They are often used for code reuse, logic abstraction, and cross-cutting
concerns like authentication and authorization.
Render Props Components:
Render props components are components that accept a function as a
child. They provide data or behavior to their children using a render prop,
which is a function passed as a prop.
Components can be composed together to build complex user interfaces. They
can also accept input data (props) and manage their own internal state. In React,
the component-based architecture promotes reusability, modularity, and
maintainability of code.
********************************************************
Stateless Functional Component vs Stateful Class Component?
Stateless Components
Stateless components, also known as functional components, do not manage or
hold state internally. They are purely presentational and rely solely on props to
render their output.
Characteristics
Pure functions:
These components are essentially JavaScript functions that take props as
input and return React elements.
No state management:
They do not have this.state or lifecycle methods like
componentDidMount.
Simpler to write and test:
Because they do not have internal state or lifecycle methods, they are
easier to reason about and test.
Example
const Greeting = (props) => {
return <h1>Hello, {props.name}!</h1>;
};
Stateful Components
Stateful components, also known as class components or components with
hooks, manage their own internal state. They can also leverage lifecycle
methods to perform side effects.
Characteristics
State management:
They have this.state and can use methods like setState to update the state.
Lifecycle methods:
They can use lifecycle methods such as componentDidMount,
componentDidUpdate, and componentWillUnmount to handle side
effects.
More complex:
Because they manage state and side effects, they can be more complex to
write and test.
Example (Class Component)
class Greeting extends React.Component {
constructor(props) {
super(props);
this.state = { name: props.name };
}
render() {
return <h1>Hello, {this.state.name}!</h1>;
}
}
Example (Functional Component with Hooks)
import React, { useState, useEffect } from 'react';
const Greeting = (props) => {
const [name, setName] = useState(props.name);
useEffect(() => {
// Similar to componentDidMount and componentDidUpdate
}, [name]);
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
ref={nameRef}
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
ref={emailRef}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default UncontrolledForm;
Summary of Differences
1. constructor()
2. componentDidMount()
3. render
constructor()
The constructor is called before the component is mounted. It is used to
initialize state and bind methods.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
// Example method binding
this.handleClick = this.handleClick.bind(this);
}
componentDidMount()
The componentDidMount method is called immediately after the
component is mounted. It is commonly used for initializing data through
API calls.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
// Fetch data from an API
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => this.setState({ data }));
}
render() {
return <div>{this.state.data ? this.state.data : 'Loading...'}</div>;
}
}
Updating
Updating occurs when a component is being re-rendered due to changes
in props or state.
1. componentDidUpdate(prevProps, prevState, snapshot)
2. shouldComponentUpdate(nextProps, nextState)
3. getSnapshotBeforeUpdate(prevProps, prevState)
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
shouldComponentUpdate(nextProps, nextState)
The shouldComponentUpdate method is invoked before rendering when
new props or state are being received. This method can return false to
prevent rendering.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
shouldComponentUpdate(nextProps, nextState) {
// Only update if count is even
return nextState.count % 2 === 0;
}
increment = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
getSnapshotBeforeUpdate(prevProps, prevState)
The getSnapshotBeforeUpdate method is invoked right before the most
recently rendered output is committed to the DOM. It returns a value to
be passed to componentDidUpdate.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
list: []
};
}
getSnapshotBeforeUpdate(prevProps, prevState) {
// Capture the current scroll position
if (prevState.list.length < this.state.list.length) {
return this.listRef.scrollHeight;
}
return null;
}
addItem = () => {
this.setState(state => ({
list: [...state.list, 'New Item']
}));
};
render() {
return (
<div>
<ul ref={(ref) => (this.listRef = ref)}>
{this.state.list.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
<button onClick={this.addItem}>Add Item</button>
</div>
);
}
}
Unmounting
Unmounting occurs when a component is being removed from the DOM.
1. componentWillUnmount()
componentWillUnmount()
The componentWillUnmount method is invoked immediately before a
component is unmounted and destroyed. It is used to clean up resources
such as timers or network requests.
class MyComponent extends React.Component {
componentDidMount() {
// Set up a timer
this.timerID = setInterval(() => {
console.log('Timer running');
}, 1000);
}
componentWillUnmount() {
// Clear the timer
clearInterval(this.timerID);
}
render() {
return <div>Timer is running. Check the console.</div>;
}
}
Summary
Mounting: constructor, componentDidMount
Updating: componentDidUpdate, shouldComponentUpdate,
getSnapshotBeforeUpdate
Unmounting: componentWillUnmount
By using these lifecycle methods, you can manage the behavior of your React
components more effectively, ensuring they perform optimally and handle
various scenarios appropriately.
****************************************************************
Fragments in React?
Fragments is used to group list of children without adding Extra node tp
DOM
Syntax:
1. <>
<h1>Hello World!</h1>
</>
2. <React.Fragment>
<h1>Hello World!</h1>
</React.Fragment>
3. <Fragment>
<h1>Hello World!</h1>
</Fragment>
****************************************************************
React Hooks
Rules of Hooks: -
Rule 1: -
Only call hooks at Top level.
Don’t call hooks inside loops, conditions or nested functions.
Rule 2: -
Only call hooks from react functions.
Call them from within react functional components and not just any
regular javascript function
****************************************************************
Summary:
The use state hook lets you use state to functional components.
In classes, the state is always an object.
With the useState hook, the state doesn’t have to be an object.
The useState hook returns an array with 2 elements.
The first element is the current value of the state and the second element
is a state setter function.
New state value depends on the previous state value? You can pass a
function to the setter function.
When dealing with objects or arrays, always make sure to spread your
state variable and then call the setter function.
****************************************************************
useEffect in react?
Understanding useEffect in React
useEffect is a hook in React that allows you to perform side effects in your
functional components. Side effects can include things like data fetching,
subscriptions, or manually changing the DOM, which are operations that are
outside the typical data flow and render process.
Basic Usage
The useEffect hook takes two arguments:
A function:
This function contains the side effect logic.
A dependency array (optional):
This array lets you specify when the effect should run.
If you omit the array, the effect runs after every render.
If you pass an empty array, it runs only once after the initial render.
If you pass a non-empty array, it runs whenever any of the array's
elements change.
import React, { useState, useEffect } from 'react';
function ExampleComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // Only re-run the effect if count changes
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default ExampleComponent;
Function Component:
ExampleComponent is a functional component that uses the useState and
useEffect hooks.
State Management:
const [count, setCount] = useState(0); initializes a state variable count
with an initial value of 0.
useEffect Hook:
useEffect(() => { document.title = You clicked ${count} times; },
[count]); sets the document title to the current count value.
The effect runs after every render where count has changed because count
is included in the dependency array.
Common Patterns with useEffect
Running an Effect Only Once (on Mount):
To run an effect only once after the initial render, pass an empty array []
as the second argument.
useEffect(() => {
console.log('Component mounted');
}, []);
Cleaning Up an Effect:
Sometimes you need to clean up after an effect, like when you set up a
subscription or timer. You can return a cleanup function from the effect
function.
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
****************************************************************
Redux
Redux is a predictable state container for javascript app.
It is for javascript.
It is state container
It is predictable.
React +Redux
Why we want to use redux in a react application?
Using Redux in a React application provides several benefits, especially for
managing complex state across large applications. Here are some of the primary
reasons why you might want to use Redux:
1. Centralized State Management
Redux provides a single source of truth for the state of your application.
By storing the state in a single object, it becomes easier to:
Manage and debug state changes.
Track changes over time (time-travel debugging).
2. Predictable State Changes
Redux enforces strict unidirectional data flow. Actions describe changes,
and pure reducer functions specify how the state updates in response to
actions. This makes the behavior of your application more predictable
and easier to understand.