Kavindu udara
SE Undergaduate
github-profile-image

All articles

Setting Up the Development Environment for React With Vite

1. Installing Node.js and npm

Node.js and npm (Node Package Manager) are prerequisites for creating and running React applications.

  1. Download and Install Node.js:
    • Visit the Node.js official website.
    • Download the LTS version for stability.
    • Follow the installation instructions for your operating system.
  2. Verify Installation:
    • Open a terminal and run the following commands:
node -v
npm -v
  • These commands will display the installed versions of Node.js and npm.

2. Setting up a React Project

  1. Install Vite Vite is a fast frontend build tool.
    • Open a terminal and run
npm create vite@latest my-react-app --template react
- Replace `my-react-app` with your desired project name.
  1. Navigate to the Project Directory:
cd my-react-app
  1. Install Dependencies Run the following command to install all the dependencies

Read more ⟶

Real World Examples of Apps Build With React

Application Description Key Features
Facebook Social media platform, React’s origin. News feed, notifications, live chat, real-time updates, and interactive UI.
Instagram Photo and video sharing platform owned by Meta. Stories, filters, reels, dynamic user feeds, and push notifications.
WhatsApp Web Web version of the popular messaging app. Real-time messaging, live updates, QR login, and responsive design.
Netflix Streaming platform for movies and TV shows. Dynamic user interface, personalized recommendations, and optimized streaming experiences.
Airbnb Marketplace for lodging, primarily short-term rentals. Interactive maps, real-time search results, and responsive layouts for booking accommodations.
Uber Ridesharing platform for booking cabs and delivery services. Live tracking, dynamic pricing, and real-time updates.
Pinterest Visual discovery engine for sharing ideas and inspirations. Infinite scrolling, dynamic pin recommendations, and smooth user interactions.
Slack Collaboration platform for messaging and workplace tools. Real-time messaging, file sharing, and integrated third-party tools.
Shopify E-commerce platform for businesses to create online stores. Dynamic dashboards, real-time inventory updates, and responsive store designs.
Discord Voice, video, and text communication platform for communities and gamers. Real-time messaging, custom UIs for servers, and seamless voice/video integration.
Dropbox Cloud storage platform for storing and sharing files. Interactive UI for file uploads, drag-and-drop functionality, and real-time collaboration tools.
Trello Project management tool for task organization. Drag-and-drop Kanban boards, real-time updates, and interactive UI elements.
Asana Task and project management application for teams. Real-time task tracking, dynamic boards, and visual project timelines.
BBC News website offering global and local news. Dynamic content updates, real-time notifications, and seamless video playback.
Medium Blogging platform for writers and readers. Interactive editor, personalized reading lists, and infinite scrolling for articles.
Khan Academy Online learning platform offering free courses and lessons. Interactive learning tools, real-time quizzes, and progress tracking.
GitHub (Front End) Code hosting platform for version control and collaboration. Interactive dashboards, real-time updates on pull requests, and code comparison tools.
CodeSandbox Online code editor for web development. Real-time collaborative editing, live previews, and seamless integration with GitHub.
Spotify (Web Player) Music streaming platform for discovering and playing music. Real-time search, dynamic playlists, and audio playback optimization.

These examples showcase React’s versatility in building scalable, interactive, and high-performing applications across various domains like social media, e-commerce, streaming, and productivity tools.

Read more ⟶

React Virtual DOM

  • The Virtual DOM (VDOM) is a lightweight in-memory representation of the real DOM.
  • React uses the VDOM to manage updates efficiently without directly manipulating the real DOM.

Key Concepts

  • The actual structure rendered in the browser.
  • Updating it is slow because it triggers reflows and repaints.

How the Virtual DOM Works

  • Initial Render:
    • React creates a VDOM representation of the UI.
    • The VDOM is then used to create the real DOM for the browser.
  • Updating State or Props:
    • React creates a new VDOM tree based on the updated state/props.
    • It compares the new VDOM tree with the previous one (a process called diffing).
    • Only the differences (changes) are applied to the real DOM.
  • Efficient Updates:
    • React batches multiple updates and applies them in one operation to minimize performance costs.

Benefits of the Virtual DOM

  • Performance:
    • Reduces direct interactions with the real DOM.
    • Optimizes updates by calculating the smallest number of changes.
  • Declarative UI:
    • Developers focus on what the UI should look like, and React handles how to update the DOM.
  • Cross-Browser Compatibility:
    • React abstracts browser-specific quirks in DOM manipulation.

Real-Life Analogy

  • Think of updating the DOM like editing a book.
  • Instead of rewriting the entire book (real DOM), React keeps a draft copy (virtual DOM), compares the draft with the original, and only updates the changed parts.

Virtual DOM Diffing Algorithm

  • Tree Comparison: React compares the new VDOM tree with the old one.
  • Key-Based Optimization:
    • Keys in lists help React identify moved or updated elements efficiently.
  • Minimal Updates:
    • React calculates and applies only the minimal required changes to the real DOM.

Example

function App() {
    const [count, setCount] = React.useState(0);

    return (
        <div>
            <p>Count: {count}</p>
            <button onClick={() => setCount(count + 1)}>Increment</button>
        </div>
    );
}

When the button is clicked:

Read more ⟶

React Reusable Components

  • Reusable components are building blocks of a React application designed to be reused in multiple places.
  • They promote modularity, maintainability, and efficiency.

Key Benefits

  • Code Reusability: Write once, use multiple times.
  • Consistency: Maintain consistent design and behavior across the app.
  • Ease of Maintenance: Updates to a component reflect across all its instances.
  • Efficiency: Reduces the need for duplicate code.

Best Practices for Creating Reusable Components

  • Single Responsibility Principle: Each component should have one clear purpose.
  • Props: Use props to make components configurable and dynamic.
  • Composition Over Inheritance: Combine smaller components to build larger ones.
  • Avoid Hardcoding: Parameterize data through props instead of hardcoding values.
  • Styling Flexibility: Use CSS modules, styled-components, or className props for flexible styling.
  • Granularity: Balance between too granular (many small components) and too monolithic (large components).

Examples of Reusable Components

  1. Button
const Button = ({ onClick, children, style }) => (
    <button onClick={onClick} style={style}>
        {children}
    </button>
);
  1. Input Field
const Input = ({ type, value, onChange, placeholder }) => (
    <input
        type={type}
        value={value}
        onChange={onChange}
        placeholder={placeholder}
    />
);
  1. Card
const Card = ({ children, style }) => (
    <div style={{ ...defaultStyle, ...style }}>
        {children}
    </div>
);

const defaultStyle = {
    border: "1px solid #ccc",
    padding: "10px",
    borderRadius: "5px",
};

Tips

  • Test Components: Ensure each component works in isolation.
  • Prop Validation: Use PropTypes or TypeScript for better validation and type safety.
  • Document Components: Add comments or maintain documentation to explain usage.

References

Read more ⟶

React Fundamentals

  1. Introduction

  2. Setting Up the Development Environment for React with Vite

    • Installing Node.js and npm.
    • Setting up a React Project.
    • Overview of the project folder structure.
  3. Understanding JSX / TSX

  4. Components in React

Read more ⟶