I'm always excited to take on new projects and collaborate with innovative minds.

Mail

academy@sogdo.com

Website

https://academy.sogdo.in/

React Js Tutorial

Sogdo Academy

Introduction to React

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:

  • Single Page Applications (SPAs)
  • Progressive Web Applications (PWAs)
  • Enterprise Web Applications
  • Dashboard Applications
  • Mobile applications using React Native

React works efficiently by updating only the parts of the user interface that actually change, resulting in excellent performance and a smooth user experience.

 

Key Features of React

1. JSX (JavaScript XML)

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.

Benefits

  • Easier to understand
  • Reduces development time
  • Improves code readability
  • Simplifies UI creation

Although JSX looks like HTML, it is converted into JavaScript by tools such as Babel during the build process.


2. Component-Based Architecture

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.

Types of Components

  • Functional Components (Recommended)
  • Class Components (Legacy)

Using reusable components helps developers write cleaner, modular, and maintainable applications.

 

3. Virtual DOM

React improves performance using a Virtual DOM.

Instead of updating the entire webpage whenever data changes, React:

  1. Creates a virtual copy of the DOM.
  2. Compares the previous and updated versions.
  3. Identifies only the modified elements.
  4. Updates only those elements in the actual browser DOM.

Advantages

  • Faster rendering
  • Reduced browser operations
  • Better application performance
  • Improved user experience

 

4. One-Way Data Flow

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.

Benefits

  • Better control over application state
  • Easier debugging
  • Cleaner architecture
  • Improved maintainability

 

5. Server-Side Rendering (SSR)

React supports Server-Side Rendering through frameworks like Next.js.

With SSR, pages are rendered on the server before being sent to the browser.

Benefits

  • Faster initial page load
  • Improved SEO
  • Better performance on slower devices
  • Enhanced user experience

6. Easy Testing

React applications are structured in small, reusable components, making them easier to test independently.

Developers can verify:

  • UI rendering
  • Component behavior
  • State updates
  • User interactions

This results in more reliable and maintainable applications.

 

7. Developer-Friendly

React offers an excellent development experience through:

  • Reusable components
  • Clear project structure
  • Rich ecosystem
  • Excellent debugging tools
  • Strong community support

These features help developers build applications more efficiently.

 

8. Easy Learning Curve

Developers with knowledge of:

  • HTML
  • CSS
  • JavaScript

can begin learning React quickly.

The official documentation and large developer community make learning React accessible for both beginners and experienced professionals.

 

How React Works

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.

React Rendering Process

  1. Application state changes.
  2. React creates a new Virtual DOM.
  3. React compares it with the previous Virtual DOM.
  4. Only the changed elements are identified.
  5. React updates those specific elements in the browser.

This process, known as Reconciliation, significantly improves application performance.

 

Simple React Example

import React from "react";

function App() {
  return (
    <div>
      <h1>Welcome to Sogdo Academy React Tutorial</h1>
    </div>
  );
}

export default App;

Output

Welcome to Sogdo Academy React Tutorial

 

Organizations Using React

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:

  • Meta
  • Instagram
  • Netflix
  • WhatsApp
  • Dropbox
  • GitHub
  • Reddit
  • Khan Academy
  • Codecademy
  • Microsoft Outlook Web
  • GoDaddy
  • Bitbucket

The widespread adoption of React demonstrates its reliability, scalability, and long-term industry relevance.

 

Why Learn React?

React has become one of the most sought-after front-end technologies in modern web development.

High Industry Demand

Thousands of companies use React for production applications, creating excellent career opportunities.

Reusable Components

Developers can build components once and reuse them throughout the application.

Excellent Performance

The Virtual DOM minimizes unnecessary rendering and improves application speed.

Strong Community

React has one of the largest developer communities, providing extensive learning resources and open-source libraries.

Easy Integration

React integrates easily with REST APIs, GraphQL, Node.js, TypeScript, Redux, Firebase, and many other technologies.

Cross-Platform Development

By learning React, developers can also move into mobile application development using React Native.

 

Advantages of React

  • Component-based architecture
  • High performance with Virtual DOM
  • Reusable UI components
  • Declarative programming model
  • Predictable one-way data flow
  • Easy integration with modern tools
  • SEO support through Server-Side Rendering
  • Large ecosystem and community
  • Simplified debugging
  • Easy testing
  • Scalable project structure
  • Strong industry adoption

 

Conclusion

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.

 

 

What is React?

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.


React in MVC Architecture

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.

MVC Responsibilities

  • Model – Manages application data and business rules.
  • View – Displays the user interface using React.
  • Controller – Processes user requests and coordinates communication between the Model and View.

This separation of responsibilities helps developers build well-organized and maintainable applications.


Components in React

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:

  • Navigation bar
  • Login form
  • Product card
  • Search box
  • Footer
  • Dashboard widget

Components can be combined together to create complex applications while keeping the code modular and easy to maintain.

Advantages of Components

  • Reusable across multiple pages
  • Easier maintenance
  • Better code organization
  • Faster development
  • Simplified testing

Virtual DOM

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:

  1. Creates an updated Virtual DOM.
  2. Compares it with the previous Virtual DOM.
  3. Detects exactly what has changed.
  4. Updates only the affected elements in the real browser DOM.

