0% found this document useful (0 votes)
21 views22 pages

Introduction to React: Key Concepts

React is an open-source JavaScript library for building user interfaces, maintained by Meta and a community of developers. It simplifies the creation of dynamic UIs through a component-based architecture and is particularly useful for developing single-page applications. Key features include the Virtual DOM for performance optimization, JSX for intuitive UI code, and a strong community ecosystem.

Uploaded by

Aaditiya Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views22 pages

Introduction to React: Key Concepts

React is an open-source JavaScript library for building user interfaces, maintained by Meta and a community of developers. It simplifies the creation of dynamic UIs through a component-based architecture and is particularly useful for developing single-page applications. Key features include the Virtual DOM for performance optimization, JSX for intuitive UI code, and a strong community ecosystem.

Uploaded by

Aaditiya Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

What is React?

React is an open-source JavaScript library used for building user interfaces (UIs) or single-page
applications. It is maintained by Meta and a community of developers.

• Role in Software Development: React simpli es the creation of dynamic, interactive UIs
by breaking them down into reusable components. It uses a component-based architecture to
build complex UIs from smaller, isolated pieces.

• Why is React needed? While HTML, CSS, and JavaScript are suf cient for basic websites,
React simpli es the creation of complex, single-page applications (SPAs) by using reusable
components.

• Diagram: The video explains a simpli ed front-end architecture. A user request goes to the
UI server (client/front-end), which has static HTML content. For dynamic content (e.g.,
products), the UI server sends a request to the API server (middleware). The API server
processes the business logic and fetches data from the database. The database sends the data
back to the API server, which then sends a response to the UI server. Finally, the UI server
displays the data on the user's browser. React is used on the UI server to build the dynamic
UI.

Key Features of React

Here are the seven key features of React:

1. Virtual DOM (Document Object Model): A lightweight copy of the real DOM. React uses
it to improve performance by only updating the parts of the real DOM that have changed.

2. Component-Based Architecture: UIs are broken down into small, reusable, and
independent components. This makes the code easier to manage, maintain, and reuse.

3. Reusability and Composition: Components can be reused in different parts of the


application or even in different projects. Smaller components can be composed to build
larger, more complex ones.

4. JSX (JavaScript XML): A syntax extension for JavaScript that looks similar to HTML. It
allows you to write UI code within your JavaScript, making it more intuitive.

5. Declarative Syntax: You describe what the UI should look like for a given state, and React
handles the updates ef ciently.

6. Strong Community and Ecosystem: React has a large and active community, which means
extensive documentation, libraries, and tools are available.
fi
fi
fi
fi
fi
7. React Hooks: Functions that let you "hook into" React state and lifecycle features from
functional components.

DOM and Virtual DOM

What is the DOM?

The DOM (Document Object Model) is a programming interface for HTML and XML documents.
It represents a web page as a tree-like structure of nodes and objects, allowing JavaScript to
dynamically access and manipulate the content and structure of the page.

• Difference between HTML and DOM: HTML is a markup language for developers to read
and write, while the DOM is a tree-like representation of that HTML in memory that the
browser uses to render the page. The browser only works with the DOM, not the HTML le
directly.

What is the Virtual DOM?

The Virtual DOM (VDOM) is a lightweight, in-memory representation of the real DOM. It is a
concept speci c to React, designed to improve the performance of web applications.

• How it works: When the state of a component changes, React rst updates the VDOM. It
then compares the VDOM to the real DOM (a process called reconciliation) to identify the
differences. Finally, it updates only the speci c parts of the real DOM that have changed,
rather than re-rendering the entire page. This selective updating is much faster and more
ef cient than re-rendering the entire page, which is what happens with the real DOM.

• Difference between DOM and VDOM:

◦ DOM: A real, browser-speci c concept that represents the entire web page.

◦ VDOM: A lightweight, React-speci c concept that is an exact copy of the real


DOM.

