Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

Why React?

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

4. Server-Side Rendering (SSR) Frameworks:


 Next.js:
A popular React framework for building server-side rendered (SSR) and
statically generated React applications. It simplifies SSR setup and offers
features like automatic code splitting, prefetching, and API routes.

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

 React Testing Library: A testing utility for React that encourages


writing tests that focus on user behavior rather than implementation
details. It provides utilities for interacting with and querying React
components in a way that simulates user actions.

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.

8. Internationalization (i18n) Libraries:


 react-i18next: A popular internationalization library for React
applications that provides multi-language support with easy integration
and customization options.
****************************************************************
Advantages of React?
React offers several advantages that have contributed to its widespread adoption
and popularity among developers. Here are some key advantages of using
React:
Component-Based Architecture:
React is built around the concept of reusable components. Components are self-
contained units that encapsulate UI elements and logic, making it easier to
develop and maintain complex user interfaces. Component-based architecture
promotes code reusability, modularity, and scalability, leading to more efficient
development workflows.
Virtual DOM:
React utilizes a virtual DOM (Document Object Model) to efficiently manage
and update the UI. 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 minimal set of updates needed and applies
them to the actual DOM, resulting in faster rendering performance and
improved user experience.
JSX Syntax:
React introduces JSX (JavaScript XML), a syntax extension that allows
developers to write HTML-like code directly within JavaScript. JSX makes it
easier to describe UI components' structure and behavior, leading to more
expressive and maintainable code. Additionally, JSX is compiled to standard
JavaScript, ensuring cross-browser compatibility and performance optimization.
Declarative Programming Model:
React promotes a declarative approach to building UIs, 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 declarative programming model leads to more predictable and easier-to-
understand code, reducing the likelihood of bugs and improving developer
productivity.
One-Way Data Binding:
React follows a unidirectional data flow, also known as one-way data binding.
Data flows from parent components to child components via props (properties),
and child components can communicate with parent components via callback
functions. This architecture simplifies data management and helps maintain a
clear and predictable data flow, making it easier to reason about the
application's state.
Rich Ecosystem and Community Support:
React has a vibrant ecosystem with a vast collection of libraries, tools, and
resources that complement its core functionality. Additionally, React has a large
and active community of developers who contribute to its ongoing
development, provide support, and share knowledge through forums,
documentation, and tutorials.
Performance Optimization:
React's virtual DOM and efficient reconciliation algorithm enable high-
performance rendering, even for complex and dynamic UIs. React minimizes
DOM manipulations and optimizes rendering updates, resulting in faster load
times and smoother user interactions. Additionally, React's built-in tools and
best practices help developers identify and address performance bottlenecks
effectively.
Cross-Platform Compatibility:
React can be used to build applications for various platforms, including web,
mobile, and desktop, using frameworks like React Native and Electron. This
cross-platform compatibility allows developers to leverage their React skills and
codebase to target multiple platforms, reducing development time and effort.
Overall, React's combination of component-based architecture, virtual DOM,
JSX syntax, declarative programming model, one-way data binding, rich
ecosystem, performance optimization, and cross-platform compatibility makes
it a powerful and versatile library for building modern and responsive user
interfaces.
****************************************************************
Disadvantages of react?
While React offers numerous advantages, it also has some limitations and
challenges that developers may encounter. Here are some disadvantages of
using React:
1. Learning Curve:
 React has a relatively steep learning curve, especially for developers who
are new to JavaScript frameworks or the concepts of virtual DOM and
JSX syntax.
 Understanding React's component-based architecture, state management,
and data flow patterns may require time and effort, particularly for
beginners.
2. Complexity of State Management:
 While React provides tools for managing component state, handling
complex state management scenarios in larger applications can become
challenging.
 Developers may need to rely on additional libraries like Redux or MobX
to manage application state effectively, adding complexity to the project.

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.

4. Integration with Other Technologies:


 Integrating React with other technologies and libraries, such as server-
side rendering (SSR), routing, and data fetching, may require additional
setup and configuration.
 Ensuring compatibility and smooth integration with third-party tools and
frameworks can be challenging, particularly in complex or legacy
systems.

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

Is this OK? (yes) y


 After this it will create a package.json file for us , which includes the