This intelligent update process minimizes unnecessary rendering and significantly improves application performance.


Creating a React Application

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:

  • Header
  • Navigation Menu
  • Input Fields
  • Labels
  • Buttons
  • Validation Messages
  • Footer

Each component performs a specific task and can be reused throughout the application. This modular approach makes development faster and future updates much easier.


Why React Is So Popular

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:

  • Simple component-based architecture
  • Excellent rendering performance
  • Large developer community
  • Strong ecosystem of libraries
  • Easy integration with modern backend technologies
  • Frequent updates and long-term industry adoption

React is widely used for building enterprise applications, business dashboards, e-commerce platforms, social media applications, and many other modern web solutions.


Limitations of Traditional DOM Updates

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:

  • Slower page updates
  • Increased memory usage
  • Reduced application performance
  • Less responsive user interfaces

As applications grow in size and complexity, these limitations become more noticeable.


How React Improves Performance

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.


Understanding the React Virtual DOM

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.


Benefits of Using React

React offers numerous advantages for modern web development.

High Performance

The Virtual DOM minimizes unnecessary browser updates, resulting in faster rendering.

Reusable Components

Developers can create components once and reuse them across different parts of the application.

Easier Maintenance

A modular code structure makes applications easier to update, debug, and extend.

Better User Experience

Efficient rendering provides smoother interactions and faster page updates.

Scalable Architecture

React applications can grow from small projects to large enterprise systems without major architectural changes.

Rich Ecosystem

React integrates seamlessly with TypeScript, Node.js, Next.js, Redux, GraphQL, REST APIs, Firebase, and many other modern technologies.

 

Summary

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.

 

React Version History

Updated for Sogdo Academy

Introduction

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.


Evolution of React

The following timeline highlights the most significant milestones in React's development.

VersionRelease YearMajor Highlights
React 0.32013First public release introducing the React library and component-based architecture.
React 0.4 – 0.142013–2015Added 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 152016–2017Major rendering optimizations, improved SVG support, simplified DOM rendering, enhanced debugging, performance improvements, and deprecation of older APIs such as React.createClass.
React 16 (Fiber)2017One of the biggest React releases. Introduced the Fiber architecture, Error Boundaries, Fragments, Portals, improved rendering engine, and better error recovery.
React 16.3 – 16.82018–2019Added the new Context API, Profiler, React.lazy(), Suspense, and the revolutionary Hooks API (useState, useEffect, and others).
React 172020Focused on easier upgrades, improved event delegation, and better compatibility without introducing major API changes.
React 182022Introduced Concurrent Rendering, Automatic Batching, createRoot(), startTransition(), improved Suspense, and Streaming Server-Side Rendering (SSR).
React 19Modern ReleasesEnhanced Server Components, Actions, improved Forms, Metadata management, Asset Loading, and overall performance optimizations for modern applications.

Major Milestones in React

React 0.x (2013–2015)

The earliest React releases introduced the foundation of modern frontend development.

Key Features

  • Component-based architecture
  • Virtual DOM
  • JSX support
  • Initial Server-Side Rendering (SSR)
  • Event handling improvements
  • Better HTML and SVG support
  • ES6 class compatibility

These versions established React as a practical alternative to traditional frontend development approaches.


React 15

React 15 focused primarily on improving stability and rendering performance.

Major Improvements

  • Faster DOM rendering
  • Improved SVG compatibility
  • Better browser support
  • Cleaner rendering process
  • Enhanced developer warnings
  • Reduced memory usage
  • Better debugging tools

React 15 also marked the beginning of deprecating several legacy APIs in preparation for future versions.


React 16 (Fiber Architecture)

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.

Major Features

  • Fiber Architecture
  • Error Boundaries
  • React Fragments
  • React Portals
  • Improved rendering performance
  • Better handling of asynchronous rendering
  • Improved developer experience

Fiber became the foundation for many advanced React capabilities introduced in later versions.


React 16.8 – Introduction of Hooks

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.

Popular Hooks

  • useState()
  • useEffect()
  • useContext()
  • useReducer()
  • useMemo()
  • useCallback()
  • useRef()

Hooks quickly became the recommended approach for developing React applications.


React 17

React 17 was designed as a transition release.

Instead of introducing major new features, it focused on making upgrades between React versions easier.

Highlights

  • Improved event delegation
  • Easier migration process
  • Better compatibility between React versions
  • Internal performance improvements
  • Foundation for future releases

React 18

React 18 introduced several advanced rendering capabilities that significantly improved application responsiveness.

Major Features

Concurrent Rendering

Allows React to prepare multiple UI updates without blocking user interactions.

Automatic Batching

Multiple state updates are automatically grouped together, reducing unnecessary re-rendering.

New Root API

Introduced:

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);

This replaces the older ReactDOM.render() method.

Transitions

Developers can mark non-urgent updates using:

startTransition(() => {
  // State updates
});

This keeps applications responsive during complex rendering operations.

Improved Suspense

Better loading experiences for asynchronous components and data fetching.


React 19

The latest generation of React focuses on improving both developer productivity and application performance.