◦ Updates: Any change to the real DOM causes a full re-render of the page, which is
slow. Updates to the VDOM are much faster because only the changed parts are
updated in the real DOM.
fi
fi
fi
fi
fi
fi
fi
◦ Implementation: The DOM is a real part of the browser's functionality. The VDOM
is an implementation detail of React.

◦ Rendering: The DOM is responsible for the actual rendering of the page. The
VDOM exists to improve the ef ciency of those updates.

Components
What are React Components?

A React component is a reusable building block for creating user interfaces. A complex UI is built
by combining many smaller components.

• Main Elements: A typical component structure includes:

◦ Importing the React library.

◦ De ning a JavaScript function or class that returns JSX.

◦ Exporting the component to be used in other les.

• Code Example:
JavaScript

import React from 'react';


• function MyComponent() {
• return (
• <div>
• <h1>Hello, World!</h1>
• <p>This is my first component.</p>
• </div>
• );
• }

• export default MyComponent;

What are the types of React Components?


fi
fi
fi
There are two main types of components in React:

1. Functional Components: De ned as simple JavaScript functions that return JSX. They
were originally "stateless" but can now manage state and lifecycle features using React
Hooks. They are generally considered simpler and more readable.

2. Class Components: De ned as ES6 classes that extend [Link]. They can
manage their own local state and have access to lifecycle methods. They are more verbose
and are less commonly used in new React applications since the introduction of Hooks.

• Code Example (Functional):


JavaScript

import React from 'react';


• const MyFunctionComponent = (props) => {
• return (
• <div>
• <h1>Hello, {[Link]}!</h1>
• </div>
• );
• };

• export default MyFunctionComponent;

• Code Example (Class):


JavaScript

import React from 'react';


• class MyClassComponent extends [Link] {
• render() {
• return (
• <div>
• <h1>Hello, {[Link]}!</h1>
• </div>
• );
• }
• }

• export default MyClassComponent;
fi
fi

What is a Single Page Application (SPA)?

A Single Page Application is a web application that loads a single HTML page and dynamically
updates the content as the user interacts with it, without requiring a full page reload.

• How it works: When a user navigates through an SPA, the browser only fetches and renders
the new content, leaving the common elements (like headers and footers) untouched. This
provides a faster, more seamless user experience.

Advantages and Disadvantages of React

What are the ve advantages of React?

1. Simpli es Single Page Application (SPA) Development: React's component-based


architecture makes it easy to build complex UIs from reusable, manageable components.

2. Cross-Platform and Open-Source: React is free to use and can be used for web
development as well as mobile development (with React Native).

3. Lightweight and Fast: React's use of the Virtual DOM makes updates ef cient, resulting in
a faster and more performant user experience.

4. Large Community and Ecosystem: A vast number of resources, tools, and third-party
libraries are available, making it easy to nd solutions and support.

5. Easy to Test: React provides tools and features that make it easy to write unit tests for UI
components.

What are the disadvantages of React?


fi
fi
fi
fi
• React is not a good choice for very small, static websites. For a simple page with static
content, using plain HTML, CSS, and JavaScript is often more ef cient. Using React would
add unnecessary complexity and a learning curve for a simple project.

JSX

What is JSX?

JSX (JavaScript XML) is a syntax extension for JavaScript used with React to describe what the
UI should look like. It allows developers to write HTML-like code directly within their JavaScript.

• Role in React:

1. Improves Code Readability: JSX is simpler to read and write than creating
elements using [Link]().

2. Transpiled by Babel: The browser cannot directly understand JSX. A tool like
Babel transpilers JSX into regular JavaScript code that the browser can interpret.

3. JavaScript Expressions: JSX allows you to embed JavaScript expressions inside


curly braces {}.

What are the advantages of JSX?

1. Improves Code Readability and Writability: Writing UI code that looks like HTML is
more intuitive and easier to read.

2. Advanced Error Checking: JSX provides compile-time error checking, which helps catch
syntax errors early.

3. Supports JavaScript Expressions: You can easily embed dynamic values and logic within
your UI code using curly braces.

