Home Blog Page 14

React Components: Functional vs Class-based

0

In React, components are the building blocks of your application. Initially, there were class-based components and functional components. However, with the introduction of Hooks in React 16.8, functional components became the recommended approach due to their simplicity and flexibility.

In this module, we will cover:

  • The basics of class-based and functional components
  • Key differences between them
  • How to manage state and side effects
  • Why functional components are now preferred

Class-based Components: The Traditional Approach

Class-based components were the original way to define components in React. They are ES6 classes that extend React.Component and can have lifecycle methods, state, and more.

Here’s an example of a basic class component:

import React, { Component } from 'react';

class MyClassComponent extends Component {
constructor(props) {
super(props);
this.state = {
message: 'Hello from class component!',
};
}

render() {
return <h1>{this.state.message}</h1>;
}
}

export default MyClassComponent;

Key Features of Class-based Components:

  • State is managed using the this.state object and updated with this.setState().
  • Lifecycle methods (e.g., componentDidMount, componentDidUpdate, componentWillUnmount) are used to perform actions during different phases of the component lifecycle.
  • More verbose and complex syntax due to class definitions and lifecycle methods.

Functional Components: The Modern Approach

Functional components, on the other hand, are simpler and typically involve just a function that returns JSX. They were initially stateless, but with the introduction of Hooks, functional components can now manage state, side effects, and perform other tasks previously possible only with class components.

Here’s an example of a functional component:

import React from 'react';

const MyFunctionalComponent = () => {
return <h1>Hello from functional component!</h1>;
};

export default MyFunctionalComponent;

Key Features of Functional Components:

  • Simpler syntax without the need for classes or lifecycle methods.
  • Initially stateless, but with Hooks, functional components can now manage state and side effects.
  • More concise and easier to understand, especially for smaller components.

Differences Between Class-based and Functional Components

FeatureClass-based ComponentsFunctional Components
SyntaxMore verbose, requires ES6 class syntaxSimpler, function-based syntax
State Managementthis.state and this.setState()useState Hook
Lifecycle MethodsAvailable via methods like componentDidMountManaged via useEffect Hook
PerformanceSlightly slower due to overhead of class methodsFaster due to simpler structure
UsageMostly legacy code nowPreferred in modern React development
Code ReadabilityCan be more complex and harder to followMore readable and easier to maintain

Managing State in Functional Components

In functional components, state is handled using the useState hook.

Example with useState:

import React, { useState } from 'react';

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

const increment = () => setCount(count + 1);

return (
<div>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
</div>
);
};

export default Counter;
  • useState(0) initializes the state with a value of 0.
  • count is the state variable, and setCount is the function used to update it.

Managing Side Effects in Functional Components

In class-based components, side effects (like fetching data) are managed using lifecycle methods. In functional components, you can achieve the same behavior using the useEffect hook.

Example with useEffect:

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

const FetchData = () => {
const [data, setData] = useState([]);

useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((data) => setData(data));
}, []); // Empty dependency array means this runs once, similar to componentDidMount