Important Features

  • Server Components
  • Actions
  • Simplified Form Handling
  • Built-in Metadata Management
  • Improved Asset Loading
  • Better Hydration
  • Faster Rendering
  • Enhanced Server-Side Rendering
  • Improved Developer Experience

React 19 continues to reduce boilerplate code while making full-stack React development simpler.


Why Understanding React Versions Matters

Learning React's evolution helps developers:

  • Understand why modern APIs exist.
  • Identify deprecated features.
  • Write applications using current best practices.
  • Upgrade legacy projects confidently.
  • Prepare for React interviews.
  • Maintain compatibility across projects.

For most modern applications, developers should focus on React 18+ concepts while understanding earlier versions for maintaining legacy codebases.


Recommended React Version for Learning

For new learners, Sogdo Academy recommends starting with the latest stable React release.

Avoid learning deprecated concepts such as:

  • Class Components (unless maintaining older projects)
  • componentWillMount()
  • componentWillReceiveProps()
  • React.createClass()
  • Legacy Context API

Instead, focus on modern React development using:

  • Functional Components
  • Hooks
  • React Router
  • Context API
  • Custom Hooks
  • React 18+ Features
  • Server Components (advanced)
  • Modern project structures

 

 

React Environment Setup

Introduction

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.


Prerequisites

Before installing React, make sure the following software is available on your computer:

  • Node.js – Required to run JavaScript outside the browser and install React packages.
  • npm (Node Package Manager) – Comes with Node.js and is used to install project dependencies.
  • React – The JavaScript library used to build user interfaces.
  • React DOM – Connects React components to the browser's HTML page.
  • Code Editor – Visual Studio Code is recommended because it provides excellent support for React development.
  • Web Browser – Google Chrome, Microsoft Edge, Firefox, or any modern browser.

Note: In modern React development, tools such as Vite automatically configure Webpack and Babel. Therefore, beginners usually do not need to configure them manually.


Ways to Install React

There are different ways to create a React project. The choice depends on your project requirements and the development approach you want to follow.

1. Using Vite (Recommended)

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:

  • Beginners
  • Students
  • Professional developers
  • Enterprise applications

Most modern React projects use Vite.


2. Using Create React App (CRA)

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.

 

React Create React App (CRA)

Introduction

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.


Why Use Create React App?

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:

  • Quick project setup
  • No manual configuration
  • Pre-configured Webpack and Babel
  • Development server with Hot Reload
  • Production-ready build support
  • Easy project structure for beginners

This allows developers to focus on writing React code instead of configuring development tools.


System Requirements

Before creating a React project, make sure the following software is installed on your computer.

  • Node.js (Latest LTS version recommended)
  • npm (Installed automatically with Node.js)

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.


Installing Create React App

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:

  • Creates a new React project
  • Downloads required dependencies
  • Configures the development environment
  • Generates the project structure

The installation may take a few minutes depending on your internet speed.


Open the Project

Move into the project directory.

cd my-react-app

Start the Development Server

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.


Default Project Structure

A newly created React project contains several important files and folders.

node_modules

Stores all third-party packages and project dependencies installed through npm.


public

Contains static files such as:

  • index.html
  • Images
  • Icons
  • Manifest file

The index.html file acts as the entry point where the React application is loaded.


src

This is the main development folder where most of your React code is written.

Common files include:

  • App.js
  • App.css
  • index.js
  • index.css

As your application grows, you can create additional folders such as:

  • components
  • pages
  • hooks
  • services
  • assets
  • utils

package.json

Contains project information, scripts, dependencies, and configuration details.


package-lock.json

Automatically generated by npm to ensure consistent dependency versions across different environments.


README.md

Contains documentation and project-related information.


Editing Your First React Component

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.


Creating Additional Components

As your application grows, avoid writing everything inside App.js.

Instead, create separate components such as:

  • Header
  • Footer
  • Navigation
  • Sidebar
  • Login Form
  • Dashboard

Import them into App.js to build modular and reusable applications.


Creating a Production Build

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.


Important Note

Although Create React App is still widely used in many existing applications, most new React projects now use Vite because it offers:

  • Faster project creation
  • Faster development server
  • Better performance
  • Smaller build size
  • Improved developer experience

Learning Create React App remains valuable because many enterprise applications continue to use it.

 

React Features

Updated for Sogdo Academy

Introduction

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.


Key Features of React

1. Component-Based Architecture

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.

Benefits

  • Reusable code
  • Better maintainability
  • Easy testing
  • Modular application structure

2. Virtual DOM

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.

Benefits

  • Faster rendering
  • Better performance
  • Reduced browser operations
  • Improved user experience

3. Declarative Programming

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.


4. JSX (JavaScript XML)

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.


5. One-Way Data Flow

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.

Advantages

  • Better control over application data
  • Easier debugging
  • Improved application architecture

6. Reusable Components

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.


7. Rich Ecosystem

React provides a large ecosystem of libraries and frameworks that extend its functionality.

Popular tools include:

  • React Router for navigation
  • Redux and Zustand for state management
  • Next.js for full-stack React applications
  • Axios for API communication
  • React Query for server state management

This ecosystem allows developers to build complete, production-ready applications.


8. Strong Community Support