4. Improved Performance: JSX allows React to perform optimizations during the


compilation process, leading to better performance.

5. Code Reusability: JSX is used within components, which are designed to be reusable.
fi
What is the role of Babel?

Babel is a JavaScript transpiler that converts JSX syntax into regular JavaScript that browsers can
understand. It also converts newer ECMAScript features (like ES6, ES7) into backward-compatible
JavaScript versions.

• Diagram: A diagram shows that JSX code (e.g., <h1>Hello</h1>) is passed through
Babel, which transpiles it into [Link]('h1', null,
'Hello'), which the browser can then execute.

Conditional Rendering

What are the types of conditional rendering in JSX?

Conditional rendering allows you to render different elements or components based on certain
conditions. The four types are:

1. If-Else Statement: A traditional JavaScript conditional statement. This is useful for


rendering different components or blocks of code based on a condition.

◦ Example:
JavaScript

if (isLoggedIn) {

◦ return <WelcomeMessage />;


◦ } else {
◦ return <LoginButton />;
◦ }

2. Ternary Operator: A concise, single-line conditional operator. It's great for simple
conditions.

◦ Example:
JavaScript
return isLoggedIn ? <WelcomeMessage /> :
<LoginButton />;

3. Logical && Operator: Used to conditionally render an element or component if a condition


is true. If the condition is false, nothing is rendered.

◦ Example:
JavaScript

return isLoggedIn && <WelcomeMessage />;

4. Switch Statement: Useful when you have multiple conditions to check.

◦ Example:
JavaScript

switch (page) {

◦ case 'home':
◦ return <HomePage />;
◦ case 'about':
◦ return <AboutPage />;
◦ default:
◦ return <NotFoundPage />;
◦ }

Spreading Operator and Fragments

What is the spread operator in JSX?


The spread operator (...) is a JavaScript feature used in JSX to pass an object's properties as
props to a component. It expands the key-value pairs of an object into individual attributes.

• Example:
JavaScript

const userProps = { name: 'John', purpose:


'Developer' };

• return <ChildComponent {...userProps} />;


This is equivalent to return <ChildComponent name="John"


purpose="Developer" />;.

What is the role of Fragments in React?

Fragments are a way to group a list of child elements without adding an extra node (like a <div>)
to the DOM.

• Why use them? JSX requires that multiple elements must be wrapped in a single parent
element. Instead of wrapping them in an unnecessary div that could impact the page's
layout or performance, you can use <[Link]> or its shorthand, <>.

• Example:
JavaScript

<>

• <h1>Title</h1>
• <p>A paragraph</p>
• </>

Project Structure and Files


How to set up a React Project?

1. Install [Link]: React requires [Link], which comes with npm (Node Package Manager).

2. Install a Code Editor: A tool like VS Code is recommended.

3. Create the App: Use the npx create-react-app my-app command in your
terminal.

4. Open the Project: Open the created folder in your code editor.

5. Run the App: Use the command npm start to run the application in your browser.

What are the main default les in a React Project?

• [Link]: The single static HTML page of the application, located in the public
folder. It contains a root div element where the entire React application is rendered.

• [Link]: The JavaScript entry point for the application. It uses


[Link]() to mount the main App component into the root div of
[Link].

• [Link]: The main or root component of the application. All other components are
typically rendered inside this component.

• node_modules: A folder containing all the libraries and dependencies needed for the
project, installed by npm.

• [Link]: A le that lists all the project's dependencies and scripts.

• [Link]: A global CSS le for styling the application. You can also have separate CSS
les for individual components.

• public folder: Contains static assets like [Link], images, and fonts that are
served directly to the browser without being processed by webpack.

• src folder: The source folder where all your React components and application logic
reside.

How does a React app load and display components?


fi
fi
fi
fi
1. A user navigates to the application's URL.

2. The browser requests [Link] from the server.

3. [Link] is loaded. It contains a <div id="root"></div>.