configuration about our project.
 package.json is configuration for npm.
{
"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",
}
****************************************************************
What is bundler?
 When we create an application the hole code needs to be bundled
together, hole code needs to be cached, hole code needs to be minified,
hole code needs to be compressed, hole code needs to be cleaned before it
sent to production, this things will be managed by bundler.
 There are number of bundlers in market, few of them are..
1. Web Pack
2. Vite
3. Parcel
****************************************************************
How to configure Parcel into our React project?
 npm install -D parcel

package.json
{

"devDependencies": {
"parcel": "^2.12.0"
}
}

^ - Upgrade minor version


~ - Upgrade major version
****************************************************************
How to start or configure application using Parcel?
 Npx parcel index.html
 With the help of this command we can able to host application on below
URL
 http://localhost:1234
****************************************************************
Installing React and React-DOM into our project?
 Npm install react
 Npm install react-dom
"devDependencies": {
"parcel": "^2.12.0"
},
"dependencies": {
"react": "^18.3.1",
"react-dom": "^18.3.1"
}

****************************************************************
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"
},

How to run application in different environment after this is


 Dev Environment
o Npm run start
 Prod Environment
o Npm run build
****************************************************************
What is JSX?
 JSX is html like syntax. It is not html in javascript.
 JSX (JavaScript XML) is a syntax extension for JavaScript that allows
you to write HTML-like code within your JavaScript files.
 It provides a more readable and convenient way to create and compose UI
components in React applications.
 Here are some key points to understand about JSX:

1. HTML-Like Syntax: JSX resembles HTML syntax, allowing you to


write familiar tags like <div>, <p>, <h1>, etc., directly in your JavaScript
code.
2. Embedding JavaScript Expressions: JSX allows you to embed
JavaScript expressions inside curly braces {}. This allows you to
dynamically generate content and attributes based on JavaScript
variables, functions, or expressions.
Example:
const name = 'John';
const greeting = <h1>Hello, {name}!</h1>;
3. Components: In JSX, you can also define custom components using
uppercase names. These components can be used like HTML tags.
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
const App = () => {
return <Greeting name="John" />;
};
4. Self-Closing Tags: Similar to HTML, JSX supports self-closing tags for
elements that do not have any children. These tags end with a slash /
before the closing angle bracket >.
Example:
const App = () => {
return <img src="logo.png" alt="Logo" />;
};
5. Attributes and Event Handlers:
JSX supports standard HTML attributes and event handlers. Event
handlers are specified using camelCase naming convention.
Example:
const handleClick = () => {
console.log('Button clicked!');
};
const App = () => {
return (
<button onClick={handleClick} className="btn">
Click Me
</button>
);
};
6. Fragments:
JSX allows you to return multiple elements by wrapping them in a
fragment, which is an empty tag <>...</> or
<React.Fragment>...</React.Fragment>.
Example:
const App = () => {
return (
<>
<h1>Hello</h1>
<p>Welcome to JSX</p>
</>
);
};
Overall, JSX simplifies the process of writing and maintaining UI code in React
applications by providing a more declarative and expressive syntax for defining
UI components.

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

 There are two main types of components in React:

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 <h1>Hello, {name}!</h1>;


};
Choosing Between Stateless and Stateful Components
When to Use Stateless Components
Pure presentation:
 When the component only needs to render UI based on props.
Reusability:
 Stateless components are more reusable because they do not depend on
internal state.
Performance:
 They are typically faster because they do not manage state or lifecycle
methods.
When to Use Stateful Components
Managing state:
 When you need to manage internal state and respond to user interactions
or other events.
Side effects:
 When you need to perform side effects such as fetching data,
subscriptions, or timers.
Complex UI logic:
 When the component needs to manage more complex UI interactions and
logic.
Summary
Stateless components are simpler, easier to test, and ideal for presentational
purposes.
Stateful components are more powerful and suitable for managing state and side
effects but can be more complex to handle.
****************************************************************
Functional Component vs Class Component?
Functional Component:
 Simple Functions
 Use Functional Component as much as possible.
 Absence of ‘this’ keyword.
 Solution without using state
 Mainly responsible for the UI.
 Stateless/ Dumb/ Presentational Component.