React has one of the largest developer communities in the world.

Developers can easily find:

  • Documentation
  • Tutorials
  • Open-source libraries
  • Community forums
  • Technical articles
  • Video courses

A strong community ensures continuous improvements and quick solutions to common development challenges.


9. Server-Side Rendering (SSR)

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.

Benefits

  • Faster page loading
  • Improved Search Engine Optimization (SEO)
  • Better performance on slower devices
  • Enhanced user experience

10. Cross-Platform Development

React knowledge can also be used for mobile application development through React Native.

Using React Native, developers can build applications for:

  • Android
  • iOS

while sharing much of the same programming knowledge used for web development.


11. Developer Tools

React provides excellent debugging support through browser extensions such as React Developer Tools.

These tools allow developers to:

  • Inspect component hierarchies
  • View Props and State
  • Monitor application updates
  • Debug rendering issues
  • Analyze application performance

12. Hooks

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:

  • useState()
  • useEffect()
  • useContext()
  • useReducer()
  • useMemo()
  • useCallback()
  • useRef()

Hooks simplify React development and are now the recommended approach for building applications.


13. Context API

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:

  • User authentication
  • Theme settings
  • Language preferences
  • Global application data

This reduces unnecessary prop drilling and keeps code cleaner.


14. Immutable State

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.


15. Accessibility Support

React makes it easier to build applications that are accessible to all users, including those using assistive technologies.

Developers can improve accessibility by using:

  • Semantic HTML
  • ARIA attributes
  • Keyboard navigation
  • Screen reader support

Building accessible applications improves usability and follows modern web standards.


16. High Performance

React is designed to deliver excellent performance through features such as:

  • Virtual DOM
  • Efficient rendering
  • Automatic batching
  • Lazy loading
  • Code splitting
  • Memoization

These optimizations help applications remain responsive even as they grow in size and complexity.

 

 

Difference Between React and React Native

Introduction

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.

  • React is used for developing web applications that run in a web browser.
  • React Native is used for developing native mobile applications for Android and iOS.

Understanding the differences between React and React Native helps developers choose the right technology based on project requirements.


React vs React Native

FeatureReactReact Native
PurposeDevelops web applications.Develops native mobile applications.
PlatformRuns in web browsers.Runs on Android and iOS devices.
RenderingUses HTML and CSS to render the user interface.Uses native mobile UI components instead of HTML.
Programming LanguageJavaScript or TypeScript with JSX.JavaScript or TypeScript with JSX.
StylingCSS, CSS Modules, Tailwind CSS, Bootstrap, Styled Components, etc.Uses the built-in StyleSheet API or third-party styling libraries.
NavigationUses libraries such as React Router.Uses React Navigation or similar navigation libraries.
DOM SupportUses the Virtual DOM for efficient browser rendering.Does not use the browser DOM. It renders native mobile components.
PerformanceOptimized for web applications.Delivers near-native performance on mobile devices.
DeploymentDeployed to web servers or cloud hosting platforms.Published through the Google Play Store and Apple App Store.
Learning CurveEasier for web developers.Requires understanding of mobile application development concepts.

React

React is a JavaScript library used to build responsive and interactive user interfaces for websites and web applications.

It is commonly used to develop:

  • Single Page Applications (SPAs)
  • Business dashboards
  • E-commerce websites
  • Content management systems
  • Enterprise web applications
  • Progressive Web Applications (PWAs)

Advantages

  • Fast rendering with Virtual DOM
  • Component-based architecture
  • Large ecosystem
  • Strong community support
  • Easy integration with backend technologies

React Native

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:

  • Social media apps
  • Food delivery apps
  • Banking applications
  • Healthcare applications
  • E-commerce mobile apps

Advantages

  • Single codebase for Android and iOS
  • Near-native performance
  • Reusable components
  • Faster mobile development
  • Access to native device features

Similarities Between React and React Native

Although React and React Native are used for different platforms, they share many common concepts.

  • Component-based architecture
  • JSX syntax
  • Functional Components
  • Hooks
  • State management
  • Props
  • Context API
  • JavaScript or TypeScript
  • Reusable code structure

Developers familiar with React can learn React Native more easily because many core concepts remain the same.


When Should You Choose React?

Choose React when you want to build:

  • Company websites
  • Business portals
  • Admin dashboards
  • E-commerce websites
  • Learning platforms
  • Web-based enterprise applications

When Should You Choose React Native?

Choose React Native when you want to build:

  • Android applications
  • iPhone applications
  • Cross-platform mobile apps
  • Business mobile applications
  • Social networking apps
  • Mobile commerce applications

Which One Should You Learn First?

For beginners, it is recommended to learn React first.

React helps you understand the core concepts such as:

  • Components
  • JSX
  • Props
  • State
  • Hooks
  • Event handling
  • API integration

After gaining confidence in React, learning React Native becomes much easier because it builds upon the same fundamentals.

 

 

React JSX

Introduction

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.


How JSX Works

When you write JSX, it is automatically converted into JavaScript function calls during the build process.

JSX Code

<div>Welcome to Sogdo Academy</div>

JavaScript Generated by Babel

React.createElement("div", null, "Welcome to Sogdo Academy");