4. The browser then loads [Link], which is the JavaScript entry point.

5. [Link] uses [Link]() to create a root for the app and then
uses the render() method to render the main App component into the div with the ID
"root".

6. The App component, along with all its child components, is then rendered in the browser.

What is the role of export default in [Link]?

The export default statement is used to make a component (e.g., App) available to be
imported and used in other les. It marks the component as the primary export from that module.

What is the role of the return statement in a component?

The return statement is used to return the JSX code that represents the component's UI. It's what
the component renders to the DOM. Without a return statement, the component would not
display anything.

State and Props

What is State?

State refers to the current data of a component. It is a plain JavaScript object that stores information
that can change over time. When the state changes, the component automatically re-renders to
re ect the new data.
fl
fi
What is the difference between Stateless and Stateful components?

• Stateless Components: Components that do not manage or store their own state. They are
purely presentational and receive data through props. (Before Hooks, this was the de ning
characteristic of functional components).

• Stateful Components: Components that manage their own state. They can update their state
and re-render in response to user actions or other events. (Before Hooks, this was the
de ning characteristic of class components).

What is State Management?

State Management is the process of controlling and updating a component's state, and ensuring
that the UI re-renders correctly when the state changes. It is the ability to make a component
"stateful" so that it can dynamically update its UI.

What are Props?

Props (short for properties) are a way to pass data from a parent component to a child component.
They are read-only and are used to customize the behavior or appearance of a child component.

• How to pass data: Data is passed from parent to child as attributes on the child component's
JSX tag.

• How to receive data: In the child component, props are received as an object. In a
functional component, this is the rst argument. In a class component, it is accessed via
[Link].

• Example (Passing Data):


JavaScript

// Parent component

• <ChildComponent name="John" purpose="Developer" />


• Example (Receiving Data):


JavaScript

// Child component (functional)


fi
fi
fi
• function ChildComponent(props) {
• return (
• <p>Name: {[Link]}, Purpose: {[Link]}</p>
• );
• }

Props Drilling and State Management

What is Props Drilling?

Props Drilling is the process of passing data from a parent component down to a deeply nested
child component through multiple layers of intermediate components. The intermediate components
receive the prop but don't actually use it themselves; they just pass it on.

• Problem with Props Drilling: It makes the code harder to maintain and debug. A change in
the data ow requires updating multiple components that may not even need the data.

How to avoid Props Drilling?

Props drilling can be avoided by using a centralized state management solution. The video suggests
ve ways:

1. Context API: A built-in React feature for sharing data that can be considered "global" for a
component tree.

2. Redux: A popular, third-party state management library for managing complex global state.

3. Component Composition: Structuring components in a way that avoids passing


unnecessary props through intermediate layers.

4. Callback Functions: Passing a function from a parent to a child to allow the child to send
data back up to the parent.

5. Custom Hooks: Creating a custom hook to encapsulate state logic and share it across
components.
fi
fl
What is the Context API?

The Context API is a built-in React feature that provides a way to pass data through the component
tree without having to pass props down manually at every level.

• How it works:

1. [Link](): Creates a Context object.

2. [Link]: A component that wraps the component tree where


you want the context to be available. It accepts a value prop, which is the data to
be shared.

3. useContext(MyContext): A hook used in a child component to access the


context value directly, without needing to receive it as a prop.

• When to use Context API? It's ideal for sharing "global" data like user authentication
status, theme (dark/light mode), or language settings to many components in a medium-
sized application.

Hooks

What are React Hooks?

React Hooks are built-in JavaScript functions provided by React that allow functional components
to "hook into" React state and lifecycle features.

• Top React Hooks: The video lists eight, but focuses on the most common ones:

◦ useState: For managing local state.

◦ useEffect: For handling side effects.

◦ useContext: For using the Context API.

◦ useReducer, useCallback, useMemo, useRef, useLayoutEffect.


What is the role of the useState hook?

The useState hook is used to manage a component's local state. It's the primary way to make a
functional component stateful.

