I'm always excited to take on new projects and collaborate with innovative minds.
academy@sogdo.com
https://academy.sogdo.in/
Sogdo Academy
React is a modern JavaScript library used to build fast, interactive, and scalable user interfaces for web applications. It follows a component-based architecture, allowing developers to create reusable UI elements that make applications easier to develop, maintain, and scale.
React is widely used for developing:
React works efficiently by updating only the parts of the user interface that actually change, resulting in excellent performance and a smooth user experience.
JSX is a syntax extension for JavaScript that allows developers to write HTML-like code directly inside JavaScript files.
Instead of manually creating UI elements using JavaScript functions, JSX provides a cleaner and more readable approach.
Although JSX looks like HTML, it is converted into JavaScript by tools such as Babel during the build process.
Everything in React is built using components.
A component is an independent, reusable piece of the user interface that contains its own structure, logic, and styling.
Using reusable components helps developers write cleaner, modular, and maintainable applications.
React improves performance using a Virtual DOM.
Instead of updating the entire webpage whenever data changes, React:
React follows a one-way data flow model.
Data moves from parent components to child components through props, making the application predictable and easier to manage.
React supports Server-Side Rendering through frameworks like Next.js.
With SSR, pages are rendered on the server before being sent to the browser.
React applications are structured in small, reusable components, making them easier to test independently.
Developers can verify:
This results in more reliable and maintainable applications.
React offers an excellent development experience through:
These features help developers build applications more efficiently.
Developers with knowledge of:
can begin learning React quickly.
The official documentation and large developer community make learning React accessible for both beginners and experienced professionals.
Traditional web applications update the complete Document Object Model (DOM) whenever changes occur, which can reduce performance in large applications.
React solves this by introducing the Virtual DOM.
This process, known as Reconciliation, significantly improves application performance.
import React from "react";
function App() {
return (
<div>
<h1>Welcome to Sogdo Academy React Tutorial</h1>
</div>
);
}
export default App;
Welcome to Sogdo Academy React Tutorial
React is trusted by organizations worldwide for building high-performance web applications.
Many technology companies and digital platforms use React to develop responsive and interactive user interfaces for millions of users.
Examples include:
The widespread adoption of React demonstrates its reliability, scalability, and long-term industry relevance.
React has become one of the most sought-after front-end technologies in modern web development.
Thousands of companies use React for production applications, creating excellent career opportunities.
Developers can build components once and reuse them throughout the application.
The Virtual DOM minimizes unnecessary rendering and improves application speed.
React has one of the largest developer communities, providing extensive learning resources and open-source libraries.
React integrates easily with REST APIs, GraphQL, Node.js, TypeScript, Redux, Firebase, and many other technologies.
By learning React, developers can also move into mobile application development using React Native.
React is one of the most powerful and widely adopted JavaScript libraries for building modern user interfaces. Its component-based design, Virtual DOM, efficient rendering, and extensive ecosystem enable developers to create scalable, maintainable, and high-performance web applications.
Whether you are a beginner starting your web development journey or an experienced software engineer building enterprise-level applications, mastering React is a valuable investment that opens opportunities across frontend, full-stack, and mobile application development.
At Sogdo Academy, you will learn React from the fundamentals to advanced concepts through practical examples, real-world projects, and industry-focused best practices, helping you become a confident React developer.
React is a modern, open-source JavaScript library used to build dynamic, interactive, and reusable user interfaces for web applications. It focuses on the presentation layer (UI) of an application, enabling developers to create fast, scalable, and maintainable frontend solutions.
React follows a declarative programming approach, allowing developers to describe how the user interface should appear for a given state instead of manually updating the browser elements.
Originally developed by engineers at Meta (formerly Facebook), React has become one of the most widely adopted frontend technologies and powers thousands of applications across the world.
Many web applications are designed using the Model-View-Controller (MVC) architectural pattern.
Within this architecture, React is primarily responsible for the View layer, which represents everything users see and interact with on the screen.
The remaining parts of the application, such as business logic and data management, are typically handled using backend services or state management libraries like Redux, Zustand, MobX, or similar solutions.
This separation of responsibilities helps developers build well-organized and maintainable applications.
React applications are built using components, which are independent and reusable building blocks of the user interface.
Each component manages a specific part of the application, such as:
Components can be combined together to create complex applications while keeping the code modular and easy to maintain.
One of React's most important performance features is the Virtual DOM.
The Virtual DOM is a lightweight in-memory representation of the browser's actual Document Object Model (DOM).
Whenever application data changes, React performs the following steps:
This intelligent update process minimizes unnecessary rendering and significantly improves application performance.
A React application is developed by combining multiple reusable components into a complete user interface.
For example, consider a user registration page.
Instead of writing the entire page as one large file, it can be divided into several smaller components:
Each component performs a specific task and can be reused throughout the application. This modular approach makes development faster and future updates much easier.
React has become one of the leading frontend technologies because it provides an excellent balance of performance, flexibility, and developer productivity.
Some of the reasons behind its popularity include:
React is widely used for building enterprise applications, business dashboards, e-commerce platforms, social media applications, and many other modern web solutions.
In traditional web development, the browser updates the Document Object Model (DOM) directly whenever application data changes.
For large applications, this approach can become inefficient because the browser may perform unnecessary rendering operations, resulting in:
As applications grow in size and complexity, these limitations become more noticeable.
React addresses these challenges by introducing the Virtual DOM.
Instead of immediately modifying the browser's DOM after every change, React first updates the Virtual DOM stored in memory.
It then compares the previous and current versions of the Virtual DOM to identify the exact elements that have changed.
Finally, React updates only those specific elements in the real DOM rather than re-rendering the entire page.
This optimization technique enables React applications to remain fast and responsive even as they become larger and more complex.
The Virtual DOM is a lightweight copy of the actual browser DOM that exists entirely in memory.
Whenever a component's state or properties change, React performs a comparison process known as Reconciliation.
During reconciliation, React identifies the minimum number of updates required and applies only those changes to the real browser DOM.
This process reduces unnecessary DOM operations, improves rendering efficiency, and provides a smoother user experience.
React offers numerous advantages for modern web development.
The Virtual DOM minimizes unnecessary browser updates, resulting in faster rendering.
Developers can create components once and reuse them across different parts of the application.
A modular code structure makes applications easier to update, debug, and extend.
Efficient rendering provides smoother interactions and faster page updates.
React applications can grow from small projects to large enterprise systems without major architectural changes.
React integrates seamlessly with TypeScript, Node.js, Next.js, Redux, GraphQL, REST APIs, Firebase, and many other modern technologies.
React is a powerful JavaScript library designed for building fast, interactive, and scalable user interfaces. Its component-based architecture, declarative programming model, and Virtual DOM make it an excellent choice for modern frontend development.
By breaking applications into reusable components and updating only the necessary parts of the interface, React enables developers to create high-performance applications that are easier to maintain and expand.
At Sogdo Academy, React is taught from the fundamentals to advanced concepts using practical examples, real-world projects, and industry best practices to help learners build production-ready web applications.
Updated for Sogdo Academy
Since its public release in 2013, React has continuously evolved into one of the world's most popular JavaScript libraries for building modern user interfaces. Every major release has introduced improvements in performance, developer productivity, application scalability, and user experience.
React has progressed from a simple UI library to a comprehensive ecosystem supporting advanced features such as Hooks, Concurrent Rendering, Automatic Batching, Server Components, and modern rendering APIs.
Understanding the evolution of React helps developers appreciate why certain features exist and which capabilities are available in different versions.
The following timeline highlights the most significant milestones in React's development.
| Version | Release Year | Major Highlights |
|---|---|---|
| React 0.3 | 2013 | First public release introducing the React library and component-based architecture. |
| React 0.4 – 0.14 | 2013–2015 | Added JSX improvements, Virtual DOM enhancements, server-side rendering support, better event handling, SVG support, HTML attribute support, ES6 class compatibility, and overall stability improvements. |
| React 15 | 2016–2017 | Major rendering optimizations, improved SVG support, simplified DOM rendering, enhanced debugging, performance improvements, and deprecation of older APIs such as React.createClass. |
| React 16 (Fiber) | 2017 | One of the biggest React releases. Introduced the Fiber architecture, Error Boundaries, Fragments, Portals, improved rendering engine, and better error recovery. |
| React 16.3 – 16.8 | 2018–2019 | Added the new Context API, Profiler, React.lazy(), Suspense, and the revolutionary Hooks API (useState, useEffect, and others). |
| React 17 | 2020 | Focused on easier upgrades, improved event delegation, and better compatibility without introducing major API changes. |
| React 18 | 2022 | Introduced Concurrent Rendering, Automatic Batching, createRoot(), startTransition(), improved Suspense, and Streaming Server-Side Rendering (SSR). |
| React 19 | Modern Releases | Enhanced Server Components, Actions, improved Forms, Metadata management, Asset Loading, and overall performance optimizations for modern applications. |
The earliest React releases introduced the foundation of modern frontend development.
These versions established React as a practical alternative to traditional frontend development approaches.
React 15 focused primarily on improving stability and rendering performance.
React 15 also marked the beginning of deprecating several legacy APIs in preparation for future versions.
Released in 2017, React 16 represented one of the largest architectural changes in React's history.
The previous rendering engine was replaced with the Fiber Reconciliation Engine, making rendering faster, interruptible, and more efficient.
Fiber became the foundation for many advanced React capabilities introduced in later versions.
React 16.8 changed how developers write React applications by introducing Hooks.
Before Hooks, state management was available mainly through Class Components.
Hooks enabled developers to use state and lifecycle features directly inside Functional Components.
useState()useEffect()useContext()useReducer()useMemo()useCallback()useRef()Hooks quickly became the recommended approach for developing React applications.
React 17 was designed as a transition release.
Instead of introducing major new features, it focused on making upgrades between React versions easier.
React 18 introduced several advanced rendering capabilities that significantly improved application responsiveness.
Allows React to prepare multiple UI updates without blocking user interactions.
Multiple state updates are automatically grouped together, reducing unnecessary re-rendering.
Introduced:
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
This replaces the older ReactDOM.render() method.
Developers can mark non-urgent updates using:
startTransition(() => {
// State updates
});
This keeps applications responsive during complex rendering operations.
Better loading experiences for asynchronous components and data fetching.
The latest generation of React focuses on improving both developer productivity and application performance.
React 19 continues to reduce boilerplate code while making full-stack React development simpler.
Learning React's evolution helps developers:
For most modern applications, developers should focus on React 18+ concepts while understanding earlier versions for maintaining legacy codebases.
For new learners, Sogdo Academy recommends starting with the latest stable React release.
Avoid learning deprecated concepts such as:
componentWillMount()componentWillReceiveProps()React.createClass()Instead, focus on modern React development using:
Before you start building React applications, you need to prepare your development environment. Setting up the required tools correctly helps you write code, test your application, and build projects without any issues.
In this chapter, you will learn the software required for React development and the common ways to create a React project.
Before installing React, make sure the following software is available on your computer:
Note: In modern React development, tools such as Vite automatically configure Webpack and Babel. Therefore, beginners usually do not need to configure them manually.
There are different ways to create a React project. The choice depends on your project requirements and the development approach you want to follow.
Vite is the preferred choice for creating new React projects. It creates projects quickly, starts the development server almost instantly, and provides a faster development experience.
It is suitable for:
Most modern React projects use Vite.
Create React App is another tool used to create React projects.
It automatically sets up the required project structure and configuration, allowing developers to focus on writing code instead of configuring build tools.
Although many existing projects still use Create React App, most new applications are now created with Vite because it offers better speed and performance.
Learning Create React App is still useful if you need to work on older React applications.
Create React App (CRA) is a command-line tool that helps developers quickly create a React project without manually configuring build tools such as Webpack or Babel. It automatically sets up the project structure, installs the required dependencies, and prepares a ready-to-use development environment.
For many years, Create React App was the standard way to start a React project. Although modern applications commonly use Vite because of its better performance, Create React App is still widely used in existing projects. Understanding CRA is useful when maintaining or working on older React applications.
Setting up a React project manually requires configuring several tools and packages. Create React App simplifies this process by handling the configuration automatically.
Some benefits include:
This allows developers to focus on writing React code instead of configuring development tools.
Before creating a React project, make sure the following software is installed on your computer.
To verify the installation, open the terminal or command prompt and run:
node -v
Check the npm version:
npm -v
If both commands display version numbers, your environment is ready for React development.
Create React App can be used without installing it globally.
The recommended approach is:
npx create-react-app my-react-app
Replace my-react-app with your preferred project name.
The command automatically:
The installation may take a few minutes depending on your internet speed.
Move into the project directory.
cd my-react-app
Run the following command:
npm start
The development server starts automatically and opens the application in your default web browser.
By default, the application runs at:
http://localhost:3000
Whenever you save changes to your code, the browser automatically refreshes and displays the updated output.
A newly created React project contains several important files and folders.
Stores all third-party packages and project dependencies installed through npm.
Contains static files such as:
The index.html file acts as the entry point where the React application is loaded.
This is the main development folder where most of your React code is written.
Common files include:
As your application grows, you can create additional folders such as:
Contains project information, scripts, dependencies, and configuration details.
Automatically generated by npm to ensure consistent dependency versions across different environments.
Contains documentation and project-related information.
Open the following file:
src/App.js
Replace the default content with your own React component.
Example:
function App() {
return (
<div>
<h1>Welcome to Sogdo Academy</h1>
<p>My first React application.</p>
</div>
);
}
export default App;
Save the file.
The browser refreshes automatically, and the updated content appears without restarting the server.
As your application grows, avoid writing everything inside App.js.
Instead, create separate components such as:
Import them into App.js to build modular and reusable applications.
When your application is ready for deployment, create an optimized production build.
Run:
npm run build
This command creates a build folder containing optimized HTML, CSS, JavaScript, and other assets suitable for deployment.
Although Create React App is still widely used in many existing applications, most new React projects now use Vite because it offers:
Learning Create React App remains valuable because many enterprise applications continue to use it.
Updated for Sogdo Academy
React is one of the most popular JavaScript libraries for building modern, interactive, and scalable user interfaces. It is widely used for developing single-page applications (SPAs), enterprise software, dashboards, e-commerce platforms, and mobile applications.
The popularity of React comes from its simple learning curve, component-based architecture, excellent performance, and strong developer ecosystem. It enables developers to build applications that are easy to maintain, reusable, and highly efficient.
In this chapter, we will explore the major features that make React a preferred choice for modern web development.
React applications are built using components, which are small, reusable pieces of the user interface.
Each component performs a specific task and can be reused throughout the application. This modular approach improves code organization and simplifies application development.
One of React's biggest advantages is the Virtual DOM.
Instead of updating the entire webpage whenever data changes, React creates a virtual copy of the DOM in memory, compares it with the previous version, and updates only the elements that have changed.
React follows a declarative programming approach.
Developers describe how the user interface should look based on the current application state, and React automatically updates the browser whenever the data changes.
This reduces manual DOM manipulation and makes applications easier to understand and maintain.
JSX is a syntax extension that allows developers to write HTML-like code inside JavaScript.
It makes React components more readable and easier to develop.
Example:
function Welcome() {
return <h1>Welcome to Sogdo Academy</h1>;
}
Although JSX looks like HTML, it is converted into standard JavaScript during the build process.
React follows a one-way data flow, meaning data moves from parent components to child components through props.
This predictable flow makes applications easier to debug and maintain.
React encourages developers to create components that can be reused in different parts of an application.
For example, a Button, Header, Navigation Bar, or Footer component can be used across multiple pages without rewriting the same code.
This saves development time and ensures consistency throughout the application.
React provides a large ecosystem of libraries and frameworks that extend its functionality.
Popular tools include:
This ecosystem allows developers to build complete, production-ready applications.
React has one of the largest developer communities in the world.
Developers can easily find:
A strong community ensures continuous improvements and quick solutions to common development challenges.
React supports Server-Side Rendering (SSR) through frameworks such as Next.js.
With SSR, web pages are rendered on the server before being sent to the browser.
React knowledge can also be used for mobile application development through React Native.
Using React Native, developers can build applications for:
while sharing much of the same programming knowledge used for web development.
React provides excellent debugging support through browser extensions such as React Developer Tools.
These tools allow developers to:
Hooks are one of the most significant features introduced in modern React.
They allow Functional Components to use state, lifecycle features, and other React capabilities without writing Class Components.
Commonly used Hooks include:
Hooks simplify React development and are now the recommended approach for building applications.
The Context API provides a simple way to share data across multiple components without passing props through every intermediate component.
It is commonly used for managing:
This reduces unnecessary prop drilling and keeps code cleaner.
React encourages developers to treat application data as immutable.
Instead of modifying existing data directly, a new copy of the data is created whenever changes are required.
This approach helps React detect updates efficiently and results in more predictable application behavior.
React makes it easier to build applications that are accessible to all users, including those using assistive technologies.
Developers can improve accessibility by using:
Building accessible applications improves usability and follows modern web standards.
React is designed to deliver excellent performance through features such as:
These optimizations help applications remain responsive even as they grow in size and complexity.
React and React Native are two popular technologies developed using the same core concepts, but they are designed for different purposes. Although they share a similar programming style and component-based architecture, they are used to build different types of applications.
Understanding the differences between React and React Native helps developers choose the right technology based on project requirements.
| Feature | React | React Native |
|---|---|---|
| Purpose | Develops web applications. | Develops native mobile applications. |
| Platform | Runs in web browsers. | Runs on Android and iOS devices. |
| Rendering | Uses HTML and CSS to render the user interface. | Uses native mobile UI components instead of HTML. |
| Programming Language | JavaScript or TypeScript with JSX. | JavaScript or TypeScript with JSX. |
| Styling | CSS, CSS Modules, Tailwind CSS, Bootstrap, Styled Components, etc. | Uses the built-in StyleSheet API or third-party styling libraries. |
| Navigation | Uses libraries such as React Router. | Uses React Navigation or similar navigation libraries. |
| DOM Support | Uses the Virtual DOM for efficient browser rendering. | Does not use the browser DOM. It renders native mobile components. |
| Performance | Optimized for web applications. | Delivers near-native performance on mobile devices. |
| Deployment | Deployed to web servers or cloud hosting platforms. | Published through the Google Play Store and Apple App Store. |
| Learning Curve | Easier for web developers. | Requires understanding of mobile application development concepts. |
React is a JavaScript library used to build responsive and interactive user interfaces for websites and web applications.
It is commonly used to develop:
React Native is a framework built on top of React that enables developers to create native mobile applications using JavaScript.
Instead of rendering HTML elements, React Native renders native Android and iOS components.
Common applications include:
Although React and React Native are used for different platforms, they share many common concepts.
Developers familiar with React can learn React Native more easily because many core concepts remain the same.
Choose React when you want to build:
Choose React Native when you want to build:
For beginners, it is recommended to learn React first.
React helps you understand the core concepts such as:
After gaining confidence in React, learning React Native becomes much easier because it builds upon the same fundamentals.
JSX stands for JavaScript XML. It is a syntax extension that allows developers to write HTML-like code directly inside JavaScript. JSX makes React components easier to read and write by combining the structure of the user interface with JavaScript logic.
Although JSX looks similar to HTML, it is not HTML. Before the code runs in the browser, tools such as Babel convert JSX into standard JavaScript that React understands.
JSX is optional in React, but it is the most commonly used approach because it improves code readability and development speed.
When you write JSX, it is automatically converted into JavaScript function calls during the build process.
<div>Welcome to Sogdo Academy</div>
React.createElement("div", null, "Welcome to Sogdo Academy");
The React.createElement() method creates a React element that React uses to build the user interface.
JSX offers several advantages that simplify React development.
JSX looks similar to HTML, making it easier to understand the structure of a component.
Developers can create user interfaces with fewer lines of code compared to using JavaScript functions directly.
Modern code editors provide syntax highlighting, auto-completion, formatting, and error detection for JSX.
JavaScript expressions can be written directly inside JSX, allowing dynamic content to be displayed easily.
Since both UI and logic are written in the same file, components become easier to develop and maintain.
A simple React component using JSX looks like this:
function App() {
return (
<div>
<h1>Welcome to Sogdo Academy</h1>
<p>Learn React with practical examples.</p>
</div>
);
}
export default App;
The component returns a JSX structure that React renders in the browser.
A React component can contain multiple elements.
However, all elements must be wrapped inside a single parent element.
Example:
function App() {
return (
<div>
<h1>Sogdo Academy</h1>
<h2>React Training</h2>
<p>Build modern web applications with React.</p>
</div>
);
}
Instead of <div>, you can also use a React Fragment (<>...</>) when no extra HTML element is required.
JSX supports attributes similar to HTML, but some attribute names are different because JavaScript keywords cannot be used directly.
| HTML | JSX |
|---|---|
| class | className |
| for | htmlFor |
| tabindex | tabIndex |
| onclick | onClick |
Example:
function App() {
return (
<h1 className="title">
Welcome to Sogdo Academy
</h1>
);
}
One of the biggest advantages of JSX is that JavaScript expressions can be embedded using curly braces {}.
Example:
function App() {
const course = "React";
return <h1>Welcome to {course}</h1>;
}
Output:
Welcome to React
Expressions can include:
Example:
<h2>{20 + 30}</h2>
Output:
50
Comments inside JSX are written using JavaScript comment syntax enclosed in curly braces.
Example:
function App() {
return (
<div>
<h1>React Tutorial</h1>
{/* This is a JSX comment */}
<p>Welcome to Sogdo Academy.</p>
</div>
);
}
Comments are ignored when the application is rendered.
React supports inline styling using JavaScript objects.
CSS property names use camelCase instead of hyphen-separated names.
Example:
function App() {
const headingStyle = {
color: "blue",
fontSize: "36px",
fontWeight: "bold"
};
return <h1 style={headingStyle}>Sogdo Academy</h1>;
}
For larger applications, using external CSS files or CSS Modules is generally recommended.
JSX does not allow traditional statements like if...else directly inside the returned JSX.
Instead, developers commonly use:
&&)return statementExample using the ternary operator:
function App() {
const isLoggedIn = true;
return (
<h2>
{isLoggedIn ? "Welcome Back!" : "Please Login"}
</h2>
);
}
Output:
Welcome Back!
When writing JSX, remember the following rules:
className instead of class.htmlFor instead of for.{}.{/* ... */}.Following these rules helps avoid syntax errors and keeps your code clean.
Components are the foundation of every React application. Instead of building an entire user interface in a single file, React encourages developers to divide the application into small, reusable pieces called components.
Each component is responsible for displaying a specific part of the user interface and can be reused wherever needed. This modular approach makes applications easier to develop, test, maintain, and scale.
For example, a website may contain components such as:
Each component works independently but combines with other components to create a complete application.
A React component is a JavaScript function or class that returns JSX describing how a part of the user interface should appear.
Components can:
Think of components as building blocks. Just as a house is built using bricks, a React application is built using components.
Using components provides several advantages:
React provides two ways to create components:
Although both can be used, Functional Components are the recommended approach in modern React development.
A Functional Component is a simple JavaScript function that returns JSX.
Modern React applications primarily use Functional Components because they are easier to understand, require less code, and support powerful features through Hooks.
function Welcome() {
return <h1>Welcome to Sogdo Academy</h1>;
}
export default Welcome;
You can also write the same component using an arrow function.
const Welcome = () => {
return <h1>Welcome to Sogdo Academy</h1>;
};
export default Welcome;
Components can receive data from their parent using props.
Example:
function Student(props) {
return <h2>Welcome, {props.name}</h2>;
}
export default Student;
Using the component:
<Student name="Rahul" />
<Student name="Priya" />
<Student name="Amit" />
Output:
Welcome, Rahul
Welcome, Priya
Welcome, Amit
Before the introduction of Hooks, Class Components were commonly used for managing state and lifecycle methods.
A Class Component extends React.Component and must include a render() method.
Example:
import React, { Component } from "react";
class Welcome extends Component {
render() {
return <h1>Welcome to Sogdo Academy</h1>;
}
}
export default Welcome;
Although Class Components are still supported, they are mainly found in older React projects.
| Feature | Functional Component | Class Component |
|---|---|---|
| Syntax | Simple JavaScript function | ES6 Class |
| Code Length | Short and clean | More verbose |
| State Management | Uses Hooks | Uses this.state |
| Lifecycle Features | Uses Hooks like useEffect() | Lifecycle methods |
| Performance | Lightweight | Slightly heavier |
| Modern Recommendation | Recommended | Mostly used in legacy projects |
For new applications, Functional Components should always be your first choice.
Large React applications are divided into many components.
Example structure:
src/
│
├── components/
│ ├── Header.jsx
│ ├── Footer.jsx
│ ├── Navbar.jsx
│ ├── Sidebar.jsx
│ └── Card.jsx
│
├── App.jsx
└── main.jsx
Each file contains a single component responsible for a specific task.
Components can be imported and combined to build a complete page.
Example:
import Header from "./components/Header";
import Footer from "./components/Footer";
function App() {
return (
<>
<Header />
<Footer />
</>
);
}
export default App;
This modular approach keeps the project organized and easy to maintain.
When creating components, follow these guidelines:
components folder.Correct examples:
Header
Navbar
StudentCard
UserProfile
Dashboard
Incorrect examples:
header
navbar
studentcard
State is one of the most important concepts in React. It allows a component to store and manage data that can change over time. Whenever the state changes, React automatically updates the user interface to display the latest information.
State makes applications interactive by responding to user actions such as button clicks, form inputs, API responses, and other events.
Examples of data commonly stored in state include:
State is a built-in object used to store data that belongs to a specific component.
Unlike regular JavaScript variables, updating the state tells React that the component needs to be re-rendered.
Each component manages its own state unless the data is shared with other components.
Without state, a React component would always display the same content.
State allows the user interface to change dynamically based on user interactions or application data.
For example:
Modern React applications use the useState() Hook to create and manage state inside Functional Components.
Example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
In this example:
count stores the current value.setCount() updates the value.The useState() Hook returns an array containing two values.
const [value, setValue] = useState(initialValue);
Example:
const [name, setName] = useState("Sogdo Academy");
State should always be updated using its setter function.
Example:
setCount(count + 1);
Never modify the state variable directly.
Incorrect:
count = count + 1;
Correct:
setCount(count + 1);
Using the setter function ensures React updates the user interface correctly.
State is commonly used to show or hide content.
import { useState } from "react";
function App() {
const [showInfo, setShowInfo] = useState(false);
return (
<div>
<button onClick={() => setShowInfo(!showInfo)}>
{showInfo ? "Hide Details" : "Show Details"}
</button>
{showInfo && (
<p>
Welcome to Sogdo Academy. Learn React through practical projects.
</p>
)}
</div>
);
}
export default App;
Clicking the button changes the state, and React updates the displayed content automatically.
State is flexible and can store various data types.
const [name, setName] = useState("John");
const [age, setAge] = useState(25);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [courses, setCourses] = useState([
"React",
"Java",
"Spring Boot"
]);
const [user, setUser] = useState({
name: "Rahul",
city: "Hyderabad"
});
| State | Regular Variable |
|---|---|
| Updates the UI automatically. | Does not update the UI. |
| Managed by React. | Managed by JavaScript. |
Uses useState(). | Uses let, const, or var. |
| Persists across component re-renders. | May reset during rendering. |
Before Hooks were introduced, React used Class Components to manage state.
Example:
class App extends React.Component {
state = {
count: 0
};
render() {
return <h2>{this.state.count}</h2>;
}
}
State was updated using:
this.setState({
count: this.state.count + 1
});
Although Class Components are still supported, modern React development primarily uses Functional Components with Hooks.
Props, short for Properties, are a mechanism for passing data from one component to another in React. They allow parent components to share information with child components, making components reusable and dynamic.
Props are read-only, which means a component can use the data it receives but cannot modify it. This helps maintain a predictable flow of data throughout the application.
Think of props as function parameters. Just as functions receive values through arguments, React components receive data through props.
Props are objects that contain values passed from a parent component to a child component.
They can be used to pass:
Props help developers build flexible and reusable components that can display different content based on the values they receive.
Props make React components reusable and configurable.
Instead of creating multiple similar components, you can create one component and display different data by passing different props.
Props are passed to a component as attributes.
Example:
function App() {
return <Welcome name="Sogdo Academy" />;
}
Receiving the prop:
function Welcome(props) {
return <h1>Welcome to {props.name}</h1>;
}
export default Welcome;
Output:
Welcome to Sogdo Academy
A component can receive multiple props at the same time.
Example:
function Student(props) {
return (
<div>
<h2>{props.name}</h2>
<p>Course: {props.course}</p>
<p>Experience: {props.experience} Years</p>
</div>
);
}
Using the component:
<Student
name="Rahul"
course="React"
experience={2}
/>
Instead of writing props.propertyName repeatedly, React developers commonly use object destructuring.
Example:
function Student({ name, course }) {
return (
<div>
<h2>{name}</h2>
<p>{course}</p>
</div>
);
}
This approach makes the code shorter and easier to read.
Sometimes a parent component may not pass a value.
You can provide a default value using JavaScript default parameters.
Example:
function Welcome({ name = "Student" }) {
return <h1>Welcome, {name}</h1>;
}
Using:
<Welcome />
Output:
Welcome, Student
Props can store different types of values.
<Profile name="Amit" />
<Profile age={25} />
<Profile isActive={true} />
<Profile skills={["React", "Java", "Spring Boot"]} />
<Profile user={{ name: "Rahul", city: "Hyderabad" }} />
<Button onClick={handleClick} />
Props should never be modified inside a component.
Incorrect:
props.name = "New Name";
Correct:
<h2>{props.name}</h2>
If the displayed value needs to change, update the data in the parent component and pass the updated value as a prop.
Props and State are often used together.
A parent component stores data in its state and passes that data to child components through props.
Example:
import { useState } from "react";
function App() {
const [course] = useState("React");
return <Course name={course} />;
}
function Course({ name }) {
return <h2>{name}</h2>;
}
This pattern keeps data centralized while allowing child components to display it.
| Props | State |
|---|---|
| Passed from a parent component. | Managed within the component itself. |
| Read-only. | Can be updated. |
| Used for sharing data. | Used for storing changing data. |
| Cannot be modified by the receiving component. | Updated using setter functions like useState(). |
| Helps components communicate. | Controls component behavior and UI updates. |
Imagine an online learning platform displaying multiple course cards.
Instead of creating separate components for every course, you can create one reusable CourseCard component and pass different props for each course.
<CourseCard
title="React Development"
instructor="Sogdo Academy"
duration="40 Hours"
/>
<CourseCard
title="Spring Boot"
instructor="Sogdo Academy"
duration="35 Hours"
/>
The same component displays different information based on the props it receives.
Props validation is a technique used to verify that a React component receives data in the expected format. By validating props, developers can identify incorrect data types during development and reduce unexpected behavior in their applications.
React provides the PropTypes library to define the expected type of each prop. If a component receives an invalid value, React displays a warning in the browser console, making it easier to identify and fix issues.
Note: PropTypes are used only during development. They do not prevent the application from running and are not included in production builds.
As applications grow, components receive data from multiple sources. Passing incorrect data types can cause rendering issues or runtime errors.
Props validation helps by:
Modern React projects require the prop-types package.
npm install prop-types
Import it into your component:
import PropTypes from "prop-types";
Example:
import PropTypes from "prop-types";
function Student({ name, age }) {
return (
<div>
<h2>{name}</h2>
<p>Age: {age}</p>
</div>
);
}
Student.propTypes = {
name: PropTypes.string,
age: PropTypes.number
};
export default Student;
If an incorrect value is passed, React shows a warning in the developer console.
Some props are mandatory for a component to function correctly.
Use isRequired to make a prop required.
Student.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
};
If either prop is missing, React displays a warning during development.
Default values can be provided when a prop is not passed.
Example:
function Welcome({ academy = "Sogdo Academy" }) {
return <h2>Welcome to {academy}</h2>;
}
Using JavaScript default parameters is the recommended approach in modern React.
| Validator | Description |
|---|---|
PropTypes.any | Accepts any data type. |
PropTypes.string | String value. |
PropTypes.number | Numeric value. |
PropTypes.bool | Boolean value. |
PropTypes.array | Array value. |
PropTypes.object | Object value. |
PropTypes.func | Function. |
PropTypes.element | React element. |
PropTypes.node | Anything React can render, including text and elements. |
PropTypes.symbol | JavaScript Symbol. |
PropTypes.instanceOf(Class) | Instance of a specific JavaScript class. |
PropTypes.oneOf() | Value must match one of the specified options. |
PropTypes.oneOfType() | Value can be one of multiple data types. |
PropTypes.shape() | Object with a defined structure. |
PropTypes.arrayOf() | Array containing a specific data type. |
PropTypes.objectOf() | Object whose values are of the same type. |
Restrict values to predefined options.
Button.propTypes = {
variant: PropTypes.oneOf([
"primary",
"secondary",
"danger"
])
};
Valid:
<Button variant="primary" />
Invalid:
<Button variant="blue" />
Allow multiple data types.
Profile.propTypes = {
id: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string
])
};
Both are valid:
<Profile id={101} />
<Profile id="101" />
Validate the structure of an object.
Student.propTypes = {
user: PropTypes.shape({
name: PropTypes.string,
age: PropTypes.number,
city: PropTypes.string
})
};
Usage:
<Student
user={{
name: "Rahul",
age: 24,
city: "Hyderabad"
}}
/>
Ensure all array items are of the same type.
Course.propTypes = {
topics: PropTypes.arrayOf(
PropTypes.string
)
};
Usage:
<Course
topics={[
"React",
"Hooks",
"JSX"
]}
/>
You can create custom validators for business-specific rules.
Example:
Student.propTypes = {
age(props, propName, componentName) {
if (props[propName] < 18) {
return new Error(
`${componentName}: Age must be at least 18.`
);
}
}
};
This validation checks whether the age is greater than or equal to 18.
import PropTypes from "prop-types";
function CourseCard({ title, duration, level }) {
return (
<div>
<h2>{title}</h2>
<p>{duration}</p>
<p>{level}</p>
</div>
);
}
CourseCard.propTypes = {
title: PropTypes.string.isRequired,
duration: PropTypes.number.isRequired,
level: PropTypes.oneOf([
"Beginner",
"Intermediate",
"Advanced"
])
};
export default CourseCard;
Usage:
<CourseCard
title="React Development"
duration={40}
level="Beginner"
/>
isRequired for mandatory data.shape() for object validation.oneOf() for predefined values.arrayOf() for arrays containing similar data.
| PropTypes | TypeScript |
|---|---|
| Runtime validation during development. | Compile-time type checking. |
| Simple to use. | More powerful and feature-rich. |
| Works with JavaScript projects. | Requires TypeScript. |
| Shows warnings in the browser console. | Detects errors before running the application. |
Many modern React projects use TypeScript for type safety, while PropTypes remain useful in JavaScript-based applications.
State and Props are two fundamental concepts in React. Every React application uses them to manage and share data between components.
Although they may appear similar, they serve different purposes.
Understanding the difference between State and Props is essential for building scalable, reusable, and maintainable React applications.
State is a built-in object that stores information specific to a component. It represents data that can change during the lifetime of the component.
Whenever state changes, React automatically re-renders the component and updates the user interface.
Example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<>
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
</>
);
}
export default Counter;
Props (Properties) are used to pass data from one component to another.
A parent component sends data through props, and the child component receives and displays it.
Props are read-only, meaning the receiving component cannot modify them.
Example:
function App() {
return <Welcome academy="Sogdo Academy" />;
}
function Welcome({ academy }) {
return <h2>Welcome to {academy}</h2>;
}
Output
Welcome to Sogdo Academy
| Feature | State | Props |
|---|---|---|
| Purpose | Stores component data. | Passes data between components. |
| Ownership | Managed by the component itself. | Controlled by the parent component. |
| Mutability | Mutable (can change). | Immutable (read-only). |
| Updated By | Component using state setter functions. | Parent component. |
| Data Flow | Internal to the component. | Parent → Child. |
| Re-render | Updating state re-renders the component. | New props from parent trigger re-render. |
| Scope | Local to one component. | Shared with child components. |
| Typical Use | Dynamic UI and user interactions. | Configuration and communication. |
setState() (Class Components) or useState() (Functional Components).Example:
const [theme, setTheme] = useState("Light");
Example:
<Card
title="React Development"
trainer="Sogdo Academy"
/>
In most React applications, both State and Props are used together.
The parent component stores data in its state and passes that data to child components through props.
Example:
import { useState } from "react";
function App() {
const [course] = useState("React Development");
return <Course name={course} />;
}
function Course({ name }) {
return <h2>{name}</h2>;
}
export default App;
Flow:
State (Parent)
│
▼
Props
│
▼
Child Component
Consider an online learning platform.
These values are stored in State.
These components receive data using Props and display it.
This approach keeps the application organized and reusable.
Use State when:
Examples:
Use Props when:
Examples:
Incorrect:
props.title = "New Title";
Correct:
Update the value in the parent component and pass the updated prop.
Incorrect:
count = count + 1;
Correct:
setCount(count + 1);
If a value never changes, pass it through props instead of storing it in state.
| Question | State | Props |
|---|---|---|
| Can it change? | ✅ Yes | ❌ No |
| Who owns it? | Current component | Parent component |
| Can child modify it? | No | No |
| Used for UI updates? | ✅ Yes | Indirectly |
| Makes components reusable? | Partially | ✅ Yes |
| Stores local data? | ✅ Yes | ❌ No |
| Shares data with children? | Indirectly | ✅ Yes |
Although State and Props have different purposes, they also share some similarities.
A constructor is a special method in JavaScript classes that is automatically executed when a new object or class instance is created. In React, constructors are used only in Class Components to initialize component data and perform setup tasks before the component is rendered.
Although constructors were commonly used in older React applications, modern React development mainly uses Functional Components with Hooks, reducing the need for constructors. However, understanding constructors remains important when working with legacy React applications or maintaining existing codebases.
A constructor is a method that runs automatically when a class component is created.
Its primary responsibilities include:
class App extends React.Component {
constructor(props) {
super(props);
// Initialization code
}
render() {
return <h1>Welcome to Sogdo Academy</h1>;
}
}
super(props) Required?A React class component extends React.Component.
Calling super(props) executes the constructor of the parent class, allowing React to initialize the component properly.
Without calling super(props), this and this.props cannot be safely accessed inside the constructor.
Correct:
constructor(props) {
super(props);
console.log(this.props);
}
Incorrect:
constructor(props) {
console.log(this.props);
super(props);
}
The second example produces an error because this is used before calling super().
A constructor is mainly used for:
The most common use of a constructor is setting the initial state.
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return <h2>{this.state.count}</h2>;
}
}
Here, the initial value of count is set before the component is displayed.
In traditional class components, JavaScript does not automatically bind this.
Constructor binding ensures that this always refers to the current component.
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log("Button clicked");
}
render() {
return (
<button onClick={this.handleClick}>
Click
</button>
);
}
}
Modern JavaScript supports arrow functions, which automatically preserve the correct this context.
Because of this, explicit binding inside the constructor is no longer required.
class App extends React.Component {
handleClick = () => {
console.log("Button clicked");
};
render() {
return (
<button onClick={this.handleClick}>
Click
</button>
);
}
}
This approach is cleaner and more commonly used in class components.
Props can be accessed after calling super(props).
class Student extends React.Component {
constructor(props) {
super(props);
console.log(props.name);
}
render() {
return <h2>{this.props.name}</h2>;
}
}
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
academy: "Sogdo Academy"
};
this.changeName = this.changeName.bind(this);
}
changeName() {
this.setState({
academy: "Sogdo Academy React Training"
});
}
render() {
return (
<div>
<h2>{this.state.academy}</h2>
<button onClick={this.changeName}>
Update Name
</button>
</div>
);
}
}
export default App;
No.
A constructor is only required when you need to:
If none of these are needed, you can omit the constructor.
Example:
class Welcome extends React.Component {
render() {
return <h2>Welcome to Sogdo Academy</h2>;
}
}
No.
Functional components do not support constructors.
Instead, React Hooks provide the same functionality.
| Class Component | Functional Component |
|---|---|
| Constructor | useState() |
| Lifecycle setup | useEffect() |
Example:
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return <h2>{count}</h2>;
}
When a class component is created, React executes the following steps:
Flow:
Component Created
│
▼
Constructor()
│
▼
Initialize State
│
▼
Render()
│
▼
Component Mounted
super(props) before using this.componentDidMount() instead.useState()| Constructor (Class Component) | useState() (Functional Component) |
|---|---|
| Used only in class components. | Used only in functional components. |
| Initializes component state. | Initializes component state. |
Requires super(props). | No constructor required. |
| Often used for method binding. | No manual binding required. |
| Older React approach. | Modern and recommended approach. |
Suppose you are building an online learning platform.
A class component can use a constructor to initialize:
These values are stored in the component state before the application renders.
In modern React applications, the same functionality is typically implemented using useState() and useEffect().
The React Component API consists of methods and utilities that help developers create, update, and manage React components. These APIs control how components behave, update their state, and interact with the user interface.
In modern React development, many applications are built using Functional Components and Hooks. However, several Component API methods are still important when working with Class Components or maintaining older React projects.
This chapter covers the most commonly used Component API methods:
setState()forceUpdate()findDOMNode()The React Component API provides built-in methods that allow developers to:
Most Component API methods belong to Class Components.
setState() is the primary method used to update the state of a class component.
Whenever the state changes, React automatically re-renders the component and updates only the necessary parts of the user interface.
this.setState({
property: value
});
import React from "react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "Welcome to Sogdo Academy"
};
}
changeMessage = () => {
this.setState({
message: "Welcome to React Training"
});
};
render() {
return (
<div>
<h2>{this.state.message}</h2>
<button onClick={this.changeMessage}>
Update Message
</button>
</div>
);
}
}
export default App;
Output
Initially:
Welcome to Sogdo Academy
After clicking:
Welcome to React Training
When updating a value based on its current value, use the callback version of setState().
this.setState((previousState) => ({
count: previousState.count + 1
}));
This approach prevents issues caused by asynchronous state updates.
A callback can be executed after the state has been updated.
this.setState(
{
count: 5
},
() => {
console.log("State Updated");
}
);
this.state directly.setState() to update values.Incorrect
this.state.count = 10;
Correct
this.setState({
count: 10
});
forceUpdate() forces a class component to render again, even if its state or props have not changed.
Normally, React automatically updates components whenever state or props change. Therefore, manually forcing an update is rarely necessary.
this.forceUpdate();
import React from "react";
class RandomNumber extends React.Component {
refresh = () => {
this.forceUpdate();
};
render() {
return (
<div>
<h2>{Math.random()}</h2>
<button onClick={this.refresh}>
Generate Number
</button>
</div>
);
}
}
export default RandomNumber;
Each button click generates a new random number because the component is re-rendered.
Use it only in exceptional situations such as:
For normal applications, updating state with setState() is the recommended approach.
findDOMNode() was used to access the actual DOM element associated with a React component.
ReactDOM.findDOMNode(component);
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component {
highlight = () => {
const node = ReactDOM.findDOMNode(this);
node.style.backgroundColor = "lightyellow";
};
render() {
return (
<div>
<button onClick={this.highlight}>
Highlight
</button>
</div>
);
}
}
Modern React discourages using findDOMNode() because it:
For these reasons, new React applications should avoid using it.
Instead of findDOMNode(), use Refs.
Example using Functional Components:
import { useRef } from "react";
function App() {
const headingRef = useRef(null);
const changeColor = () => {
headingRef.current.style.color = "blue";
};
return (
<div>
<h2 ref={headingRef}>
Welcome to Sogdo Academy
</h2>
<button onClick={changeColor}>
Change Color
</button>
</div>
);
}
export default App;
This is the recommended approach in modern React.
| Method | Purpose | Recommended Today |
|---|---|---|
setState() | Updates component state. | Yes (Class Components) |
forceUpdate() | Forces a component to re-render. | Rarely |
findDOMNode() | Accesses the DOM element. | No (Deprecated) |
| Class Component API | Functional Component |
|---|---|
setState() | useState() |
| Lifecycle methods | useEffect() |
findDOMNode() | useRef() |
| Constructor | useState() |
setState() to update component state.forceUpdate() unless absolutely necessary.findDOMNode() in new projects.useRef() for accessing DOM elements.Consider an online learning portal.
A course enrollment page may use:
This approach keeps the application responsive and aligned with modern React development practices.
eact component goes through a series of stages from creation until it is removed from the application. These stages are known as the React Component Lifecycle.
Understanding the lifecycle helps developers know when to initialize data, call APIs, update the UI, and clean up resources.
Note: Lifecycle methods are available only in Class Components. In modern React, Functional Components with Hooks (
useEffect) are the recommended approach.
A React component passes through four major phases:
This is the starting stage of a component before it is displayed in the browser.
During this phase React:
The constructor is mainly used to:
constructor(props) {
super(props);
this.state = {
message: "Welcome to Sogdo Academy"
};
}The mounting phase begins when the component is inserted into the DOM and becomes visible on the screen.
Initializes the component.
Returns the JSX that will be displayed.
Runs only once after the component is rendered.
Common uses:
Example
componentDidMount() {
console.log("Component Mounted");
}Whenever State or Props change, React updates the component.
Determines whether the component should re-render.
Returns:
true → Update componentfalse → Skip renderingRuns after every successful update.
Common uses:
Example
componentDidUpdate(prevProps, prevState) {
console.log("Component Updated");
}Note: Older methods like
componentWillReceiveProps()andcomponentWillUpdate()are deprecated and should not be used in modern React applications.
The unmounting phase occurs when a component is removed from the DOM.
This method is used to clean up resources before the component is destroyed.
Common uses:
Example
componentWillUnmount() {
console.log("Component Removed");
}constructor()
│
▼
render()
│
▼
componentDidMount()
│
(State / Props Change)
│
▼
shouldComponentUpdate()
│
▼
render()
│
▼
componentDidUpdate()
│
(Component Removed)
│
▼
componentWillUnmount()import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
message: "Welcome to Sogdo Academy"
};
}
componentDidMount() {
console.log("Component Mounted");
}
updateMessage = () => {
this.setState({
message: "React Lifecycle Updated Successfully"
});
};
shouldComponentUpdate() {
return true;
}
componentDidUpdate() {
console.log("Component Updated");
}
componentWillUnmount() {
console.log("Component Removed");
}
render() {
return (
<div>
<h2>{this.state.message}</h2>
<button onClick={this.updateMessage}>
Update Message
</button>
</div>
);
}
}
export default App;Modern React applications primarily use Functional Components with the useEffect() Hook instead of lifecycle methods.
Example
import { useEffect } from "react";
function App() {
useEffect(() => {
console.log("Component Mounted");
return () => {
console.log("Component Unmounted");
};
}, []);
return <h2>Welcome to Sogdo Academy</h2>;
}
export default App;The React Component Lifecycle is the sequence of stages that a component goes through from creation until it is removed from the DOM.
componentDidMount()
componentWillUnmount()
shouldComponentUpdate()
useEffect()