The React.createElement() method creates a React element that React uses to build the user interface.


Why Use JSX?

JSX offers several advantages that simplify React development.

Improved Readability

JSX looks similar to HTML, making it easier to understand the structure of a component.

Less Code

Developers can create user interfaces with fewer lines of code compared to using JavaScript functions directly.

Better Developer Experience

Modern code editors provide syntax highlighting, auto-completion, formatting, and error detection for JSX.

JavaScript Integration

JavaScript expressions can be written directly inside JSX, allowing dynamic content to be displayed easily.

Easier Component Development

Since both UI and logic are written in the same file, components become easier to develop and maintain.


Writing Your First JSX

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.


Nested Elements

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 Attributes

JSX supports attributes similar to HTML, but some attribute names are different because JavaScript keywords cannot be used directly.

HTMLJSX
classclassName
forhtmlFor
tabindextabIndex
onclickonClick

Example:

function App() {
  return (
    <h1 className="title">
      Welcome to Sogdo Academy
    </h1>
  );
}

Using JavaScript Expressions

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:

  • Variables
  • Arithmetic calculations
  • Function calls
  • Object properties
  • Template literals

Example:

<h2>{20 + 30}</h2>

Output:

50

JSX Comments

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.


Inline Styling in JSX

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.


Conditional Rendering in JSX

JSX does not allow traditional statements like if...else directly inside the returned JSX.

Instead, developers commonly use:

  • Ternary Operator
  • Logical AND (&&)
  • Conditional rendering before the return statement

Example using the ternary operator:

function App() {
  const isLoggedIn = true;

  return (
    <h2>
      {isLoggedIn ? "Welcome Back!" : "Please Login"}
    </h2>
  );
}

Output:

Welcome Back!

JSX Rules

When writing JSX, remember the following rules:

  • Return only one parent element.
  • Close every HTML tag.
  • Use className instead of class.
  • Use htmlFor instead of for.
  • Write JavaScript expressions inside {}.
  • Component names should begin with an uppercase letter.
  • Style properties use camelCase.
  • Comments must be enclosed within {/* ... */}.

Following these rules helps avoid syntax errors and keeps your code clean.


Advantages of JSX

  • Easy to read and write
  • Simplifies UI development
  • Supports JavaScript expressions
  • Encourages reusable components
  • Improves developer productivity
  • Better error reporting during development
  • Excellent support in modern code editors

 

React Components

Introduction

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:

  • Header
  • Navigation Menu
  • Sidebar
  • Product Card
  • Login Form
  • Footer

Each component works independently but combines with other components to create a complete application.


What is a React Component?

A React component is a JavaScript function or class that returns JSX describing how a part of the user interface should appear.

Components can:

  • Display data
  • Accept user input
  • Handle events
  • Manage state
  • Reuse business logic
  • Communicate with other components

Think of components as building blocks. Just as a house is built using bricks, a React application is built using components.


Benefits of Components

Using components provides several advantages:

  • Code reusability
  • Better project organization
  • Easier maintenance
  • Faster development
  • Improved readability
  • Independent testing
  • Scalable application architecture

Types of React Components

React provides two ways to create components:

  1. Functional Components
  2. Class Components

Although both can be used, Functional Components are the recommended approach in modern React development.


Functional Components

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.

Example

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;

Functional Components with Props

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

Class Components

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.


Functional Components vs Class Components

FeatureFunctional ComponentClass Component
SyntaxSimple JavaScript functionES6 Class
Code LengthShort and cleanMore verbose
State ManagementUses HooksUses this.state
Lifecycle FeaturesUses Hooks like useEffect()Lifecycle methods
PerformanceLightweightSlightly heavier
Modern RecommendationRecommendedMostly used in legacy projects

For new applications, Functional Components should always be your first choice.


Creating Multiple Components

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.


Combining Components

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.


Component Naming Rules

When creating components, follow these guidelines:

  • Component names should start with an uppercase letter.
  • Keep each component focused on a single responsibility.
  • Store reusable components in a separate components folder.
  • Export components so they can be reused in other files.

Correct examples:

Header
Navbar
StudentCard
UserProfile
Dashboard

Incorrect examples:

header
navbar
studentcard

Best Practices

  • Create small and reusable components.
  • Avoid writing large components with multiple responsibilities.
  • Use Functional Components for new projects.
  • Pass data using props instead of global variables.
  • Keep component logic simple and readable.
  • Organize components into folders based on their purpose.
  • Reuse components whenever possible to reduce duplicate code.

 

 

React State

Introduction

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:

  • User information
  • Counter values
  • Form data
  • Theme settings
  • Shopping cart items
  • API response data
  • Loading status

What is State?

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.


Why Do We Need State?

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:

  • Increasing a counter
  • Showing or hiding content
  • Displaying login status
  • Updating search results
  • Changing themes
  • Displaying fetched data

State in Modern React

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.
  • Updating the state automatically refreshes the displayed count.

Understanding useState()

The useState() Hook returns an array containing two values.

const [value, setValue] = useState(initialValue);
  • value → Current state value.
  • setValue() → Function used to update the state.
  • initialValue → Default value when the component first loads.

Example:

const [name, setName] = useState("Sogdo Academy");