Class Component:
 More Feature rich.
 Maintain their own private data – state
 Complex UI logic
 Provide lifecycle methods(hooks)
 Stateful / Smart / Container
****************************************************************
What is Props?
 In React, "props" (short for properties) are a mechanism for passing data
from one component to another.
 Props are arguments passed into React components.
 They are used to customize and configure components, making them
more reusable and composable.
 Props are read-only, meaning that a component receiving props cannot
modify them directly.
How to Use Props
Passing Props to a Component
Props are passed to a component as attributes in the JSX syntax.
<Greeting name="John" age={30} />
Accessing Props in a Functional Component
In a functional component, props are accessed via the function's arguments.
const Greeting = (props) => {
return <h1>Hello, {props.name}! You are {props.age} years old.</h1>;
};
Accessing Props in a Class Component
In a class component, props are accessed via this.props.
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}! You are {this.props.age} years
old.</h1>;
}
}
Advantages of Using Props
Reusability
 Props allow components to be reused with different data, making your UI
more flexible and maintainable.
 For example, a Button component can be reused with different labels and
actions.
<Button label="Submit" onClick={handleSubmit} />
<Button label="Cancel" onClick={handleCancel} />
Separation of Concerns
 By passing data and behavior into components via props, you can
separate the logic of how data is managed and how it is displayed. This
leads to cleaner, more organized code.
Declarative Nature
 Props align with React’s declarative nature, allowing you to define what
the UI should look like for any given state without worrying about how to
achieve it.
Component Composition
 Props enable the composition of components, where a parent component
can combine multiple child components and pass necessary data to them.
This makes the UI modular and easier to manage.
const App = () => {
return (
<div>
<Header title="Welcome to My App" />
<Content text="This is some content." />
<Footer year={2024} />
</div>
);
};
Summary
 Props are used to pass data and event handlers from parent to child
components.
 They are read-only and help in making components reusable and
composable.
 Props promote the separation of concerns and support React’s declarative
approach.
 They enable component composition, allowing complex UIs to be built
from simpler, reusable components.
****************************************************************
Controlled Component vs Uncontrolled Component?
In React, forms can be handled in two main ways: controlled components and
uncontrolled components. Each approach has its use cases, advantages, and
implementation methods.
Controlled Components
 In a controlled component, form data is handled by the React component
state.
 The component state is the single source of truth for the input values.
 This approach makes it easier to handle form validation and other side
effects of user input.
Advantages of Controlled Components
 Easier to implement form validation.
 Simple to manipulate form data.
 Better control over the form's state and behavior.
Implementation of Controlled Components
Here's an example of how to implement a controlled component:
import React, { useState } from 'react';
const ControlledForm = () => {
const [formData, setFormData] = useState({ name: '', email: '' });
const handleChange = (e) => {
const { name, value } = e.target;
setFormData({ ...formData, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log('Form data:', formData);
};
return (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="name">Name:</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleChange}
/>
</div>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleChange}
/>
</div>
<button type="submit">Submit</button>
</form>
);
};
export default ControlledForm;
Uncontrolled Components
 In an uncontrolled component, form data is handled by the DOM itself.
Input values are accessed using refs. This approach is more similar to
traditional HTML form handling.
Advantages of Uncontrolled Components
 Simpler to set up initially.
 Useful for integrating with non-React code.
 Sometimes less boilerplate code.
Implementation of Uncontrolled Components
Here's an example of how to implement an uncontrolled component:
import React, { useRef } from 'react';
const UncontrolledForm = () => {
const nameRef = useRef();
const emailRef = useRef();
const handleSubmit = (e) => {
e.preventDefault();
const formData = {
name: nameRef.current.value,
email: emailRef.current.value,
};
console.log('Form data:', formData);
};

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

Feature Controlled Component Uncontrolled Component

State State is managed by React State is managed by the DOM


Management component
Data Access Accessed via component Accessed via refs
state
Validation Easier to implement More complex validation
validation
Integration Best for React-specific use Useful for integrating with non-
cases React code
Setup Complexity More initial setup Less initial setup
Re-rendering Re-renders on every change Does not re-render on every
change

When to Use Which Approach


Controlled Components: Use when you need more control over form data, for
form validation, or when you need to react to user input in real-time.
Uncontrolled Components: Use for simple forms or when integrating with
non-React code where form data needs to be accessed directly from the DOM.
By understanding and utilizing both controlled and uncontrolled components,
you can effectively handle a wide range of form-handling scenarios in your
React applications.
****************************************************************
LifeCycle Methods in React class Component?
 React class components have several lifecycle methods that allow you to
run code at specific points in the component's life cycle. These lifecycle
methods can be categorized into three phases:
 Mounting
 Updating
 Unmounting
 Error Handling
Here is a summary of each lifecycle method along with examples:
Mounting
 Mounting is the phase when a component is being created and inserted
into the DOM.

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)