• How it works:

4. useState is called at the top of a functional component.

5. It accepts an initial state value as an argument.

6. It returns an array with two elements: the current state value and a function to update
that value.

7. You can use array destructuring to get the state variable and the updater function.

8. When the updater function is called with a new value, React re-renders the
component with the updated state.

• Code Example:
JavaScript

import React, { useState } from 'react';


• function Counter() {
• const [count, setCount] = useState(0);

• const increment = () => {
• setCount(count + 1);
• };

• return (
• <div>
• <p>Count: {count}</p>
• <button onClick={increment}>Increment</button>
• </div>
• );
• }

What is the role of the useEffect hook?


The useEffect hook is used to perform side effects in functional components. A side effect is
any operation that happens after the component has rendered, such as data fetching, subscriptions,
or manually changing the DOM.

• How it works:

1. useEffect takes two arguments: a callback function (the "effect" function) and a
dependency array.

2. The effect function runs after the component renders.

3. The dependency array determines when the effect function will be re-run.

▪ An empty array [] means the effect will run only once, after the initial
render.

▪ An array with a variable (e.g., [userId]) means the effect will run once
on initial render and then again whenever that variable's value changes.

▪ No dependency array means the effect will run after every render.

• Code Example (Data Fetching):


JavaScript

import React, { useState, useEffect } from 'react';


• function DataFetcher() {
• const [data, setData] = useState(null);

• useEffect(() => {
• // This is a side effect
• fetchDataFromAPI().then(response => {
• setData([Link]);
• });
• }, []); // Empty dependency array: runs only once

• return (
• <div>
• {data ? <p>{data}</p> : <p>Loading data...</p>}
• </div>
• );
• }

Component Lifecycle (Class Components)

What are Component Lifecycle Phases?

A component's lifecycle has three main phases:

1. Mounting: The phase where a component is created and inserted into the DOM. Methods in
this phase are executed before the component becomes visible to the user.

2. Updating: The phase where a component is re-rendered due to a change in its state or props.

3. Unmounting: The phase where a component is removed from the DOM. Methods in this
phase are executed just before the component is destroyed.

What are Component Lifecycle Methods?

These are special methods that get called at different stages of a component's lifecycle. Here are the
most important ones:

• Mounting Phase:

◦ constructor(): The rst method called when a component is created. It's used
to initialize state and bind event handlers. It always calls super() to initialize the
parent [Link]'s constructor.

◦ render(): The only required method in a class component. It returns the JSX that
will be rendered to the DOM.

◦ componentDidMount(): Called after the component has been rendered to the


DOM for the rst time. It is a good place to perform side effects like fetching data
from an API.

• Updating Phase:

◦ render(): Called again to re-render the component with the new state or props.

◦ componentDidUpdate(): Called after the component has re-rendered due to a


state or prop change. It's useful for side effects that need to happen after an update.

• Unmounting Phase:
fi
fi
◦ componentWillUnmount(): Called just before a component is removed from
the DOM. It's the ideal place to clean up resources like timers or network requests.

Controlled and Uncontrolled Components

What is a Controlled Component?

A controlled component is a component whose form elements (like input elds) are controlled by
the component's state. The state acts as the "single source of truth" for the form data.

• How it works:

◦ The value of the input eld is tied to a state variable.

◦ An onChange event handler updates the state every time the user types.

◦ This ensures that the component's state and the UI are always in sync.

• Best Practice: Controlled components are the recommended approach for handling forms in
React because they provide better control, validation, and predictability.

• Code Example:
JavaScript

import React, { useState } from 'react';


• function ControlledComponent() {
• const [inputValue, setInputValue] = useState('');

• const handleInputChange = (event) => {
• setInputValue([Link]);
• };

• return (
• <div>
• <input type="text" value={inputValue}
onChange={handleInputChange} />
• <p>You typed: {inputValue}</p>
• </div>
• );
fi
fi
• }

What is an Uncontrolled Component?