Updating State

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.


Example: Toggle Content

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 Can Store Different Types of Data

State is flexible and can store various data types.

String

const [name, setName] = useState("John");

Number

const [age, setAge] = useState(25);

Boolean

const [isLoggedIn, setIsLoggedIn] = useState(false);

Array

const [courses, setCourses] = useState([
  "React",
  "Java",
  "Spring Boot"
]);

Object

const [user, setUser] = useState({
  name: "Rahul",
  city: "Hyderabad"
});

State vs Regular Variables

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

State in Class Components

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.


Best Practices

  • Keep state as simple as possible.
  • Store only data that changes over time.
  • Always update state using the setter function.
  • Avoid directly modifying state.
  • Split large state objects into smaller pieces when appropriate.
  • Lift state to a parent component when multiple components need the same data.

 

React Props

Introduction

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.


What are Props?

Props are objects that contain values passed from a parent component to a child component.

They can be used to pass:

  • Text
  • Numbers
  • Boolean values
  • Arrays
  • Objects
  • Functions
  • React elements

Props help developers build flexible and reusable components that can display different content based on the values they receive.


Why Use Props?

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.

Benefits

  • Reusable components
  • Better code organization
  • Easy data sharing
  • Predictable data flow
  • Cleaner application structure

Passing 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

Using Multiple Props

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

Destructuring Props

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.


Default Props

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

Passing Different Data Types

Props can store different types of values.

String

<Profile name="Amit" />

Number

<Profile age={25} />

Boolean

<Profile isActive={true} />

Array

<Profile skills={["React", "Java", "Spring Boot"]} />

Object

<Profile user={{ name: "Rahul", city: "Hyderabad" }} />

Function

<Button onClick={handleClick} />

Props are Read-Only

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

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 vs State

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

Best Practices

  • Keep props simple and meaningful.
  • Use descriptive prop names.
  • Avoid passing unnecessary data.
  • Use destructuring for cleaner code.
  • Do not modify props inside a component.
  • Pass only the data a component actually needs.
  • Keep business logic in the parent component whenever possible.

Real-World Code Practice

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.

 

 

React Props Validation

Introduction

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.


Why Use Props Validation?

As applications grow, components receive data from multiple sources. Passing incorrect data types can cause rendering issues or runtime errors.

Props validation helps by:

  • Detecting incorrect data types
  • Improving code readability
  • Making components easier to maintain
  • Providing better documentation for component usage
  • Reducing bugs during development

Installing PropTypes

Modern React projects require the prop-types package.

npm install prop-types

Import it into your component:

import PropTypes from "prop-types";

Basic Props Validation

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.


Required Props

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 Props

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.


Common PropTypes Validators

ValidatorDescription
PropTypes.anyAccepts any data type.
PropTypes.stringString value.
PropTypes.numberNumeric value.
PropTypes.boolBoolean value.
PropTypes.arrayArray value.
PropTypes.objectObject value.
PropTypes.funcFunction.
PropTypes.elementReact element.
PropTypes.nodeAnything React can render, including text and elements.
PropTypes.symbolJavaScript 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.

Example: oneOf()

Restrict values to predefined options.

Button.propTypes = {
  variant: PropTypes.oneOf([
    "primary",
    "secondary",
    "danger"
  ])
};

Valid:

<Button variant="primary" />

Invalid:

<Button variant="blue" />

Example: oneOfType()

Allow multiple data types.

Profile.propTypes = {
  id: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ])
};

Both are valid:

<Profile id={101} />

<Profile id="101" />

Example: shape()

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

Example: arrayOf()

Ensure all array items are of the same type.

Course.propTypes = {
  topics: PropTypes.arrayOf(
    PropTypes.string
  )
};

Usage:

<Course
  topics={[
    "React",
    "Hooks",
    "JSX"
  ]}
/>

Custom Validation

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.


Complete Example

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

Best Practices

  • Validate important props during development.
  • Use isRequired for mandatory data.
  • Keep prop names descriptive.
  • Use shape() for object validation.
  • Use oneOf() for predefined values.
  • Use arrayOf() for arrays containing similar data.
  • Avoid overly complex custom validators unless necessary.

 

PropTypes vs TypeScript

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

 

React State vs Props

Introduction

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.

  • Props are used to pass data from a parent component to a child component.
  • State is used to store and manage data within a component that can change over time.

Understanding the difference between State and Props is essential for building scalable, reusable, and maintainable React applications.


What is State?

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.

Common Uses of State

  • Form input values
  • Counter values
  • Toggle buttons
  • Loading indicators
  • API responses
  • Shopping cart items
  • Theme switching

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;

What are Props?

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

State vs Props

FeatureStateProps
PurposeStores component data.Passes data between components.
OwnershipManaged by the component itself.Controlled by the parent component.
MutabilityMutable (can change).Immutable (read-only).
Updated ByComponent using state setter functions.Parent component.
Data FlowInternal to the component.Parent → Child.
Re-renderUpdating state re-renders the component.New props from parent trigger re-render.
ScopeLocal to one component.Shared with child components.
Typical UseDynamic UI and user interactions.Configuration and communication.