return (
<div>
{data.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
};

export default FetchData;
  • useEffect runs the code inside the callback function after the component renders.
  • The empty dependency array ([]) makes the effect run only once, like componentDidMount in class components.

Why Functional Components Are Preferred

  1. Simplicity: Functional components are easier to write and understand, especially when dealing with smaller or simpler UI elements.
  2. Hooks: With Hooks, functional components can now manage state, context, and side effects, which was previously only possible with class components.
  3. Better Performance: Functional components are typically faster because they have less overhead compared to class components, which require more boilerplate code.
  4. Better Code Organization: With hooks, you can logically group related state and effects together in a single function, making it easier to reuse logic across components.

When to Use Class Components

While functional components are the preferred approach in modern React development, there are still cases where you might need class components:

  • Working with legacy codebases that are built using class components.
  • When integrating with external libraries or APIs that require class components.
  • React Native uses class components in certain cases, though it has been shifting to functional components as well.

However, these cases are becoming increasingly rare as functional components with hooks are now the standard.


Summary

In this module, we’ve explored the key differences between class-based and functional components. Functional components are now the go-to method for building React apps due to their simplicity, better performance, and the power of Hooks.

In the next module, we’ll dive into React State and the useState Hook, where you will learn how to manage state in functional components, a core concept for building interactive applications.

JSX Deep Dive: Syntax, Logic Embedding, Gotchas

0

One of the key features of React is JSX (JavaScript XML), a syntax extension that allows us to write HTML-like code inside JavaScript. JSX makes React code more readable and expressive. However, to fully leverage it, it’s essential to understand its syntax, how logic can be embedded, and some common pitfalls developers encounter when using it.

In this module, we’ll explore:

  • What JSX is and how it works
  • Embedding JavaScript logic inside JSX
  • Common gotchas and best practices to avoid errors

What is JSX?

JSX is not a separate language. It’s a syntax extension for JavaScript that lets you write HTML-like code directly in JavaScript. This makes React components look more like the HTML you’re used to working with, but it’s still JavaScript under the hood.

For example, here’s a simple JSX expression:

const element = <h1>Hello, World!</h1>;

JSX gets compiled into JavaScript code by tools like Babel, transforming it into something like this:

const element = React.createElement('h1', null, 'Hello, World!');

The JSX syntax allows you to express the UI structure more clearly without manually calling React.createElement() for each DOM node.


JSX Syntax

Here are the essential syntax rules and features of JSX:

1. JSX is Expression Syntax

JSX is just syntactic sugar over React’s React.createElement() function. You can use JavaScript expressions inside JSX by enclosing them in curly braces {}.

const name = 'John';
const element = <h1>Hello, {name}!</h1>;

The expression inside {} will be evaluated and its result will be inserted into the JSX. This is how you embed dynamic content into the UI.

2. JSX Tags Must Be Closed

Unlike HTML, JSX tags must always be closed. If you’re using an empty tag (like <img /> or <input />), make sure to self-close it.

// Valid JSX
const imgElement = <img src="logo.png" alt="logo" />;

// Invalid JSX (missing closing tag)
const imgElement = <img src="logo.png" alt="logo">

3. JSX Attributes

JSX attributes are similar to HTML attributes but with a few differences:

  • class in HTML becomes className in JSX.
  • for in HTML becomes htmlFor in JSX.
  • You can pass dynamic values as well, similar to how JavaScript expressions work in JSX.
const button = <button className="btn-primary" htmlFor="inputId">Submit</button>;

Embedding JavaScript Logic in JSX

One of the most powerful features of JSX is its ability to embed JavaScript logic directly in the markup. You can use JavaScript expressions and control structures (like conditionals, loops) inside your JSX, but with certain syntax constraints.

1. Conditionals in JSX

You can use ternary operators for conditional rendering inside JSX. This is the most common approach to conditionally display elements:

const isLoggedIn = true;
const greeting = <h1>{isLoggedIn ? 'Welcome back!' : 'Please sign in'}</h1>;

Alternatively, short-circuit evaluation can be used for conditional rendering:

const showMessage = true;
const message = showMessage && <p>This is a conditional message</p>;

In this example, if showMessage is false, nothing will be rendered.

2. Loops in JSX (Rendering Lists)

To render lists of elements, you can use JavaScript’s .map() method. Ensure that each element in the list has a unique key prop to help React efficiently update the DOM.

const numbers = [1, 2, 3, 4, 5];
const numberList = (
<ul>
{numbers.map((number) => (
<li key={number}>{number}</li>
))}
</ul>
);

3. Function Calls and Expressions

You can also call functions inside JSX. However, remember that JSX can only evaluate expressions and cannot handle statements like if, for, or while.

function greetUser(name) {
return `Hello, ${name}`;
}

const element = <h1>{greetUser('John')}</h1>;

Common Gotchas in JSX

1. JSX is Case-Sensitive

JSX is case-sensitive. HTML elements are lowercase (<div />, <button />), but custom React components need to be capitalized.

// Correct
const MyComponent = () => <h1>Hello, World!</h1>;

// Incorrect
const myComponent = () => <h1>Hello, World!</h1>; // will not render

2. No class Attribute in JSX

As mentioned, class in HTML is replaced by className in JSX.

// Correct
const element = <div className="container"></div>;

// Incorrect
const element = <div class="container"></div>; // will cause an error

3. JSX Elements Need to Have One Parent Element

JSX elements must be wrapped in a single parent element. For example:

// Correct
const container = (
<div>
<h1>Hello</h1>
<p>Welcome to React</p>
</div>
);

// Incorrect
const container = (
<h1>Hello</h1>
<p>Welcome to React</p>
); // will throw an error

If you want to avoid unnecessary wrapping elements, React offers a Fragment shorthand (<>...</>) to group elements without introducing additional DOM nodes.

const container = (
<>
<h1>Hello</h1>
<p>Welcome to React</p>
</>
);

Best Practices for JSX

  • Always use className instead of class in JSX.
  • Always use htmlFor instead of for when working with form elements.
  • Use curly braces {} to embed JavaScript expressions within JSX.
  • Avoid side effects in JSX. Do not put imperative code (e.g., console.log(), or direct state mutations) inside JSX expressions.
  • Use fragments to avoid unnecessary wrapper divs and reduce DOM clutter.
  • Always ensure unique keys for list items to avoid rendering issues.

Summary

JSX is a powerful feature in React that allows you to write HTML-like code inside JavaScript. Understanding how to embed JavaScript logic and handle common pitfalls will help you write cleaner and more efficient code. In the next module, we will explore React Components: Functional vs Class-based, where you’ll learn how to define and manage components in React.

Setting Up Your First React Project (Vite, CRA, and Alternatives)

0

Before diving into React development, it’s essential to set up your environment properly. In this module, we’ll explore how to initialize a React project using modern tooling. While the traditional approach has been using Create React App (CRA), newer tools like Vite offer a faster, more efficient setup experience.

We will cover:

  • The limitations of CRA
  • Why Vite is the new standard
  • Step-by-step setup with Vite
  • Other alternatives such as Next.js and Parcel
  • Best practices for maintaining your project structure

Why Tooling Matters in React Development

React is only a library. To create an actual application, you need:

  • A bundler (e.g., Vite, Webpack)
  • A development server with hot reload
  • JSX support (compiled using Babel or esbuild)
  • Ability to manage static assets (CSS, images, etc.)

Good tooling reduces configuration overhead and improves your development experience with faster builds and better DX (Developer Experience).


Create React App (CRA): The Old Standard

Create React App has been the go-to tool for bootstrapping React projects since 2016. It abstracts away configuration using Webpack under the hood.

To create a project using CRA:

bashCopyEditnpx create-react-app my-app
cd my-app
npm start

Limitations of CRA:

  • Slow startup and build time in larger apps
  • Limited customization unless you eject
  • Uses older versions of Webpack and Babel
  • Heavier by default compared to modern tools

Due to these drawbacks, the React ecosystem is gradually shifting away from CRA.


Vite: The Modern Way to Build React Apps

Vite (pronounced veet) is a modern frontend build tool that offers:

  • Lightning-fast startup via native ES modules in development
  • Instant Hot Module Replacement (HMR)
  • Uses esbuild for faster compilation
  • Simple plugin system
  • Better defaults and minimal config

Setting Up a React Project with Vite

Make sure you have Node.js (version 14.18+, preferably 18+) installed.

  1. Create a new Vite-powered React app:
bashCopyEditnpm create vite@latest my-vite-app --template react
cd my-vite-app
npm install
npm run dev
  1. Project Structure: Vite generates a minimal and clean folder structure:
arduinoCopyEditmy-vite-app/
├─ public/
├─ src/
│  ├─ App.jsx
│  ├─ main.jsx
├─ index.html
├─ vite.config.js
  1. Hot Reloading is enabled by default, and the development server usually runs at http://localhost:5173.

Comparing CRA and Vite

FeatureCRAVite
Build ToolWebpackesbuild + Rollup
Start Time (Cold Boot)SlowFast
Hot Module ReloadingSlowerInstant
CustomizationRequires ejectingSimple via plugins
File BundlingIncludedFaster and leaner
Active DevelopmentDecliningRapidly growing

Vite is now recommended for most new projects unless your team has an existing Webpack setup or enterprise-specific tooling built on CRA.


Alternatives to CRA and Vite

1. Next.js

Ideal for building fullstack React apps with SSR (Server-Side Rendering), routing, and API support built-in. Useful if you plan to scale into a fullstack architecture.

bashCopyEditnpx create-next-app my-next-app

2. Parcel

Zero-config bundler with fast builds and auto installation of dependencies. Good for small-to-medium projects.

bashCopyEditnpx parcel index.html

3. React + Webpack (Manual)

If you want complete control, you can configure React manually with Webpack, Babel, and custom loaders. This approach is not recommended for beginners.


Best Practices for Project Setup

  • Use Vite for new frontend-only React apps
  • Use Next.js for fullstack React applications
  • Follow a modular folder structure (components/, pages/, utils/)
  • Keep src/ as the main directory for all source files
  • Use environment variables via .env files (VITE_API_KEY in Vite)

Summary

Setting up your React environment with the right tooling is foundational for a productive development experience. While Create React App served well in the past, Vite has emerged as the new standard due to its speed, simplicity, and modern architecture.

In the next module, we’ll dive into JSX and the Virtual DOM, the very building blocks of React development.

React vs Angular, Vue, and Svelte – A Comprehensive Comparison

0

As a modern frontend developer, understanding the ecosystem of JavaScript frameworks and libraries is essential. While React is one of the most widely used solutions, it is not the only one. Alternatives like Angular, Vue, and Svelte offer different approaches and philosophies to building user interfaces.

This module will compare React with Angular, Vue, and Svelte across various criteria including learning curve, architecture, performance, community support, and use cases. By the end of this module, you will have a clear understanding of what makes React unique and why you might choose it over other options.


Overview of the Frontend Landscape

The modern frontend landscape is dominated by a few key players:

  • React – A JavaScript library for building component-based UIs. Maintained by Meta.
  • Angular – A full-fledged framework developed by Google. Includes everything out of the box.
  • Vue.js – A progressive framework that combines the best features of Angular and React.
  • Svelte – A newer compiler-based framework that converts components to highly optimized JavaScript at build time.

Each has its own philosophy, use cases, and trade-offs.


React: A Library, Not a Framework

React is fundamentally a UI library, not a full framework. It focuses solely on rendering the view layer and managing UI state. Other concerns such as routing, form validation, and state management are handled through external libraries like React Router, Redux, or Zustand.

This composable nature gives developers the freedom to choose their tools, but it also means there’s a learning curve in figuring out the best architectural choices for each project.

Key Characteristics:

  • Component-based architecture
  • Virtual DOM for efficient rendering
  • Hooks for managing state and lifecycle
  • Backed by Meta and a massive open-source community

Angular: The Complete Framework

Angular is a comprehensive framework developed by Google. It includes everything you need to build a large-scale enterprise-grade application right out of the box—routing, form management, HTTP client, testing utilities, and more.

Key Characteristics:

  • TypeScript-first (not optional)
  • Opinionated structure and strong conventions
  • Two-way data binding
  • Dependency injection built-in
  • Steeper learning curve, especially for beginners

Angular is often used in enterprise environments that require standardization and long-term support.


Vue.js: The Progressive Framework

Vue provides a middle ground between React’s flexibility and Angular’s completeness. It is designed to be incrementally adoptable, meaning you can use as little or as much of it as you need.

Key Characteristics:

  • Simple and clean syntax
  • Optional use of JSX or template syntax
  • Two-way data binding (like Angular)
  • Reactive core based on composition API
  • Vibrant ecosystem including Vue Router and Vuex

Vue is often praised for its ease of use and quick learning curve, making it popular among solo developers and startups.


Svelte: The Compiler-Based Approach

Svelte takes a radically different approach by shifting much of the work to build time. Instead of using a virtual DOM, Svelte compiles components into highly optimized JavaScript at build time, resulting in faster runtime performance and smaller bundle sizes.

Key Characteristics:

  • No virtual DOM
  • Truly reactive variables
  • Simplified syntax with less boilerplate
  • Smaller bundles, faster runtime performance
  • Excellent for performance-critical apps

Although it has a smaller community and ecosystem compared to React, Svelte is gaining traction for projects where speed and simplicity are top priorities.


Feature Comparison Table

FeatureReactAngularVue.jsSvelte
TypeLibraryFrameworkFrameworkCompiler
LanguageJavaScriptTypeScriptJavaScriptJavaScript
Learning CurveModerateSteepEasyEasy
Virtual DOMYesYesYesNo
Reactivity ModelHooksObservablesReactivity APICompiler-based
PerformanceGoodGoodGoodExcellent
Community SupportVery LargeLargeMedium-LargeGrowing
Ecosystem FlexibilityHighLowMediumMedium
Enterprise AdoptionHighVery HighMediumLow

When Should You Use React?

React is an excellent choice when:

  • You want flexibility in choosing your architecture and libraries
  • You are building highly interactive UIs or SPAs
  • You plan to scale from small to large applications
  • You need a huge ecosystem of tools, packages, and community support
  • You want access to full-stack frameworks like Next.js and React Native

Summary

React stands out due to its flexibility, modularity, and large ecosystem. While Angular provides an all-in-one framework and Vue offers a balance of ease and power, React’s composability and community momentum make it a compelling choice for most modern web projects. Svelte is an exciting new player that brings cutting-edge performance optimizations but is still maturing.

Understanding these differences will help you make informed decisions when building or contributing to frontend applications. In the next module, we will walk through the process of setting up your first React project using modern tooling such as Vite and alternatives to Create React App.

What is React? The Past, Present, and Future of UI Development

0

React is one of the most popular JavaScript libraries in the world. Developed and maintained by Meta (formerly Facebook), it has revolutionized how developers build user interfaces for web and mobile applications. But what exactly is React, why was it created, and where is it headed?

Let’s unpack React from its core philosophy to its future roadmap.


What is React?

React is an open-source JavaScript library used for building component-based user interfaces (UIs), especially for single-page applications (SPAs). It allows developers to create reusable UI components that can efficiently update and render as your data changes.

React’s core idea: Build encapsulated components that manage their own state, then compose them to make complex UIs.

Why Was React Created?

Before React, developers mostly relied on templating engines like jQuery, Mustache, and Handlebars. These tools manipulated the DOM (Document Object Model) directly, which became slow and buggy as apps grew in complexity.

React introduced:

  • A Virtual DOM that improves performance by only updating what’s necessary
  • A declarative approach that makes code predictable and easier to debug
  • Component-based architecture to help split UI into manageable parts

A Brief History of React

  • 2011: React was developed internally at Facebook to power features like the Facebook news feed.
  • 2013: React was open-sourced at JSConf US.
  • 2015: React Native was introduced for mobile development.
  • 2017: Introduction of React Fiber, a complete rewrite of React’s core.
  • 2019+: The introduction of Hooks (useState, useEffect) revolutionized how we write components.
  • 2022+: React Server Components and concurrent rendering are shaping the future of performance-driven apps.

What Can You Build with React?

React is not just for websites. With React and its ecosystem, you can build:

  • Single Page Applications (SPAs)
  • Progressive Web Apps (PWAs)
  • Cross-platform mobile apps with React Native
  • Desktop applications using Electron
  • Full-stack apps using frameworks like Next.js

Core React Concepts (Covered in This Course)

This course will take you from zero to hero by covering:

  • JSX and component fundamentals
  • State and lifecycle management
  • Hooks (useState, useEffect, useContext, etc.)
  • Routing and navigation
  • Form handling and APIs
  • Performance optimization
  • Real-world app architecture
  • Fullstack integration with Next.js

A Simple Example

Here’s a simple “Hello World” React component:

function HelloWorld() {
return <h1>Hello, React!</h1>;
}

And rendering it in your app:

import React from 'react';
import ReactDOM from 'react-dom/client';
import HelloWorld from './HelloWorld';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HelloWorld />);

This is the foundation—soon you’ll be building full-fledged apps!


The Future of React

React’s roadmap focuses on:

  • React Server Components for better performance
  • Concurrent rendering for responsive UIs
  • Integration with meta-frameworks like Next.js
  • Improved developer tooling (e.g., React DevTools, new compiler with Turbopack)

React is here to stay—and now is the best time to learn it.


Summary

React is a modern, flexible, and high-performance library that has reshaped front-end development. Whether you’re building a basic site or a production-grade application, React gives you the tools to succeed.

In the next module, we’ll compare React with Angular, Vue, and Svelte to understand when and why to use React in modern web projects.