componentDidUpdate(prevProps, prevState, snapshot)


 The componentDidUpdate method is invoked immediately after updating
occurs. This method is not called for the initial render. It can be used to
operate on the DOM when the component has been updated.
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
componentDidUpdate(prevProps, prevState) {
if (prevState.count !== this.state.count) {
console.log('Count updated:', this.state.count);
}
}

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

componentDidUpdate(prevProps, prevState, snapshot) {


if (snapshot !== null) {
this.listRef.scrollTop = this.listRef.scrollHeight - snapshot;
}
}

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

What are Hooks?


 Hooks are a new features addition in React version 16.8 which allow you
to use React features without having to write class.
 Ex. State of component
 Hooks don’t work inside classes.
****************************************************************
Why Hooks?
Reason 1:
 Understand how this keyword words in JS.
 Remember to bind event handlers in class components.
 Classes don’t minify very well and make hot reloading very unreliable.
Reason 2:
 There is no particular way to reuse stateful component logic.
 HOC and render props patterns do address this problem.
 Makes the code harder to follow.
 There is need to share stateful logic in a better way.
Reason 3:
 Create components for complex scenarios such as data fetching and
subscribing to events.
 Related code is not organized in one place.
 Ex. Data fetching - In componentDidMount and ComponentDidUpdate
 EventListener – In componentDidMount and subscribes in
componentWillUnmount
 Because of stateful logic- cannot break components into smaller ones.
Note:
 React version 16.8 or higher(Hooks introduced)
 Completely opt In.
 Hooks don’t contain any breaking changes and the release is 100%
backward compatible.
 Class won’t be removed from React.
 Can’t use hooks inside a class component
 Hooks don’t replace your existing knowledge of react concepts.
 Instead, Hooks provide more direct API to the React concepts you
already know such as props, refs, lifecycle, state
Summary:
 Hooks are new features addition in React version16.8
 They allow you to use React features without having to write class.
 Avoid the whole confusion with ‘this’ keyword.
 Allow you to reuse stateful logic.
 Organize the logic inside a component into reusable isolated units.
****************************************************************
useState Hook
Syntax:
const [state, setState] = useState(initialState)
 State: - current value of state property
 setState:- method that update that state property
 initialState:- previous state

 useState accepts an arguments which is initial value of a state property


returns current value property and method that updates that state property.
const [state, setState]  called array destructuring.

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

return () => clearInterval(timer); // Cleanup function


}, []); // Empty array ensures this runs only once
Effect with Dependencies:
 The effect runs whenever any value in the dependency array changes.