State Characteristics

  • Stores dynamic data.
  • Changes over time.
  • Managed inside the component.
  • Updated using setState() (Class Components) or useState() (Functional Components).
  • Causes the component to re-render.
  • Cannot be modified directly.

Example:

const [theme, setTheme] = useState("Light");

Props Characteristics

  • Passed from parent to child.
  • Read-only.
  • Cannot be modified by the receiving component.
  • Used to make components reusable.
  • Support one-way data flow.

Example:

<Card
  title="React Development"
  trainer="Sogdo Academy"
/>

State and Props Working Together

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

Real-World Example

Consider an online learning platform.

Parent Component

  • Stores course information.
  • Stores instructor details.
  • Stores enrollment count.

These values are stored in State.

Child Components

  • Course Card
  • Instructor Card
  • Student List

These components receive data using Props and display it.

This approach keeps the application organized and reusable.


When to Use State

Use State when:

  • Data changes frequently.
  • Users interact with the application.
  • Form values need updating.
  • API responses are stored.
  • UI elements need to refresh.
  • Managing loading or error states.

Examples:

  • Login forms
  • Counter application
  • Shopping cart
  • Theme switcher
  • Todo list

When to Use Props

Use Props when:

  • Passing data to child components.
  • Reusing components with different values.
  • Passing callback functions.
  • Configuring reusable UI elements.
  • Sharing static or parent-controlled data.

Examples:

  • Product cards
  • User profile cards
  • Navigation menus
  • Course cards
  • Dashboard widgets

Common Mistakes

Modifying Props

Incorrect:

props.title = "New Title";

Correct:

Update the value in the parent component and pass the updated prop.


Updating State Directly

Incorrect:

count = count + 1;

Correct:

setCount(count + 1);

Using State for Static Data

If a value never changes, pass it through props instead of storing it in state.


Best Practices

  • Store only changing data in State.
  • Keep State as small as possible.
  • Never modify Props directly.
  • Pass only required Props.
  • Lift State to the nearest common parent when multiple components need the same data.
  • Use descriptive names for both State variables and Props.
  • Keep data flow simple and predictable.

Quick Comparison

QuestionStateProps
Can it change?✅ Yes❌ No
Who owns it?Current componentParent component
Can child modify it?NoNo
Used for UI updates?✅ YesIndirectly
Makes components reusable?Partially✅ Yes
Stores local data?✅ Yes❌ No
Shares data with children?Indirectly✅ Yes

Similarities Between State and Props

Although State and Props have different purposes, they also share some similarities.

  • Both are JavaScript objects.
  • Both store data used by components.
  • Both influence how a component is rendered.
  • Both trigger component re-rendering when their values change.
  • Both help create dynamic user interfaces.
  • Both are essential for building React applications.

 

React Constructor

Introduction

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.


What is a Constructor?

A constructor is a method that runs automatically when a class component is created.

Its primary responsibilities include:

  • Initializing the component state.
  • Accessing incoming props.
  • Binding event handler methods.
  • Performing one-time setup before rendering.

Basic Syntax

class App extends React.Component {
  constructor(props) {
    super(props);

    // Initialization code
  }

  render() {
    return <h1>Welcome to Sogdo Academy</h1>;
  }
}

Why is 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().


Common Uses of Constructor

A constructor is mainly used for:

  • Initializing component state
  • Binding event handler methods
  • Performing one-time setup
  • Creating object instances required by the component

Initializing State

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.


Binding Event Handlers

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

Using Arrow Functions Instead

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.


Accessing Props Inside Constructor

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

Complete Example

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;

Is Constructor Mandatory?

No.

A constructor is only required when you need to:

  • Initialize state.
  • Bind event handlers.
  • Perform setup logic.

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

Can We Use Constructor in Functional Components?

No.

Functional components do not support constructors.

Instead, React Hooks provide the same functionality.

Class ComponentFunctional Component
ConstructoruseState()
Lifecycle setupuseEffect()

Example:

import { useState } from "react";

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

  return <h2>{count}</h2>;
}

Constructor Execution Order

When a class component is created, React executes the following steps:

  1. Constructor executes.
  2. State is initialized.
  3. Render method executes.
  4. Component is mounted to the DOM.

Flow:

Component Created
        │
        ▼
Constructor()
        │
        ▼
Initialize State
        │
        ▼
Render()
        │
        ▼
Component Mounted

Best Practices

  • Use constructors only in class components.
  • Always call super(props) before using this.
  • Keep constructor logic simple.
  • Initialize only essential state.
  • Prefer arrow functions over manual binding when possible.
  • Avoid performing API calls inside constructors. Use lifecycle methods such as componentDidMount() instead.
  • For new projects, prefer Functional Components with Hooks over class components.

Constructor vs 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.

Real-World Example

Suppose you are building an online learning platform.

A class component can use a constructor to initialize:

  • Student information
  • Selected course
  • Login status
  • Theme preference

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().

 

React Component API

Introduction

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

What is the React Component API?

The React Component API provides built-in methods that allow developers to:

  • Update component state
  • Re-render components
  • Access DOM elements (legacy)
  • Control component behavior

Most Component API methods belong to Class Components.


1. setState()

What is setState()?

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.

Syntax

this.setState({
  property: value
});