An uncontrolled component is a component where form elements handle their own state
internally. The data is accessed directly from the DOM, typically using a ref, instead of being
controlled by React's state.

• How it works:

◦ React doesn't manage the state of the input eld.

◦ You use the useRef hook to get a direct reference to the DOM element.

◦ You access the input eld's value when a speci c event (like a button click) occurs.

• When to use them: They are used in very rare scenarios, such as when integrating with
non-React libraries or when performance is a critical concern, as they avoid re-renders.

Code Splitting

What is Code Splitting?

Code splitting is a technique that divides the application's JavaScript bundle into smaller "chunks."
These chunks are then loaded on demand, only when they are needed.

• Why use it? By default, a large React application is bundled into a single le, which can
take a long time to load. Code splitting improves initial load time by sending only the
essential code to the user and loading other parts later.

How to implement Code Splitting?


fi
fi
fi
fi
Code splitting is implemented using two main React features:

1. [Link](): This function allows you to render a dynamic import as a regular


component. It's a method for "lazy loading" a component, meaning it won't be loaded until
it's rendered.

2. Suspense: A component that wraps a lazily-loaded component. It displays a "fallback" UI


(like a loading spinner) while the lazy component is being fetched.

• Code Example:
JavaScript

import React, { lazy, Suspense } from 'react';


• const LazyComponent = lazy(() => import('./
LazyComponent'));

• function App() {
• return (
• <div>
• <Suspense fallback={<div>Loading...</div>}>
• <LazyComponent />
• </Suspense>
• </div>
• );
• }

Other Important Questions

What is a Higher-Order Component (HOC)?

A Higher-Order Component (HOC) is a function that takes a component as an argument and


returns a new component with added functionality or enhanced props. HOCs are a way to reuse
component logic in React.
• Example: A logging HOC might take a component and return a new component that logs
when it renders, without modifying the original component's code.

What are the ways to style React components?

There are several ways to style React components:

1. Inline Styles: Writing CSS as a JavaScript object directly on the element's style attribute.

2. CSS Style Sheets: Creating and importing a separate .css le for a component.

3. CSS Modules: Creating a unique class name for a component to avoid style con icts.

4. Global Style Sheets: Creating a common CSS le for application-wide styles.

5. CSS Frameworks: Using libraries like Bootstrap or Tailwind CSS for pre-de ned styles
and components.

What is the difference between React and React Native?

• Purpose: React is a JavaScript library for building web applications that run in a browser.
React Native is a framework for building native mobile applications for iOS and Android.

• UI Elements: React uses HTML tags and CSS for UI. React Native uses its own set of UI
components (e.g., View, Text) which are compiled to native UI elements.

• Deployment: React apps are deployed as web applications on a server. React Native apps
are deployed through app stores (Google Play, Apple App Store).

What are the three ways to achieve state management in React?

1. useState Hook: Best for simple, component-level state.

2. Context API: Best for sharing "global" state across multiple, deeply nested components to
avoid props drilling.

3. Redux: A third-party library for managing complex, global state in large-scale applications.
It provides a centralized store and predictable state management.
fi
fi
fi
fl
How to pass data from a child component to a parent component?

Data is passed from a child to a parent using a callback function.

• How it works:

1. The parent component de nes a function (the callback) that accepts data as an
argument.

2. The parent component passes this function as a prop to the child component.

3. The child component then calls this prop function, passing the data as an argument.

4. The parent's function is executed with the data from the child.

How to optimize performance in a React application?

1. Memoization: Using useMemo and useCallback hooks to prevent unnecessary re-


calculations and re-renders.

2. Code Splitting: Implementing [Link]() and Suspense to load components on


demand.

3. Use Fragments: Using <> or <[Link]> to avoid adding unnecessary


<div> elements to the DOM.

4. Optimizing Images: Compressing images and using responsive image techniques.

5. Use React Pro ler: A tool to analyze and identify performance bottlenecks in the
component tree.
fi
fi

You might also like