useEffect(() => {
console.log('Count has changed:', count);
}, [count]);
Example: Fetching Data with useEffect
Here's an example of using useEffect to fetch data from an API:
import React, { useState, useEffect } from 'react';
function DataFetchingComponent() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch('https://api.example.com/data');
const result = await response.json();
setData(result);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
};
fetchData();
}, []); // Empty array ensures this runs only once
if (loading) {
return <p>Loading...</p>;
}
return (
<div>
<h1>Fetched Data</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default DataFetchingComponent;
Explanation of the Data Fetching Example
State Management:
data: Stores the fetched data.
loading: Indicates whether the data is currently being loaded.
useEffect Hook:
The effect function is an async function that fetches data from an API and
updates the state.
The empty dependency array [] ensures the effect runs only once after the initial
render.
Rendering:
If loading is true, a loading message is displayed.
Once the data is fetched, it is displayed in a list.
Conclusion
The useEffect hook is a powerful and flexible way to handle side effects in
React functional components. By understanding its basic usage and common
patterns, you can effectively manage component lifecycles and side effects in
your React applications.

****************************************************************
Redux
Redux is a predictable state container for javascript app.
 It is for javascript.
 It is state container
 It is predictable.

Redux is for javascript Applications.


 Redux is not tied to React.
 It can be used with React, Angular, Vue or even vanilla Javascript.
 Redux is a library used for Javascript application.
Redux is a State Container
 Redux stores a state of your application.
 Consider a react app - state of a component.
 State of an application is the state represented by all the individual
components of that app.
Ex:
UserListComponent{
state={
user:[]
}
}
LoginFormComponent
state={
username:’’,
password:’’,
submitting:’’
}
Application
state ={
isUserLoggedIn:true,
username: ‘vk’,
profileUrl: ‘’,
onlineUsers:[],
isModalOpened: false
}
 Redux will store and manage the application state.
Redux is Predictable:
Predictable in what way?
 Redux is a state container.
 The state of the application can change.
Ex: todo list application
item (pending) => item(completed)
 In redux, all state transitions are explicit and it is possible to keep track of
them.
 The change to your applications state become predictable.
 To manage the state of your application in a predictable way, redux can
help you.
****************************************************************

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.

3. Improved Debugging and Testing


 With Redux DevTools, you can inspect every action that modifies the
state, see the state changes, and even "time travel" by reverting or
replaying actions. This enhances the ability to debug and understand the
application flow.
 Actions and reducers can be tested in isolation, which simplifies unit
testing.
4. Separation of Concerns
 Redux encourages a clear separation between state management and UI.
 This separation makes your codebase more modular and maintainable:
 Components focus on rendering UI.
 Redux handles the state and business logic.
5. Middleware for Asynchronous Logic
 Redux middleware like redux-thunk or redux-saga allows you to
handle asynchronous operations (such as API calls) in a predictable way.
 Middleware can intercept actions and dispatch other actions, making it
easier to handle side effects.
6. Ease of Sharing State
 Redux makes it easier to share state between deeply nested components
or across different parts of your application without "prop drilling":
 Any component can access the global state directly if it is
connected to the Redux store.
7. Consistency Across Different Platforms
 For applications that have multiple platforms (web, mobile, desktop),
using Redux ensures that state management logic is consistent across all
platforms. This is particularly useful when using libraries like React
Native.
 Example Use Case
 Consider a complex e-commerce application with the following features:
 User authentication
 Shopping cart management
 Product listings and filtering
 Order history
 User reviews and ratings
 Without Redux, managing the state for such a complex application would
involve passing down props through many levels of components and
handling state updates in various places. This can lead to tangled,
difficult-to-maintain code.
 With Redux, the state for user authentication, shopping cart, products,
orders, and reviews can be managed centrally. Actions can describe
events like logging in, adding to the cart, or posting a review. Reducers
update the state based on these actions, and any component can access the
state it needs without prop drilling.
Conclusion
 While Redux adds some boilerplate code and requires a learning curve,
its benefits in managing complex state make it a valuable tool for large-
scale React applications. For simpler applications, the built-in state
management of React (using useState and useContext) might be
sufficient. However, as an application grows in complexity, Redux can
help manage that complexity in a predictable and maintainable way.
****************************************************************
What is Redux?
 Redux is a 3rd party library to manage global state.
 Standalone library, but easy to integrate with React apps using react-
redux library.
 All global state is stored in one globally accessible store, which is easy to
update using ‘actions’ (like useReducer)
 It’s conceptually similar to using the Context API+ useReducer
 There are two ‘versions’ :
 Classic Redux
 Modern Redux Toolkit
****************************************************************
Do you need to Learn Redux?
 Historically, Redux was used in most React apps for all global state.
Today, That has changed, because there are many alternatives. Many
apps don’t need Redux anymore, unless they need a lot of global UI state.
 Ideal use case for Redux , when there is lots of state that updates
frequently.
****************************************************************
Local State Global State
UI  useState  ContextAPI+useState/
State  useReducer useReducer
 useRef  Redux, Zustand, recoil,etc.
 React Router
Remo  fetch+useEffect+useState+useR  ContextApi+useState/
te educer useReducer
State  Redux, Zustand, Recoil,
etc.
 SWR
 React Query
 RTK Query

You might also like