Example

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

Using Previous State

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.


Callback Function

A callback can be executed after the state has been updated.

this.setState(
  {
    count: 5
  },
  () => {
    console.log("State Updated");
  }
);

Best Practices for setState()

  • Never modify this.state directly.
  • Use setState() to update values.
  • Use the callback version when the new state depends on the previous state.
  • Keep state small and meaningful.

Incorrect

this.state.count = 10;

Correct

this.setState({
  count: 10
});

2. forceUpdate()

What is forceUpdate()?

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.

Syntax

this.forceUpdate();

Example

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.


When Should You Use forceUpdate()?

Use it only in exceptional situations such as:

  • Integrating older third-party libraries
  • Working with external data that React cannot detect
  • Legacy React applications

For normal applications, updating state with setState() is the recommended approach.


3. findDOMNode()

What is findDOMNode()?

findDOMNode() was used to access the actual DOM element associated with a React component.

Syntax

ReactDOM.findDOMNode(component);

Legacy Example

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

Why is findDOMNode() Deprecated?

Modern React discourages using findDOMNode() because it:

  • Breaks component encapsulation.
  • Does not work well with Strict Mode.
  • Is incompatible with some modern React features.
  • Has better alternatives.

For these reasons, new React applications should avoid using it.


Modern Alternative: useRef()

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.


Component API Comparison

MethodPurposeRecommended Today
setState()Updates component state.Yes (Class Components)
forceUpdate()Forces a component to re-render. Rarely
findDOMNode()Accesses the DOM element. No (Deprecated)

Modern React Equivalents

Class Component APIFunctional Component
setState()useState()
Lifecycle methodsuseEffect()
findDOMNode()useRef()
ConstructoruseState()

Best Practices

  • Use setState() to update component state.
  • Never modify state directly.
  • Avoid forceUpdate() unless absolutely necessary.
  • Do not use findDOMNode() in new projects.
  • Prefer useRef() for accessing DOM elements.
  • Build new applications using Functional Components and Hooks whenever possible.

Real-World Example

Consider an online learning portal.

A course enrollment page may use:

  • setState() to update the number of enrolled students.
  • forceUpdate() only in rare cases where an external library changes data outside React.
  • useRef() to automatically focus the search box when the page loads.

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.


React Lifecycle Phases

A React component passes through four major phases:

  1. Initial Phase
  2. Mounting Phase
  3. Updating Phase
  4. Unmounting Phase

1. Initial Phase

This is the starting stage of a component before it is displayed in the browser.

During this phase React:

  • Creates the component
  • Initializes state
  • Receives initial props

Common Method

constructor()

The constructor is mainly used to:

  • Initialize state
  • Bind event handlers
 
constructor(props) {
    super(props);

    this.state = {
        message: "Welcome to Sogdo Academy"
    };
}
 

2. Mounting Phase

The mounting phase begins when the component is inserted into the DOM and becomes visible on the screen.

Important Methods

constructor()

Initializes the component.

render()

Returns the JSX that will be displayed.

componentDidMount()

Runs only once after the component is rendered.

Common uses:

  • Fetch API data
  • Load user information
  • Start timers
  • Add event listeners

Example

 
componentDidMount() {
    console.log("Component Mounted");
}
 

3. Updating Phase

Whenever State or Props change, React updates the component.

Important Methods

shouldComponentUpdate()

Determines whether the component should re-render.

Returns:

  • true → Update component
  • false → Skip rendering

componentDidUpdate()

Runs after every successful update.

Common uses:

  • Compare previous values
  • Call APIs after updates
  • Update external libraries

Example

 
componentDidUpdate(prevProps, prevState) {
    console.log("Component Updated");
}
 

Note: Older methods like componentWillReceiveProps() and componentWillUpdate() are deprecated and should not be used in modern React applications.


4. Unmounting Phase

The unmounting phase occurs when a component is removed from the DOM.

componentWillUnmount()

This method is used to clean up resources before the component is destroyed.

Common uses:

  • Clear timers
  • Remove event listeners
  • Cancel API requests
  • Close WebSocket connections
  • Release allocated resources

Example

 
componentWillUnmount() {
    console.log("Component Removed");
}
 

React Lifecycle Flow

 
constructor()
        │
        ▼
render()
        │
        ▼
componentDidMount()
        │
(State / Props Change)
        │
        ▼
shouldComponentUpdate()
        │
        ▼
render()
        │
        ▼
componentDidUpdate()
        │
(Component Removed)
        │
        ▼
componentWillUnmount()
 

Complete Example

 
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 (Hooks)

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;
 

Interview Questions

What is the React Component Lifecycle?

The React Component Lifecycle is the sequence of stages that a component goes through from creation until it is removed from the DOM.


What are the four lifecycle phases?

  • Initial
  • Mounting
  • Updating
  • Unmounting

Which lifecycle method is used for API calls?

componentDidMount()


Which lifecycle method is used for cleanup?

componentWillUnmount()


Which lifecycle method controls re-rendering?

shouldComponentUpdate()


Which Hook replaces lifecycle methods in Functional Components?

useEffect()

 

 

 

 

 

 

54 min read
Jul 04, 2026
By Sogdo Academy
Share