Task Manager application: Load tasks from Rails API after login

In the last session we have completed the Login form implementation with conditional UI. We also covered Github Actions for Frontend CI. Now Let’s move on to loading tasks, creating and deleting task actions.

Load tasks from the Rails API

We’ll now connect the React UI to the authenticated Tasks API.

Let’s do this in small steps:

  1. Fetch the logged-in user’s tasks using the access token.
  2. Display the returned tasks in TaskList.
  3. Load the selected task’s details.
  4. Later, implement create, edit and delete.

Step 1: Check our existing Task type

export type Task = {
  id: number,
  title: string,
  description: string,
  status: TaskStatus,
  created_at: string,
  updated_at: string
}

Step 2: Verify the API response

# api/v1/tasks_controller.rb
def index
    tasks = current_user.tasks.order(created_at: :desc)

    render json: TaskBlueprint.render_as_hash(
      tasks,
      root: :data
    ), status: :ok
  end

# backend/app/blueprints/task_blueprint.rb
class TaskBlueprint < Blueprinter::Base
  identifier :id

  fields :title, :description, :status, :created_at, :updated_at
end

Now we know the exact response structure. Because you use root: :data, the Tasks API returns a response like this:

{
  "data": [
    {
      "id": 1,
      "title": "Learn React",
      "description": "Practice React hooks",
      "status": "pending",
      "created_at": "...",
      "updated_at": "..."
    }
  ]
}

The current_user.tasks scope also ensures that the endpoint returns only the logged-in user’s tasks.

Step 3: Create taskService.ts

Let’s create a service responsible for fetching tasks. Create: frontend/src/features/tasks/services/taskService.ts

For this first step, add a function that makes the authenticated GET request:

import type { Task } from "../types/task";

interface TaskResponse {
  data: Task[]
}

export async function fetchTasks(accessToken: string): Promise<Task[]> {

  const response = await fetch(import.meta.env['VITE_API_BASE_URL'] + "/api/v1/tasks", {
    method: "GET",
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + accessToken
    },
    credentials: 'include'
  });

  if(!response.ok) {
    throw new Error("Failed to load tasks");
  }

  const result: TaskResponse = await response.json();

  return result.data;
}

One small cleanup: for this GET request, we don’t need the Content-Type header or credentials: 'include'. The endpoint uses JWT authentication through the Authorization header. Keep credentials: 'include' in the login and refresh requests where cookies are required.

1. Authorization header Authorization: Bearer ${accessToken}. This sends the JWT to Rails. Your BaseController can then verify it and identify the current user.

2. Response type

type TasksResponse = {
data: Task[];
};

This represents the JSON structure returned by your TaskBlueprint.

3. Return only the tasks return result.data;

The component needs the task array, not the entire API response.

Fetch tasks in App.tsx

We’ll use React’s useEffect to fetch tasks automatically after a successful login.

1. Update your React import: import { useEffect, useState } from "react";
2. Import the service: import { fetchTasks } from "./features/tasks/services/taskService";

3. Add this effect inside App, alongside your existing state declarations:

useEffect(() => {
    async function loadTasks() {
      if (!accessToken) return;

      try {
        const tasks = await fetchTasks(accessToken);
        setTasks(tasks);
      } catch (error) {
        console.log("Failed to load tasks: ", error);
      }
    }

    loadTasks();
  }, [accessToken]);

Understand what happens

  1. Initially, accessToken is null, so the effect does nothing.
  2. After login, setAccessToken updates the token.
  3. React runs the effect again because accessToken changed.
  4. fetchTasks() requests tasks from Rails.
  5. setTasks(tasks) updates the React state, and TaskList receives the new tasks through props.

Add this effect to App.tsx and test it.

Let’s implement Add Task incrementally, using your existing Fluent UI components and Rails API.

We’ll follow this flow:

  1. Clicking Add Task opens a form.
  2. The form accepts a title, description and status.
  3. React sends a POST request to Rails.
  4. On success, the new task appears in the task list.

We’ll start by verifying the backend API before writing the frontend code.

Step 1: Check the Rails create action

def create
    task = current_user.tasks.new(task_params)

    if task.save
      render json: TaskBlueprint.render_as_hash(
        task,
        root: :data
      ), status: :created
    else
      render_validation_errors(task)
    end
  end

Our create action confirms a few things:

  • Rails creates tasks through current_user.tasks, so the task is associated with the authenticated user.
  • On success, it returns HTTP 201 Created.
  • The response is wrapped inside a top-level data property.
  • Validation failures are handled by render_validation_errors(task).

Now we know exactly what the frontend needs to send. Our Rails controller expects this JSON structure because of params.require(:task):

{
  "task": {
    "title": "Learn React",
    "description": "Practice React forms",
    "status": "pending"
  }
}

Validation failures return:

{
  "errors": ["Title can't be blank"]
}

Add createTask() to taskService.ts

We’ll reuse the same service file that already contains fetchTasks().

Add this function below fetchTasks():

export async function createTask(params: CreateTaskParams, accessToken:string): Promise<Task> {
  const response = await fetch(import.meta.env['VITE_API_BASE_URL'] + "/api/v1/tasks", {
    method: "POST",
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + accessToken
    },
    body: JSON.stringify(params)
  });
  const result = await response.json();

  if(!response.ok) {
    throw new Error(result.errors?.join(", ") ?? "Failed to create task");
  }

  return result.data;
}

Why return Task?

Our Rails controller returns the newly created task under data. We return that task so React can add it to the existing task list without making another GET request.

Two small cleanup points

  • credentials: 'include' isn’t needed here because the Tasks API authenticates using the Bearer token, not a cookie.
  • Use result.errors?.join(", ") so the error handler doesn’t itself fail when the response has no errors property.

Step 1: Add state in App.tsx

Inside our App component, add:

const [showAddTaskForm, setShowAddTaskForm] = useState(false);

<AppHeader
  isAuthenticated={!!accessToken}
  onAddTaskClick={() => setShowAddTaskForm(true)}
/>

{accessToken && showAddTaskForm && (
  <main className="add-task-form">
    <h2>Add a new task</h2>
  </main>
)}

Step 2: Update AppHeader.tsx

Add the callback to our existing interface:

interface AppHeaderProps {
  isAuthenticated: boolean,
  onAddTask: (addTask: boolean) => void
}

<Button appearance="primary" onClick={() => props.onAddTask(true)}>
          Add Task
        </Button>

Create AddTaskForm.tsx

Let’s create a separate component rather than putting the form directly inside App.tsx. Create: frontend/src/features/tasks/components/AddTaskForm.tsx

For our first iteration, we’ll add just two fields: Title and Description. Use your existing Fluent UI components:

import { useState } from "react";
import { Button, Field, Input, Textarea } from "@fluentui/react-components";

interface AddTaskFormProps {
  onCancel: () => void;
}

function AddTaskForm(props: AddTaskFormProps) {
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const handleAddtask = () => {
  }

  return (
    <form onSubmit={handleAddtask}>
      <h2>Add a new task</h2>
      
                <Input
                  name="title"
                  value={title}
                  placeholder="Enter task title"
                  onChange={(e) => setTitle(e.target.value)} />
 
                <Textarea
                  name="description"
                  value={description}
                  placeholder="Enter task description"
                  rows={4}
                  onChange={(e) => setDescription(e.target.value)} />

      <Button type="button" onClick={onCancel}>
        Cancel
      </Button>
    </form>
  );
}

export default AddTaskForm;

Connect AddTaskForm to App.tsx

Currently, App.tsx still renders the placeholder heading instead of your new component.

import AddTaskForm from "./features/tasks/components/AddTaskForm";

{loggedIn && openAddForm && (
  <main className="add-task-form">
    <AddTaskForm />
  </main>
)}

Step 2: Add a Cancel button

Let’s allow the user to close the form. In AddTaskForm.tsx, add a prop:

AddTaskForm:
interface AddTaskFormProps {
  onCancel: () => void;
}

function AddTaskForm({ onCancel }: AddTaskFormProps) {

form:
<Button type="button" onClick={onCancel}>
  Cancel
</Button>

App:
<AddTaskForm onCancel={() => setOpenAddForm(false)} />

Convert the Add Form into a Pop up Box

App.tsx should manage the dialog’s visibility state, while AddTaskForm.tsx should own the dialog UI and form fields. The parent doesn’t need to know how Fluent UI Dialog works.

1. Update AddTaskForm.tsx

Add the Dialog components to your existing imports:


import { useState } from "react";
import {
  Dialog,
  DialogSurface,
  DialogBody,
  DialogTitle,
  DialogContent,
  Button,
  Textarea,
  Input,
  Field
} from "@fluentui/react-components";

interface AddTaskFormProps {
  open: boolean,
  onClose: () => void
}

function AddTaskForm(props: AddTaskFormProps) {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');

  const handleAddTask = () => {

  }

  return (
    <Dialog open={props.open} onOpenChange={(_, data) => { if (!data.open) props.onClose() }}>
      <DialogSurface>
        <DialogBody>
          <DialogTitle></DialogTitle>

          <DialogContent>
            <form className="add-task-form" onSubmit={handleAddTask}>
              <h2>Add a New Task</h2>

              <Field label="Task title" required>
                <Input
                  className="add-task-form__input"
                  name="title"
                  value={title}
                  placeholder="Enter task title"
                  onChange={(e) => setTitle(e.target.value)} />
              </Field>

              <Field label="Description">
                <Textarea
                  className="add-task-form__input"
                  name="description"
                  value={description}
                  placeholder="Enter task description"
                  rows={4}
                  onChange={(e) => setDescription(e.target.value)} />
              </Field>

              <div className="add-task-form__actions">
                <Button type="button" onClick={props.onClose}>
                  Cancel
                </Button>

                <Button type="submit" appearance="primary">
                  Add
                </Button>
              </div>
            </form>
          </DialogContent>
        </DialogBody>
      </DialogSurface>
    </Dialog>
  );
}

export default AddTaskForm;

2. Add CSS – Add this to your existing CSS file:

.add-task-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 350px;
  padding-top: 12px;
}

.add-task-form__input {
  width: 100%;
}

.add-task-form__actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 8px;
}

App.tsx:

{loggedIn && (
  <AddTaskForm
    open={openAddForm}
    onClose={() => setOpenAddForm(false)}
  />
)}

Why this design?

  • App.tsx: Controls when the dialog opens and closes.
  • AddTaskForm.tsx: Owns the Dialog, form fields and form behaviour.
  • AppHeader.tsx: Only triggers the Add Task action.

This keeps each component focused on its responsibility without adding unnecessary abstractions.

Implement Add Task functionality

We’ll connect our existing createTask() service to AddTaskForm.

The flow will be:

  1. Validate the title.
  2. Call createTask() with the form values and access token.
  3. Add the returned task to the existing tasks state in App.tsx.
  4. Close the dialog after successful creation.

We’ll also display Rails validation errors in the form instead of using browser alerts. Let’s connect the form to our existing createTask() API service.

We’ll keep the responsibilities simple:

  • AddTaskForm: Handles input values, submission, loading and errors.
  • App.tsx: Owns the task list and updates it when a task is created.
  • taskService.ts: Makes the API request.

Step 1: Pass the required props to AddTaskForm, Import the API service, Add loading and error states

The form needs the access token to call Rails and a callback to notify App.tsx when creation succeeds.

Inside AddTaskForm, alongside your existing title and description states, add: loading, error

1. Update AddTaskForm.tsx

import type { Task } from "../types/task";
import { createTask } from "../services/taskService";
...

interface AddTaskFormProps {
  open: boolean;
  accessToken: string;
  onClose: () => void;
  onTaskCreated: (task: Task) => void;
}
...

const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
...

function AddTaskForm({
  open,
  accessToken,
  onClose,
  onTaskCreated
}: AddTaskFormProps) {

2. Update App.tsx

Pass the token and callback:

{accessToken && (
  <AddTaskForm
    open={openAddForm}
    accessToken={accessToken}
    onClose={() => setOpenAddForm(false)}
    onTaskCreated={(task) => {
      setTasks((currentTasks) => [task, ...currentTasks]);
    }}
  />
)}

Why [task, ...currentTasks]?

It creates a new array with the newly created task at the beginning, followed by the existing tasks. This is important because React state should be updated immutably.

Step 3: Implement handleAddTask

Replace our empty function with:

const handleAddTask = async () => {
  setLoading(true);
  setError(null);

  try {
    const task = await createTask(
      {
        task: {
          title: title.trim(),
          description: description.trim() || null,
          status: "pending"
        }
      },
      accessToken
    );

    onTaskCreated(task);

    setTitle("");
    setDescription("");
    onClose();

  } catch (error) {
    setError(
      error instanceof Error ? error.message : "Failed to create task"
    );
  } finally {
    setLoading(false);
  }
};

Check our Add Task Functionality:

Task Manager application: Integrate React useState and component communication

We have completed integrating Fluent UI and adding the React components. We also modified UI by adding extra css. Now let’s make the application interactive. This is our first important React concept: state management using useState and communication between parent and child components.

Step 5.3 – React useState and component communication

Our objective:

When you click a task in the left panel, its details should appear in the right panel. The selected task should also be visually highlighted.

Read: https://react.dev/reference/react/useState

1. First understand why we need state

Currently, your App.tsx probably has something like:

<TaskList tasks={tasks} selectedTaskId={1} />

<TaskDetails task={tasks[0]} />

What’s the problem? We’re hardcoding the selected task ID and the task details. When someone clicks another task, React has no information telling it that the selected task has changed.

This is where useState comes in.

2. What is useState?

useState is a React Hook that allows functional components to store and update information between renders.

Syntax:

const [state, setState] = useState(initialValue);

Let’s understand the three parts.

PartMeaning
stateCurrent state value
setStateFunction to update the state
initialValueInitial state value

Example:

import { useState } from 'react';

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

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

Initially, count is 0. When you click the button:

  1. setCount(count + 1) requests a state update.
  2. React schedules a re-render.
  3. React calls the component again with the updated state.
  4. The UI displays the new count.

Important: Why not use a normal variable?

Consider:

let selectedTaskId = 1;

function selectTask(id: number) {
  selectedTaskId = id;
}

Changing this variable doesn’t tell React to render the component again. But:

const [selectedTaskId, setSelectedTaskId] = useState(1);

Calling setSelectedTaskId(2) requests a re-render.

Remember: State is React-managed component data. Changing state triggers a render when the new value differs from the previous one.

3. Where should we maintain selectedTaskId?

Look at our component structure:

App.tsx  (Parent)
│
├── TaskList.tsx
│     └── Displays all tasks
│
└── TaskDetails.tsx
      └── Displays selected task

Both children need to know which task is selected. Therefore, we should maintain selectedTaskId in their common parent: App.tsx. This concept is called lifting state up in React. React recommends keeping shared state in the closest common parent of the components that need it. React

4. Our implementation assignment – We’ll modify three files.

A. App.tsx – introduce useState

Import:

import { useState } from 'react';

Inside your App component, create:

const [selectedTaskId, setSelectedTaskId] =
  useState<number | null>(tasks[0]?.id ?? null);

Why number | null? Initially, we’ll select the first task. But eventually, our API might return an empty task list. In that case, null represents no selected task. Now derive the selected task:

const selectedTask =
  tasks.find(task => task.id === selectedTaskId) ?? null;

Important learning point: Don’t create another state variable for selectedTask. We already have the selected ID and the complete tasks array. The selected task can be derived from those values. Storing both would duplicate state unnecessarily.

Now pass these props:

<TaskList
  tasks={tasks}
  selectedTaskId={selectedTaskId}
  onSelectTask={setSelectedTaskId}
/>

<TaskDetails task={selectedTask} />

You need to add the callback prop to TaskList in the next section.

B. TaskList.tsx – communicate with parent

Currently your props interface probably looks like:

interface TaskListProps {
  tasks: Task[];
  selectedTaskId: number;
}

Modify it to include:

onSelectTask: (taskId: number) => void;

Let’s understand this TypeScript syntax.

(taskId: number) => void

It means:

  • Accept one argument named taskId.
  • Its type is number.
  • The function doesn’t return anything meaningful (void).

Now, when rendering each task, add an onClick handler. Conceptually:

onClick={() => onSelectTask(task.id)}

Also, use the existing selectedTaskId prop to apply the selected class. For example:

className={
  task.id === selectedTaskId
    ? 'task-list-item task-list-item--selected'
    : 'task-list-item'
}

Accessibility note: Make each selectable task a real button (type="button") or a keyboard-accessible Fluent UI control. Don’t rely on a clickable <div> alone. You can use a native button styled as a task row.

C. TaskDetails.tsx – receive updated task

You don’t need to introduce any new state in TaskDetails. It already receives:

interface TaskDetailsProps {
  task: Task | null;
}

Whenever the selected task changes in App.tsx, React passes the newly selected task to TaskDetails. That’s it.

5. Understand the complete data flow

This is the most important part of today’s exercise.

Notice something:

TaskList never directly modifies TaskDetails.

It communicates with its parent through a callback. The parent updates state and passes the new data to both children.

This is React’s one-way data flow.

6. An important useState concept: State is a snapshot

Consider:

function handleClick() {
  setSelectedTaskId(2);

  console.log(selectedTaskId);
}

We might expect the console to print 2. But it prints the old selected ID. Why?

React state behaves like a snapshot. Calling the setter schedules a future render; it doesn’t change the state variable inside the currently executing function. This is an important concept when working with asynchronous operations and event handlers.

Also, never do this:

selectedTaskId = 2; // Don't mutate state

Always use the setter.

7. Test our implementation

Run: npm run dev
npm run lint
npm run build

8. Needed one improvement

One improvement: I am using a clickable <div>. For keyboard accessibility, use a <button type="button"> for each selectable task, with aria-pressed reflecting its selected state. Reset its default button styling in CSS.

Now:

<div key={task.id} className={`task-list-item ${task.id === props.selectedTaskId
          ? 'task-list-item--selected'
          : ''
          }`} onClick={() => props.onSelectTask(task.id)}>
   .....
</div>

To

<button type="button"
          aria-pressed={task.id === props.selectedTaskId ? true : false}
          key={task.id}
          className={`task-list-item ${task.id === props.selectedTaskId
            ? 'task-list-item--selected'
            : ''
            }`}
     .....
</button>

To create an accessible toggle button in React, use a native <button> element with aria-pressed bound to a boolean state. This tells screen readers whether the button is currently active (“pressed”) or inactive (“not pressed”).

Example:

import { useState } from 'react';

export function MuteToggleButton() {
  const [isMuted, setIsMuted] = useState(false);

  return (
    <button
      type="button"
      aria-pressed={isMuted}
      onClick={() => setIsMuted((prev) => !prev)}
      className={isMuted ? 'btn-active' : 'btn-default'}
    >
      Mute
    </button>
  );
}

9. What we’ll learn next

Once you finish this exercise, we’ll move to another important React concept:

Step 5.4 – React useEffect and API data loading

We’ll replace our static task array with the actual Rails API.

Topics:

  1. What is useEffect?
  2. Why shouldn’t we call APIs directly inside the component body?
  3. Dependency arrays ([], [value], no dependency array).
  4. Loading and error states.
  5. Fetch API and asynchronous operations.
  6. Updating state using API responses.
  7. Effect cleanup and race conditions.
  8. Why React StrictMode may execute Effects twice in development.

We’ll initially use useEffect and useState, then migrate to TanStack Query to understand efficient server-state caching.

Quick code review

Our App.tsx is correct.

const [selectedTaskId, setSelectedTaskId] =
  useState<number | null>(tasks[0]?.id ?? null);

const selectedTask =
  tasks.find((task) => task.id === selectedTaskId) ?? null;

Two good decisions here:

  • App owns the shared selection state.
  • selectedTask is derived from existing state rather than maintained as another state variable.

Our TaskList props are also correctly typed.

Step 5.4 – Connect React with Rails: API client and Login

Before implementing useEffect for loading tasks, we need one missing piece: React must obtain an access token first.

Remember, our Rails endpoint is protected:

GET /api/v1/tasks
Authorization: Bearer

We cannot properly integrate task fetching without authentication. So we’ll first implement the frontend login flow. This also gives us practical experience with controlled forms, TypeScript API types and asynchronous requests.

1. Understand the frontend architecture

We’ll introduce two new responsibilities:


frontend/src/
│
├── features/
│   ├── auth/
│   │   ├── components/
│   │   │   └── LoginForm.tsx
│   │   ├── services/
│   │   │   └── authService.ts
│   │   └── types/
│   │       └── auth.ts
│   │
│   └── tasks/
│       └── components/
│
├── services/
│   └── api/
│       └── apiClient.ts
│
├── App.tsx
└── main.tsx

Why this separation?

FileResponsibility
apiClient.tsCommon HTTP communication
authService.tsAuthentication API operations
auth.tsAuthentication TypeScript contracts
LoginForm.tsxLogin UI and form state
App.tsxApplication-level authentication state

We’ll eventually reuse apiClient.ts for all Task APIs.

2. Configure the Rails API URL

Create: frontend/.env.local

Add: VITE_API_BASE_URL=http://localhost:3000

Why VITE_?

Vite exposes environment variables prefixed with VITE_ to frontend code through import.meta.env. These values are public. Never put JWT signing secrets, database passwords or other server-side secrets here.

Add .env.local to Git ignore if it isn’t already covered.

3. Create the API client

Create: mkdir -p src/services/api
touch src/services/api/apiClient.ts

Your API client should initially support:

  • HTTP requests using fetch.
  • JSON request headers.
  • Parsing JSON responses.
  • Sending cookies using credentials: "include".
  • Handling unsuccessful HTTP responses.
  • Supporting optional Bearer authentication.

Think about designing a reusable function that accepts:

url
options
accessToken (optional)

Why centralize this?

Without an API client, every component might independently implement headers, error handling and authentication.

We’ll eventually reuse it for GET, POST, PATCH and DELETE requests.

To fetch data from an API in React, you typically combine the native JavaScript fetch() API with the useState and useEffect hooks. Users on Stack Overflow agree that enclosing asynchronous API calls inside useEffect properly manages the component lifecycle and prevents infinite re-render loops.

4. Define authentication types

Create: src/features/auth/types/auth.ts

Our Rails login request expects:

{
  "login": {
    "email": "test@example.com",
    "password": "password@1"
  }
}

And the successful response is:

{
  "data": {
    "access_token": "eyJhbGciOi...",
    "token_type": "Bearer",
    "expires_in": 600,
    "user": {
      "id": 1,
      "email": "test@example.com"
    }
  }
}

Create TypeScript interfaces representing:

  1. Login request.
  2. Authenticated user.
  3. Login response.
  4. API error response.

Use export interface and export type appropriately.

5. Implement authService

Create: mkdir -p src/features/auth/services
touch src/features/auth/services/authService.ts

Add a login function.

It should:

  1. Accept email and password.
  2. Call POST /api/v1/auth/login.
  3. Send the nested login request body.
  4. Set Content-Type: application/json.
  5. Enable credentials: "include".
  6. Handle unsuccessful responses.
  7. Return the parsed login response.

Why credentials: "include"?

Our Rails backend sets the refresh token as an HttpOnly cookie. The browser must be allowed to accept this cookie from the cross-origin login response. The browser will automatically include the appropriate Origin header. Don’t try to manually set that header in React.

To handle login authentication with cookies in React using the native Fetch API, pass credentials: 'include' in your fetch options object. This tells the browser to accept Set-Cookie headers from the login response and send those cookies back on future cross-origin requests (such as when your React app runs on localhost:5173 and your backend API runs on localhost:3000).

Include credentials: 'include' in both your initial login POST request and any subsequent requests to protected routes.

6. Create LoginForm component

Create: mkdir -p src/features/auth/components
touch src/features/auth/components/LoginForm.tsx

Use Fluent UI components:

import {
  Button,
  Input,
  Field
} from '@fluentui/react-components';

Your login form should have:

  • Email input.
  • Password input.
  • Login button.
  • Loading state.
  • Error message.

Important React learning: Controlled components

Use useState for the email and password fields. For example, conceptually:
const [email, setEmail] = useState('');

Connect the state to the Fluent UI Input using:
value={email}
onChange={...}

Why? The input value becomes controlled by React state. Whenever the user types, the state updates. React then renders using the latest state.

Also, use the form’s onSubmit handler rather than relying exclusively on a button click. This supports keyboard submission using Enter.

1. Does useState cause a re-render on every character?

Yes. That’s exactly how a controlled React input is supposed to work.

Consider:

const [email, setEmail] = useState('');

<Input
  value={email}
  onChange={(_, data) => setEmail(data.value)}
/>

When you type hello@example.com, the sequence is:


User types "h"
    |
    v
onChange fires
    |
    v
setEmail("h")
    |
    v
React schedules re-render
    |
    v
LoginForm executes again
    |
    v
Input receives value="h"

The same happens for each subsequent character.

Is this good practice? Absolutely.

Controlled inputs are the standard React approach when you need to validate input, enable/disable buttons, display errors or submit form data.

React’s documentation also explains that controlled inputs update their state on each edit.

Does the entire application re-render?

No, and this is an important distinction. In our implementation:

App
│
├── AppHeader
│
└── LoginForm
    ├── Email Input
    ├── Password Input
    └── Login Button

Since the email and password states live inside LoginForm, typing causes LoginForm to render again. App doesn’t automatically re-render just because its child updates its own state. AppHeader also doesn’t need to re-render. This is precisely why we keep form state close to the component that needs it.

What if we have a very large component?

Imagine an entire dashboard containing 100 components, and we put the search input’s state at the dashboard root.

Every state update could cause unnecessary component work.

We can improve this by:

  • Keeping state close to where it’s used.
  • Splitting independent components.
  • Using React.memo when profiling identifies expensive child renders.
  • Using useDeferredValue for expensive results driven by a rapidly changing input.

2. What is React memory?

This is an important security and architecture concept.

Consider: const [accessToken, setAccessToken] = useState<string | null>(null);

Where is accessToken stored?

It is stored as React-managed state in the browser’s running JavaScript environment.

People commonly call this in-memory state.

It is not a browser storage API like localStorage or sessionStorage.

React maintains state across component renders, even though the component function executes again. Read: https://react.dev/learn/state-as-a-snapshot

2.1 Understanding the three storage approaches

A. React memory (useState)

const [token, setToken] = useState<string | null>(null);

  • Survives component re-renders.
  • Lost when the application is fully reloaded.
  • Lost when the owning component unmounts.
  • Accessible to JavaScript running in our application.

B. localStorage

localStorage.setItem("theme", "dark");
localStorage.getItem("theme");
localStorage.removeItem("theme");

  • Persists across page reloads.
  • Survives browser restarts in normal browsing.
  • Shared between tabs of the same origin.
  • Accessible to JavaScript.

Example use cases: UI preferences, theme selection and non-sensitive settings.

C. sessionStorage

sessionStorage.setItem("filter", "completed");
sessionStorage.getItem("filter");

  • Survives page reloads in the same tab.
  • Generally cleared when that tab’s browsing session ends.
  • Separate between browser tabs.
  • Accessible to JavaScript.

Example use cases: temporary filters, form progress and tab-specific UI state.

Comparison

BehaviourReact memorylocalStoragesessionStorage
Survives re-renderYesYesYes
Survives page reloadNoYesYes
Survives browser restartNoYesNo
Shared across tabsNo, per app instanceYesNo
Accessible to JavaScriptYesYesYes

2.2 Why shouldn’t we store JWT in localStorage?

Imagine our application has an XSS vulnerability. An attacker manages to execute JavaScript in our application.

They could execute: const token = localStorage.getItem("access_token");

And send the stolen token to their own server.

The same problem applies to sessionStorage.

OWASP recommends against storing authentication tokens and session identifiers in either browser storage mechanism because JavaScript executing under the same origin can read them. Read: https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html

7. Store the access token in App state

After successful login, we need to make the access token available to other components.

Add an authentication state to App.tsx.

For now:

App
│
├── LoginForm (when unauthenticated)
│
└── TaskWorkspace (when authenticated)
    ├── TaskList
    └── TaskDetails

Our responsibilities:

  • Store the access token using useState.
  • Store the authenticated User.
  • Pass a callback to LoginForm.
  • On successful login, update authentication state.
  • Show TaskWorkspace after successful authentication.

Important security decision: Keep the access token in React memory. Do not put it in localStorage or sessionStorage.

When the browser refreshes, React memory is lost. Our HttpOnly refresh cookie will allow us to obtain a new access token in the next step.

What about React memory?

React memory is not completely protected against XSS.

Malicious JavaScript executing inside our application could potentially access the active token or perform authenticated actions on behalf of the user.

However, memory storage has an advantage: the access token isn’t persistently available after a page reload or browser restart.

That’s why we’re using:

Our authentication storage strategy

Access JWT: React memory

Refresh token: HttpOnly cookie

The browser handles the refresh cookie. JavaScript cannot read its value because it is HttpOnly.

One more distinction: HttpOnly prevents JavaScript from reading the cookie, but doesn’t prevent an XSS attack from making authenticated requests through the browser. That’s why we also care about XSS prevention and CSRF protection.

8. Expected login flow

9. Test our implementation

First, make sure Rails and React are running. Use the credentials of a user you’ve already registered.

Verify:

  • Login form appears.
  • Email and password are controlled by React state.
  • Valid credentials return a JWT.
  • Refresh token cookie is accepted by the browser.
  • Invalid credentials display an error.
  • Loading state is displayed while the request is running.
  • Successful login displays the Task Manager workspace.
  • Access token isn’t stored in browser storage.

Then: npm run lint
npm run build

What have we learned?

  • async allows a function to use await.
  • await waits for a Promise to settle before continuing.
  • fetch() returns a Response object after the request completes.
  • response.json() is also asynchronous.
  • JSON.stringify() converts a JavaScript object into JSON.

One thing to understand: fetch() does not throw an error for HTTP responses such as 401 Unauthorized or 422 Unprocessable Entity. It only rejects for things like network failures. We’ll handle HTTP error responses in the next small step.

Create Task Manager app: Setup React application and Integrate Fluent UI

After setting up the Github actions, let’s now move on to the frontend side React application development. We’ll build the frontend incrementally, starting with Fluent UI and understanding how a React application is bootstrapped.

Step 5.1 – React application setup and Fluent UI

Frontend development starts here. Our first objective is simple: replace the default Vite screen with a working Task Manager application shell using Fluent UI.

1. Understand the existing React structure

Open our frontend directory. Our generated structure should look similar to this:

frontend/
├── public/
├── src/
│   ├── assets/
│   ├── App.tsx
│   ├── App.css
│   ├── index.css
│   └── main.tsx
│
├── index.html
├── package.json
├── tsconfig.json
└── vite.config.ts

Before coding, understand these four files.

FileResponsibility
index.htmlHTML entry point
main.tsxReact application entry point
App.tsxRoot React component
index.cssGlobal styles

How does React start?

index.html – Contains the root DOM element: <div id="root"></div>. It loads main.tsx as a JavaScript module.

main.tsx – This is the React entry point. It initializes React using createRoot() and mounts the root component.

App.tsx – This is our root UI component. Eventually, it will compose authentication pages, task list and task details. This distinction is important: main.tsx initializes the application; App.tsx defines its UI structure.

2. Install Fluent UI React v9

Microsoft’s current Fluent UI React v9 package is @fluentui/react-components. Its current npm release is 9.75.2.

From your frontend directory:

cd frontend

npm install @fluentui/react-components

Official documentation: Fluent UI React v9.

Why do we need FluentProvider?

Fluent UI uses CSS-in-JS styling and a theme system. FluentProvider provides the theme and styling context to its child components. Without the provider, our application won’t have the intended Fluent UI theme setup.

3. Configure FluentProvider in main.tsx

Open: frontend/src/main.tsx

Our task is to:

  1. Import FluentProvider and webLightTheme.
  2. Wrap the root App component with FluentProvider.
  3. Keep React’s StrictMode.
  4. Keep the global CSS import.

The intended component hierarchy:

StrictMode
    |
    v
FluentProvider
    |
    v
App
    |
    v
Child components

Conceptually:

<FluentProvider theme={webLightTheme}>
  <App />
</FluentProvider>

Why put FluentProvider in main.tsx instead of App.tsx?

Because we want the entire application to share the same theme and styling context. Later, if we introduce React Router, every route will automatically have access to Fluent UI. Microsoft recommends placing the provider near the application root.

4. Create our initial application shell

Open: frontend/src/App.tsx For now, replace the default Vite demonstration screen.

Our first component should:

  • Display the heading Task Manager.
  • Display a short description: Manage your tasks efficiently.
  • Show a Fluent UI primary button labelled Add Task.
  • Keep the component as a functional React component.

We can import: import { Button } from "@fluentui/react-components";

A Fluent UI button supports different appearances:

AppearanceTypical usage
primaryMain action
secondarySecondary action
outlineOutlined button
subtleLow-emphasis action
transparentMinimal visual emphasis

For our Add Task button, use: appearance="primary"

Don’t implement the click functionality yet. We’ll do that when we introduce component state.

5. Our eventual React folder structure

We’ll gradually build towards this structure.

src/
├── app/
│   ├── App.tsx
│   └── providers/
│
├── components/
│   ├── layout/
│   └── common/
│
├── features/
│   ├── auth/
│   └── tasks/
│       └── components/
│
├── services/
│   └── api/
│
├── hooks/
│
├── types/
│
├── main.tsx
└── index.css

Why organize using features/? Our application has two main business features:

  • Authentication.
  • Task management.

Keeping feature-related components together makes the application easier to maintain as it grows. We’ll avoid creating empty files and directories until we actually need them.

6. Verify your React application

Start Vite: npm run dev

Open: http://localhost:5173

We should see our Task Manager heading and Fluent UI button.

Now run: npm run lint

Since we selected Oxlint, this should run our configured linting checks.

Finally: npm run build

This verifies the TypeScript compilation and production build.

# package.json
 "dependencies": {
    "@fluentui/react-components": "^9.75.3",
    "react": "^19.3.1",
    "react-dom": "^19.3.1"
  },

# main.tsx
...
import { FluentProvider, webLightTheme } from '@fluentui/react-components'

createRoot(document.getElementById('root')!).render(
  <StrictMode>
    <FluentProvider theme={webLightTheme}>
      <App />
    </FluentProvider>
  </StrictMode>,
)

# App.tsx

import { Button } from '@fluentui/react-components';

function App() {

  return (
    <div>
      <h2>Task Manager </h2>
      <p>Manage your tasks efficiently</p>
      <section>
        <Button appearance="primary">Add Task</Button>
      </section>
    </div>
  );
}

export default App;

A couple of small suggestions:

  • Keep FluentProvider in main.tsx, not in individual components.
  • Keep StrictMode. We’ll discuss why React may execute certain development lifecycle operations more than once when we cover useEffect.

Let’s build our actual Task Manager UI.

Step 5.2 – Build the Task Manager layout

We’ll build our actual UI:

Left panel

  • Task list.
  • Search input.
  • Status filters.
  • Add Task button.

Right panel

  • Selected task details.
  • Description.
  • Status.
  • Edit and Delete actions.

We’ll introduce Fluent UI Input, Button, Badge, Card and layout components.

Step 5.2 – Build the two-panel Task Manager layout

We’ll divide the application into three components.

App
│
├── AppHeader
│   ├── Task Manager heading
│   └── Add Task button
│
└── TaskWorkspace
    │
    ├── TaskList
    │   ├── Search input (later)
    │   └── TaskListItem
    │
    └── TaskDetails
        ├── Task title
        ├── Description
        ├── Status
        ├── Edit button
        └── Delete button

For this step, we’ll implement the static layout and display sample tasks. No API calls or React state yet.

1. Create component directories

From your frontend directory:

mkdir -p src/features/tasks/components
mkdir -p src/features/tasks/types
mkdir -p src/components/layout

Create these files:

touch src/features/tasks/types/task.ts

touch src/features/tasks/components/TaskList.tsx
touch src/features/tasks/components/TaskDetails.tsx

touch src/components/layout/AppHeader.tsx

Our structure:

src/
├── components/
│   └── layout/
│       └── AppHeader.tsx
│
├── features/
│   └── tasks/
│       ├── components/
│       │   ├── TaskList.tsx
│       │   └── TaskDetails.tsx
│       └── types/
│           └── task.ts
│
├── App.tsx
├── App.css
└── main.tsx

2. Define our Task TypeScript type

Open: src/features/tasks/types/task.ts

Our Rails Task model currently has:

  • id
  • title
  • description
  • status
  • created_at
  • updated_at

Create a TypeScript type representing this API resource. Our task:

  1. Define a TaskStatus union type containing pending, in_progress and completed.
  2. Define a Task interface containing the fields above.
  3. Use the correct TypeScript types for each property.

Hint:

export type TaskStatus =
  | 'pending'
  | 'in_progress'
  | 'completed';

Why do we need this? – TypeScript helps us catch invalid values during development.

For example: const status: TaskStatus = 'unknown';

TypeScript should report an error because unknown isn’t a supported task status.

Important: Our API uses snake_case (created_at), so we’ll initially use the same property names in TypeScript. We’ll avoid unnecessary response transformations.

3. Build AppHeader

Open: src/components/layout/AppHeader.tsx Our responsibility:

  • Display Task Manager.
  • Display a short description.
  • Add a primary Fluent UI button labelled Add Task.
  • Export the component.

Useful Fluent UI imports:

import {
  Button,
  Text
} from '@fluentui/react-components';

Why create a separate component?

The header is independent of task data. Keeping it separate makes it reusable and easier to maintain.

4. Build TaskList

Open: src/features/tasks/components/TaskList.tsx

This component will receive a list of tasks through props. Its requirements:

  • Accept tasks: Task[].
  • Accept selectedTaskId: number.
  • Display the task title.
  • Display its status using Fluent UI Badge.
  • Visually distinguish the selected task.

Think about how we’ll define component props using TypeScript. The component should eventually look conceptually like this:

interface TaskListProps {
  tasks: Task[];
  selectedTaskId: number;
}

function TaskList({
  tasks,
  selectedTaskId
}: TaskListProps) {
  // Render tasks here
}

Read more about Interfaces: https://www.typescriptlang.org/docs/handbook/2/objects.html
Type vs interface: https://www.typescriptlang.org/cheatsheets/

Learn about TypeScript fundamentals here: https://railsdrop.com/typescript-fundamentals-type-pipe-operator-interface/

Use .map() to render the task array. We’ll introduce click handling and callbacks in our next step.

Error in TaskList: ‘TaskList’ cannot be used as a JSX component.

Why is your TaskList function throwing an error?

# TaskList.tsx

import type { Task } from "../types/task"
import { Text, Badge } from "@fluentui/react-components";

function TaskList(tasks: Task[], selectedTaskId: number) {

  return (
    <div>{tasks.map((task) => (
      <div key={task.id} className={selectedTaskId == task.id ? 'selected-task' : ''}>
        <h3>{task.title}</h3>
        <Text>{task.description}</Text>
        <Badge>{task.status}</Badge>
      </div>
    ))
    }
      <h3>Selected: {selectedTaskId}</h3>
    </div>
  );
}

export default TaskList;

# App.tsx
...
return (
    <div>
      <h2>Task Manager </h2>
      <p>Manage your tasks efficiently</p>
      <TaskList tasks={tasks} selectedTaskId={1}></TaskList>
    </div>
  );

This is the main issue.

I wrote: function TaskList(tasks: Task[], selectedTaskId: number) {

But React components don’t receive multiple positional arguments like normal functions.

React passes one props object to the component.

Consider your invocation:

<TaskList tasks={tasks} selectedTaskId={1} />

React effectively passes an object like this:

{
  tasks: [...],
  selectedTaskId: 1
}

Our function expects:

function TaskList(
  tasks: Task[],
  selectedTaskId: number
)

But React passes one object, not two arguments.

That’s why TypeScript complains that TaskList cannot be used as a JSX component.

Correct approach

First, define the props interface.

TaskList.tsx

import type { Task } from '../types/task';

interface TaskListProps {
  tasks: Task[];
  selectedTaskId: number;
}

Now modify our component:

function TaskList({ tasks, selectedTaskId }: TaskListProps) {

  return (
    <div>
      {tasks.map((task) => (
        <div key={task.id}>
          {task.title}

          {task.id === selectedTaskId && (
            <span>Selected</span>
          )}
        </div>
      ))}
    </div>
  );
}

export default TaskList;

Notice this syntax: function TaskList({ tasks, selectedTaskId }: TaskListProps)

We’re doing two things:

  1. TypeScript checks that the incoming props follow TaskListProps.
  2. JavaScript destructures the props object into tasks and selectedTaskId.

This is called object destructuring. Alternatively, without destructuring:

function TaskList(props: TaskListProps) {
  return (
    <div>
      {props.tasks.map(task => (
        <div key={task.id}>{task.title}</div>
      ))}
    </div>
  );
}

Both approaches are correct. I prefer destructuring for most React components.

The parent component (App) passes data to the child component (TaskList) using props. The child receives props and uses them to render its UI.

This is called one-way data flow in React.

We’ll build on this in our next step when we introduce useState and callback functions.

Our initial Layout

Our components are rendering correctly, but the two-panel layout hasn’t been applied yet.

Looking at the pic, all three tasks and the details component are being rendered vertically. We need to fix this before moving to useState, because our target application requires a proper left/right layout.

This is most likely a CSS Grid or parent-container issue, not a Fluent UI issue.

1. Why is this happening?

Fluent UI provides styled components such as buttons, badges, inputs and cards. It does not automatically arrange your application into columns. We need a parent container that controls the layout.

Our intended structure:

2. Fix App.tsx

Make sure both components are inside the same parent container. Our return structure should look like this:

return (
  <div className="app-shell">
    <AppHeader />

    <main className="task-workspace">
      <aside className="task-list-panel">
        <TaskList
          tasks={tasks}
          selectedTaskId={1}
        />
      </aside>

      <section className="task-details-panel">
        <TaskDetails task={tasks[0]} />
      </section>
    </main>
  </div>
);

The important part is:

<main className="task-workspace">
  <aside>...</aside>
  <section>...</section>
</main>

Both components must be direct children of the grid container.

3. Add CSS Grid

Open src/App.css. Add:

.app-shell {
  max-width: 1400px;
  margin: 0 auto;
  padding: 32px 24px;
}

.task-workspace {
  display: grid;
  grid-template-columns: minmax(280px, 360px) minmax(0, 1fr);
  gap: 24px;
  margin-top: 24px;
  min-height: 600px;
}

.task-list-panel,
.task-details-panel {
  min-width: 0;
  padding: 20px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
}

/* Responsive layout */
@media (max-width: 768px) {
  .task-workspace {
    grid-template-columns: 1fr;
  }
}

Understand this CSS grid-template-columns: 360px minmax(0, 1fr);

It creates two columns:

  • Left panel: 360px.
  • Right panel: Takes the remaining available space.

The minmax(0, 1fr) prevents long task descriptions from forcing the right panel beyond its allocated width.

4. Check your CSS imports

Make sure App.tsx imports: import './App.css'; Also, our index.css should remove the browser’s default margin:

* {
  box-sizing: border-box;
}

html,
body,
#root {
  min-height: 100%;
  margin: 0;
}

body {
  background: #f5f7fa;
}

Now we have updated UI:

Still we have small ui issues. Fixed all issues by adding css classes and css.

Web Application Testing: Rails, RSpec, Puppeteer and Playwright

Testing is a critical part of building reliable web applications. However, choosing the right testing tools and deciding what to test at each layer can be confusing, especially when working with Ruby on Rails, React and separate API services.

In this guide, we’ll cover four types of tests, Rails examples, browser automation tools and a recommended testing architecture for modern web applications.

1. Understanding the Four Types of Tests

A good testing strategy uses different testing layers rather than testing everything through a browser.

1. Unit Tests

Purpose: Test a small, isolated piece of business logic.

Examples include price calculations, validations, discount rules, and service objects.

# app/services/discount_calculator.rb
class DiscountCalculator
  def self.apply(price:, percent:)
    price * (100 - percent) / 100.0
  end
end

RSpec example:

RSpec.describe DiscountCalculator do
  it "calculates a discounted price" do
    result = described_class.apply(
      price: 100,
      percent: 10
    )

    expect(result).to eq(90)
  end
end

Characteristics:

  • Fast and easy to debug.
  • Tests business rules independently.
  • Usually avoids databases, network calls, and browsers.

Unit tests provide a strong foundation for an application, but they cannot prove that all components work together.

2. Integration and Request Tests

Purpose: Verify that multiple components work together correctly.

In Rails, request specs are especially useful for testing API endpoints, HTTP status codes, response bodies, authorization, and database side effects.

# spec/requests/api/products_spec.rb
RSpec.describe "GET /api/products", type: :request do
  it "returns products as JSON" do
    product = create(:product, name: "Trail Shoes")

    get "/api/products"

    expect(response).to have_http_status(:ok)

    json = JSON.parse(response.body)

    expect(json.map { |item| item["id"] })
      .to include(product.id)
  end
end

This tests the HTTP request and response through Rails, without opening a browser.

Other important scenarios include:

  • Authentication and authorization.
  • Invalid parameters and validation errors.
  • Database interactions.
  • API error handling and response formats.

Characteristics: More realistic than isolated unit tests, generally faster and less brittle than browser tests.

RSpec supports model, request, job, mailer, system, and other spec types. Therefore, RSpec is not limited to unit testing. See the RSpec Rails documentation.

3. Frontend Component Tests

Purpose: Test individual UI components and their user-visible behavior.

For a React frontend, you can use Vitest with React Testing Library.

For example, a search component should display matching results or an appropriate empty state when users search.

import { render, screen } from "@testing-library/react";
import { describe, it, expect } from "vitest";
import SearchMessage from "./SearchMessage";

describe("SearchMessage", () => {
  it("shows an empty-state message", () => {
    render(<SearchMessage results={[]} />);

    expect(
      screen.getByText("No products found")
    ).toBeInTheDocument();
  });
});

This assumes SearchMessage renders the specified text when its results array is empty and that the testing dependencies are configured.

Component tests are useful for:

  • Form validation and error messages.
  • Loading and empty states.
  • Button interactions.
  • Rendering based on props and state.

They usually do not require a real browser or a running Rails API.

See React Testing Library.

4. End-to-End (E2E) Browser Tests

Purpose: Test a complete user journey through a real browser.

For example:

  1. User signs in.
  2. Searches for a product.
  3. Adds it to the cart.
  4. Completes checkout.
  5. Sees an order confirmation.

These tests can detect integration problems across the frontend, backend, browser, and database that isolated tests may miss.

However, they are generally slower and require more setup. Consequently, you should prioritize critical workflows instead of testing every button or input through a browser.

❓ 2. Is RSpec the Best Testing Framework for Enterprise Applications?

This assumption is partly correct.

RSpec is popular in Rails applications because it offers an expressive testing DSL, useful matchers, shared examples, mocking support, and a mature ecosystem. These features can make tests easier to write and maintain.

However, there are two important distinctions.

First, RSpec is not the same as unit testing.

You can use RSpec for all of these:

  • Unit tests.
  • Request and integration tests.
  • Background job tests.
  • Browser-based system tests.

A project may use RSpec extensively but have very few isolated unit tests. For example, if most specs exercise HTTP endpoints, its test suite may be heavily integration-oriented.

Second, RSpec is not automatically faster than other testing frameworks.

Rails includes Minitest by default. Both Minitest and RSpec can support maintainable, comprehensive test suites. Overall execution time depends heavily on database setup, test isolation, factories, external services, parallelization, and the proportion of browser tests.

The best choice is the framework that fits your team’s conventions, expertise, and application requirements.

3. Puppeteer vs. Rails System Tests

Puppeteer is a JavaScript library for controlling browsers programmatically. It can automate clicks, form submissions, page navigation, screenshots, and other browser activities.

It is not a Rails testing framework.

What is the equivalent in Rails?

There is no exact one-to-one replacement, but the closest built-in Rails equivalent is system testing using Capybara and a browser driver.

Rails system tests integrate browser automation with your Rails testing environment. You can interact with links, forms, buttons, JavaScript behavior, and page content.

Example:

# spec/system/product_search_spec.rb
RSpec.describe "Product search", type: :system do
  it "shows matching products" do
    create(:product, name: "Trail Shoes")

    visit "/products"

    fill_in "Search", with: "Trail"
    click_button "Search"

    expect(page).to have_text("Trail Shoes")
  end
end

This example assumes a server-rendered Rails page with a search field labeled “Search” and a corresponding button.

In an RSpec project, configure system specs with Capybara and an appropriate browser driver, such as Selenium. Other supported driver integrations are available.

See the Rails Testing Guide.

Comparison

ToolMain use
RSpecBackend and Rails application testing
CapybaraHigh-level API for interacting with web pages
SeleniumBrowser automation driver
PuppeteerJavaScript browser automation
PlaywrightBrowser automation and end-to-end testing

These tools are not all direct competitors. For example, RSpec and Playwright can be used in the same project because they test different layers.

❓ 4. What Is Playwright and When Should You Use It?

Playwright is a browser automation and testing framework. It supports Chromium, Firefox, and WebKit, and provides a test runner, assertions, browser contexts, and automatic waiting for many browser actions.

This makes it especially useful for modern JavaScript applications.

See the Playwright documentation.

React + Rails API: My Recommendation

Suppose you build an application with:

  • React + Vite for the frontend.
  • Ruby on Rails for the API.
  • PostgreSQL for persistence.

I would recommend the following:

Testing requirementRecommended tool
Rails business logicRSpec unit specs
Rails API endpointsRSpec request specs
React componentsVitest + React Testing Library
Complete user journeysPlaywright

Playwright is a strong default for E2E tests in this architecture because it can run independently of the Rails testing framework and interact with the deployed or locally running React application.

For example, a Playwright test might open the React application, enter a search term, verify the displayed products, add one to the cart, and complete a checkout flow against a test Rails API.

You can still use Rails system tests if you prefer a Ruby-based browser-testing workflow. However, Playwright often provides a more natural fit when the frontend is a separately developed React application.

My preference: Use RSpec for backend behavior and Playwright for critical cross-application browser journeys. Avoid duplicating every backend test in Playwright.

❓ 5. Are Browser Tests, System Tests and E2E Tests the Same?

This terminology causes considerable confusion because different tools and teams use these terms differently.

  • Browser test: A broad term for a test that drives an actual browser.
  • System test in Rails: A Rails testing category that exercises the application through a browser, typically using Capybara.
  • E2E test: A test that validates a complete workflow across the components involved in that workflow.

A Rails system test that signs in, purchases a product, and verifies the confirmation page is also an E2E test in the broader sense.

Likewise, a Playwright test can be an E2E test.

Not every browser test must be a full E2E test. For example, a browser test might verify that a dropdown opens correctly without exercising the backend.

Remember that system testing is a specific Rails testing facility, whereas E2E describes the scope and purpose of a test.

☑️ 6. Recommended Testing Architecture

For a typical production web application, I recommend the following strategy:

LayerToolPriority
UnitRSpecHigh
Integration / APIRSpec request specsHigh
Frontend componentsVitest + Testing LibraryHigh for substantial JS frontends
E2E browser workflowsPlaywright or Rails system testsCritical user journeys

A practical CI strategy is:

  1. Run unit, request, and component tests on every pull request.
  2. Run a small set of critical E2E tests on every pull request when execution time permits.
  3. Run broader browser coverage, including additional browser engines where required, on a scheduled or pre-release basis.
  4. Scan dependencies and run relevant security checks as part of CI.

The goal is not to maximize the number of tests. The goal is to catch defects quickly and reliably at the lowest reasonable level.

For example, test twenty discount calculation edge cases with unit tests rather than maintaining twenty browser tests for the same business rules. Then use a few E2E tests to prove that the essential shopping journey works.

🎯 The Conclusion

For a conventional Rails application, RSpec with request specs and a carefully selected set of system tests can be sufficient.

For a React + Rails API application, I recommend:

  • RSpec for business logic and backend integration.
  • Vitest + React Testing Library for frontend components.
  • Playwright for important E2E journeys.

Puppeteer is also capable of browser automation, but there is no need to introduce it merely because it is popular in JavaScript projects.

The best testing architecture is a balanced suite that verifies business rules, API behavior, frontend interactions, and critical end-to-end workflows without making every test expensive to maintain.


Build Rails 8 API + React + Vite from Scratch – Part 2

For this specific project, I recommend a single Git repository containing two applications:

rails_react_user_management/
├── backend/      # Rails API
└── frontend/     # React + Vite

This is cleaner than forcing Vite into Rails views because we explicitly want an API-only Rails backend. React’s current guidance supports using Vite as a build tool when building React from scratch, and Vite has a first-class Rails integration, but that integration is more useful when Rails is also serving the frontend. (React)

For our learning project, we’ll therefore keep the frontend and backend clearly separated while keeping them in one repo.

1. Prerequisites

Check:

ruby -v
rails -v
node -v
npm -v

Current Vite requires Node.js 20.19+ or 22.12+. (vitejs)


2. Create the Rails API

mkdir rails_react_user_management
cd rails_react_user_management

rails new backend --api -d postgresql
cd backend

The important part is:

--api

This tells Rails to create an API-only application rather than a traditional Rails application with views/assets. That’s exactly what we want.

Create the database:

bin/rails db:create

Start Rails:

bin/rails server

API:

http://localhost:3000

3. Create our User API

Let’s create a simple User model:

bin/rails generate model User name:string email:string
bin/rails db:migrate

Create controller:

bin/rails generate controller Users

app/controllers/users_controller.rb:

class UsersController < ApplicationController
  def index
    render json: User.all
  end

  def show
    render json: User.find(params[:id])
  end

  def create
    user = User.create!(user_params)
    render json: user, status: :created
  end

  private

  def user_params
    params.require(:user).permit(:name, :email)
  end
end

Routes:

# config/routes.rb

Rails.application.routes.draw do
  scope "/api" do
    resources :users
  end
end

Now:

curl http://localhost:3000/api/users

returns:

[]

Our backend is ready.


4. Create React + Vite frontend

Go back to the root:

cd ..

Create React using Vite:

npm create vite@latest frontend -- --template react
cd frontend
npm install

This creates:

frontend/
├── src/
│   ├── App.jsx
│   └── main.jsx
├── public/
├── index.html
├── package.json
└── vite.config.js

React’s documentation currently recommends a build tool such as Vite when building a React application from scratch and Create React App is deprecated. (React)


5. Start React

npm run dev

You should get:

http://localhost:5173

So now we have:

React/Vite
localhost:5173
↓ HTTP
Rails API
localhost:3000

6. Connect React to Rails

Modify:

// frontend/src/App.jsx

import { useEffect, useState } from "react";

function App() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch("http://localhost:3000/api/users")
      .then(response => response.json())
      .then(data => setUsers(data));
  }, []);

  return (
    <div>
      <h1>Users</h1>

      {users.map(user => (
        <div key={user.id}>
          {user.name} - {user.email}
        </div>
      ))}
    </div>
  );
}

export default App;

But there’s an important issue here:

5173 → 3000

The browser sees these as different origins, so we’ll eventually need CORS or a development proxy.

For development, I prefer the Vite proxy approach.

We can also configure cors from Rails end and make it work:


7. Configure Vite proxy

// frontend/vite.config.js

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],

  server: {
    proxy: {
      "/api": "http://localhost:3000",
    },
  },
});

Now React can simply call:

fetch("/api/users")

instead of:

fetch("http://localhost:3000/api/users")

Vite receives:

GET /api/users

and proxies it to:

http://localhost:3000/api/users

So our architecture becomes:

Browser
   │
   ▼
Vite :5173
   │
   │ /api/*
   ▼
Rails :3000
   │
   ▼
PostgreSQL

8. Seed some users

Let’s add some data.

# backend/db/seeds.rb

User.create!([
  { name: "Abhilash", email: "abhilash@example.com" },
  { name: "John", email: "john@example.com" }
])

Run:

cd backend
bin/rails db:seed

Then:

curl http://localhost:3000/api/users

You should get:

[
  {
    "id": 1,
    "name": "Abhilash",
    "email": "abhilash@example.com"
  },
  {
    "id": 2,
    "name": "John",
    "email": "john@example.com"
  }
]

Refresh React:

http://localhost:5173

and the users should appear.


9. Final project structure

rails_react_user_management/
│
├── backend/
│   ├── app/
│   │   ├── controllers/
│   │   │   └── users_controller.rb
│   │   └── models/
│   │       └── user.rb
│   │
│   ├── config/
│   │   └── routes.rb
│   ├── db/
│   └── Gemfile
│
├── frontend/
│   ├── src/
│   │   ├── App.jsx
│   │   └── main.jsx
│   ├── public/
│   ├── package.json
│   └── vite.config.js
│
└── README.md

10. What we’re learning from this project

We’ll gradually turn this into a proper int.-ready application:

                    React
                      │
             ┌────────┴────────┐
             │                 │
        Components          Hooks
             │                 │
             └────────┬────────┘
                      │
                 API calls
                      │
                      ▼
                Rails API
                      │
             ┌────────┴────────┐
             │                 │
        Controllers       Services
             │                 │
             └────────┬────────┘
                      │
                 ActiveRecord
                      │
                      ▼
                  PostgreSQL

Then we’ll add React Router, reusable components, forms, CRUD, loading/error states, custom hooks, useContext, Redux Toolkit, API abstraction, authentication, pagination, optimistic updates, testing, and production deployment.

For the int., the important architectural distinction is:

Rails is the API/backend and React is the client application. Vite is the frontend development/build tool.

Vite provides the development server and production build pipeline; its current production build uses Rolldown and outputs optimized static assets. (vitejs)

Next, we should implement the actual User Management UI – User list + Add User + Edit + Delete – using proper React components and API calls, because that will give you the hands-on React knowledge needed for the int.

Q) The request inside the useEffect is firing 2 times.
App.jsx line 9: fetch("/api/users") Why?

This is most likely happening because React StrictMode intentionally runs useEffect twice in development to help identify bugs in your components.

The above screenshot shows two successful GET /api/users requests, which matches this behavior.

1. Check main.jsx

Open frontend/src/main.jsx. The Vite React template typically wraps your app in StrictMode:

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Because of StrictMode, React performs an extra effect setup-and-cleanup cycle when mounting components in development.

our code:

useEffect(() => {
  fetch("/api/users")
    .then(response => response.json())
    .then(data => setUsers(data));
}, []);

Even though the dependency array is empty ([]), the effect runs twice during the initial development mount under StrictMode.

2. Does this happen in production?

No. React’s extra StrictMode effect cycle is development-only. A production build does not perform this extra cycle.

3. Int. takeaway

Remember these three points:

  • useEffect(..., []) normally runs on initial mount, not after every render.
  • StrictMode deliberately runs an extra effect setup-and-cleanup cycle in development.
  • Effects involving network requests should handle cleanup, errors, and cancellation where appropriate.

For our Rails + React application, keep StrictMode enabled. This behavior is expected during development and is not evidence that your Rails API or Vite proxy is incorrectly configured.

Guide: Integrating React ⚛️ into a Rails 8 Application – Part 4 | Synthetic Event System | Event Methods | Props

This is about React’s Synthetic Event System and naming conventions. Let me explain why React uses onClick instead of click.

React’s Synthetic Event System

React doesn’t use native DOM events directly. Instead, it creates its own Synthetic Events system that wraps around native DOM events.

HTML vs React Comparison:

<!-- Regular HTML -->
<button onclick="myFunction()">Click me</button>

<!-- React JSX -->
<button onClick={myFunction}>Click me</button>

Key Differences:

1. Naming Convention – camelCase vs lowercase:

// ❌ HTML style (lowercase) - doesn't work in React
<button click={addTodo}>Add Todo</button>
<input change={handleChange} />
<form submit={handleSubmit}>

// ✅ React style (camelCase) - correct
<button onClick={addTodo}>Add Todo</button>
<input onChange={handleChange} />
<form onSubmit={handleSubmit}>

2. More Event Examples:

// HTML → React
onclick    → onClick
onchange   → onChange
onsubmit   → onSubmit
onkeydown  → onKeyDown
onkeyup    → onKeyUp
onmouseenter → onMouseEnter
onmouseleave → onMouseLeave
onfocus    → onFocus
onblur     → onBlur

❓ Why React Uses Synthetic Events?

1. Cross-Browser Compatibility:

// Without React - you'd need to handle browser differences
function addEventListenerCrossBrowser(element, event, handler) {
  if (element.addEventListener) {
    element.addEventListener(event, handler); // Modern browsers
  } else if (element.attachEvent) {
    element.attachEvent('on' + event, handler); // Old IE
  }
}

// With React - it handles all browser differences for you
<button onClick={addTodo}>Add Todo</button>

2. Consistent API:

// React events work the same across all browsers
const handleClick = (e) => {
  e.preventDefault();    // Always works
  e.stopPropagation();   // Always works
  console.log(e.target); // Always works
};

3. Performance Optimization:

// React uses event delegation - attaches one listener to document
// and manages all events from there (more efficient)
<div>
  <button onClick={handleClick1}>Button 1</button>
  <button onClick={handleClick2}>Button 2</button>
  <button onClick={handleClick3}>Button 3</button>
  {/* React doesn't attach 3 separate listeners */}
</div>

What happens behind the scenes:

When you write:
<button onClick={addTodo}>Add Todo</button>
React internally:
  1. Wraps the native click event in a SyntheticEvent
  2. Normalizes the event across different browsers
  3. Delegates the event handling to the document root
  4. Calls your addTodo function with the synthetic event

Example of React’s event object:

const handleClick = (e) => {
  console.log(e.type);        // "click"
  console.log(e.target);      // The button element
  console.log(e.currentTarget); // The button element
  console.log(e.preventDefault); // Function to prevent default

  // React provides the native event if needed
  console.log(e.nativeEvent); // Original DOM event
};

💡 Common Mistakes:

❌ Don’t do this:
// Wrong - lowercase (HTML style)
<button onclick={addTodo}>Add Todo</button>

// Wrong - calling the function immediately
<button onClick={addTodo()}>Add Todo</button>

// Wrong - using string (HTML style)
<button onClick="addTodo()">Add Todo</button>
✅ Do this:
// Correct - camelCase and function reference
<button onClick={addTodo}>Add Todo</button>

// Correct - arrow function for parameters
<button onClick={() => deleteTodo(id)}>Delete</button>

// Correct - arrow function for event access
<button onClick={(e) => handleClick(e, id)}>Click</button>

Full Event System Examples:

const MyComponent = () => {
  const handleClick = (e) => {
    console.log('Button clicked!');
    e.preventDefault(); // Prevent default behavior
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter') {
      console.log('Enter pressed!');
    }
  };

  const handleMouseEnter = () => {
    console.log('Mouse entered!');
  };

  return (
    <div>
      <button onClick={handleClick}>Click me</button>
      <input onKeyPress={handleKeyPress} />
      <div onMouseEnter={handleMouseEnter}>Hover me</div>
    </div>
  );
};

📝 Summary:

React uses onClick (camelCase) instead of click (lowercase) because:

  1. Consistency – All React props use camelCase
  2. Synthetic Events – React wraps native events for better cross-browser support
  3. Performance – React optimizes event handling with event delegation
  4. Predictability – Same API across all browsers and components

The onClick you use in React is actually more powerful and reliable than the native onclick in HTML!

❓Questions

1. How Event Delegation Improves Performance?

Event delegation is a powerful optimization technique. Let me show you the difference:

Without Event Delegation (Traditional DOM):

// Imagine you have 1000 buttons - traditional approach
const buttons = document.querySelectorAll('button');
buttons.forEach(button => {
  button.addEventListener('click', handleClick); // 1000 event listeners!
});

With Event Delegation (React’s approach):

// React attaches ONE listener to the document root
document.addEventListener('click', (e) => {
  if (e.target.matches('button')) {
    handleClick(e); // Only one listener for all buttons!
  }
});

Performance Benefits:

Memory Usage:

// Without delegation: 1000 buttons = 1000 event listeners in memory
// With delegation: 1000 buttons = 1 event listener in memory

DOM Manipulation:

// Without delegation: Adding/removing elements requires managing listeners
const newButton = document.createElement('button');
newButton.addEventListener('click', handleClick); // Must remember to add
document.body.appendChild(newButton);

// With delegation: New elements automatically work
const newButton = document.createElement('button');
document.body.appendChild(newButton); // Automatically handles clicks!

Real React Example:

// Even with 1000 todos, React only has ONE click listener
<ul>
  {todos.map(todo => (
    <li key={todo.id}>
      <button onClick={() => deleteTodo(todo.id)}>Delete</button>
      <button onClick={() => editTodo(todo.id)}>Edit</button>
    </li>
  ))}
</ul>
// React manages all these clicks with ONE delegated listener

2. Event Parameter Naming – why always use ‘e’ for events?

We can absolutely use different names! e is just a convention, not a requirement.

All of these are valid:

// Common conventions
<button onClick={(e) => handleClick(e, id)}>Click</button>
<button onClick={(event) => handleClick(event, id)}>Click</button>
<button onClick={(evt) => handleClick(evt, id)}>Click</button>

// Your custom names
<button onClick={(v) => handleClick(v, id)}>Click</button>
<button onClick={(ev) => handleClick(ev, id)}>Click</button>
<button onClick={(clickEvent) => handleClick(clickEvent, id)}>Click</button>

Why developers use ‘e’:

// 'e' is short and widely recognized
const handleClick = (e) => {
  console.log(e.target);
};

// 'event' is more descriptive but longer
const handleClick = (event) => {
  console.log(event.target);
};

// Custom names work but might confuse other developers
const handleClick = (banana) => {
  console.log(banana.target); // Works but confusing!
};

Best Practice:

// Use 'e' for short inline handlers
<button onClick={(e) => e.preventDefault()}>Click</button>

// Use 'event' for longer, more complex handlers
const handleSubmit = (event) => {
  event.preventDefault();
  event.stopPropagation();
  // ... more logic
};

3. Event Methods and Properties Explained

Explain preventDefault, stopPropagation, currentTarget, target, type etc.

Let me create a comprehensive example:

const EventDemo = () => {
  const handleClick = (e) => {
    console.log('=== EVENT PROPERTIES ===');
    console.log('e.type:', e.type);                    // "click"
    console.log('e.target:', e.target);                // Element that triggered event
    console.log('e.currentTarget:', e.currentTarget);  // Element with event listener

    console.log('=== EVENT METHODS ===');
    // e.preventDefault(); // Prevents default behavior
    // e.stopPropagation(); // Stops event from bubbling up
  };

  return (
    <div onClick={handleClick} style={{padding: '20px', border: '1px solid blue'}}>
      <h3>Parent Div</h3>
      <button onClick={handleClick}>Child Button</button>
    </div>
  );
};

e.target vs e.currentTarget:

const Example = () => {
  const handleClick = (e) => {
    console.log('target:', e.target.tagName);        // What you clicked
    console.log('currentTarget:', e.currentTarget.tagName); // What has the listener
  };

  return (
    <div onClick={handleClick}>  {/* currentTarget will be DIV */}
      <button>Click me</button>  {/* target will be BUTTON */}
    </div>
  );
};

preventDefault() – Stops Default Browser Behavior:

const FormExample = () => {
  const handleSubmit = (e) => {
    e.preventDefault(); // Prevents form from submitting and page refresh
    console.log('Form submitted via JavaScript instead!');
  };

  const handleLinkClick = (e) => {
    e.preventDefault(); // Prevents link from navigating
    console.log('Link clicked but not navigating!');
  };

  return (
    <div>
      <form onSubmit={handleSubmit}>
        <input type="text" />
        <button type="submit">Submit</button>
      </form>

      <a href="https://google.com" onClick={handleLinkClick}>
        This link won't navigate
      </a>
    </div>
  );
};

stopPropagation() – Stops Event Bubbling:

const BubblingExample = () => {
  const handleParentClick = () => {
    console.log('Parent clicked!');
  };

  const handleChildClick = (e) => {
    console.log('Child clicked!');
    e.stopPropagation(); // Prevents parent from also firing
  };

  return (
    <div onClick={handleParentClick} style={{padding: '20px', backgroundColor: 'lightblue'}}>
      Parent
      <button onClick={handleChildClick}>
        Child (click me - parent won't fire)
      </button>
    </div>
  );
};

e.type – Event Type:

const MultiEventExample = () => {
  const handleEvent = (e) => {
    switch(e.type) {
      case 'click':
        console.log('Button was clicked!');
        break;
      case 'mouseenter':
        console.log('Mouse entered button!');
        break;
      case 'mouseleave':
        console.log('Mouse left button!');
        break;
    }
  };

  return (
    <button 
      onClick={handleEvent}
      onMouseEnter={handleEvent}
      onMouseLeave={handleEvent}
    >
      Multi-event button
    </button>
  );
};

4. React Props 📦 Explained

Props (properties) are how you pass data from parent components to child components.

Basic Props Example:

// Parent component
const App = () => {
  const userName = "John";
  const userAge = 25;

  return (
    <div>
      <UserCard name={userName} age={userAge} />
    </div>
  );
};

// Child component receives props
const UserCard = (props) => {
  return (
    <div>
      <h2>Name: {props.name}</h2>
      <p>Age: {props.age}</p>
    </div>
  );
};

Props with Destructuring (More Common):

// Instead of using props.name, props.age
const UserCard = ({ name, age }) => {
  return (
    <div>
      <h2>Name: {name}</h2>
      <p>Age: {age}</p>
    </div>
  );
};

Different Types of Props:

const ComponentExample = () => {
  const user = { name: "Alice", email: "alice@example.com" };
  const numbers = [1, 2, 3, 4, 5];
  const isActive = true;

  return (
    <MyComponent 
      // String prop
      title="Hello World"

      // Number prop
      count={42}

      // Boolean prop
      isVisible={isActive}

      // Object prop
      user={user}

      // Array prop
      items={numbers}

      // Function prop
      onButtonClick={() => console.log('Clicked!')}
    />
  );
};

const MyComponent = ({ title, count, isVisible, user, items, onButtonClick }) => {
  return (
    <div>
      <h1>{title}</h1>
      <p>Count: {count}</p>
      {isVisible && <p>This is visible!</p>}
      <p>User: {user.name} ({user.email})</p>
      <ul>
        {items.map(item => <li key={item}>{item}</li>)}
      </ul>
      <button onClick={onButtonClick}>Click me</button>
    </div>
  );
};

Props in Our Todo App:

// We can break our todo app into smaller components
const TodoApp = () => {
  const [todos, setTodos] = useState([]);
  const [inputValue, setInputValue] = useState('');

  const addTodo = () => {
    // ... add todo logic
  };

  const deleteTodo = (id) => {
    // ... delete todo logic
  };

  return (
    <div>
      <AddTodoForm 
        value={inputValue}
        onChange={setInputValue}
        onAdd={addTodo}
      />
      <TodoList 
        todos={todos}
        onDelete={deleteTodo}
      />
    </div>
  );
};

// Child component receives props
const AddTodoForm = ({ value, onChange, onAdd }) => {
  return (
    <div>
      <input 
        type="text"
        value={value}
        onChange={(e) => onChange(e.target.value)}
      />
      <button onClick={onAdd}>Add Todo</button>
    </div>
  );
};

const TodoList = ({ todos, onDelete }) => {
  return (
    <ul>
      {todos.map(todo => (
        <TodoItem 
          key={todo.id}
          todo={todo}
          onDelete={onDelete}
        />
      ))}
    </ul>
  );
};

const TodoItem = ({ todo, onDelete }) => {
  return (
    <li>
      {todo.text}
      <button onClick={() => onDelete(todo.id)}>Delete</button>
    </li>
  );
};

Props Rules:

  1. Props are read-only – child components cannot modify props
  2. Props flow down – from parent to child, not the other way up
  3. Props can be any data type – strings, numbers, objects, arrays, functions
  4. Props are optional – you can provide default values
// Default props
const Greeting = ({ name = "World", enthusiasm = 1 }) => {
  return <h1>Hello {name}{"!".repeat(enthusiasm)}</h1>;
};

// Usage
<Greeting />                    // "Hello World!"
<Greeting name="Alice" />       // "Hello Alice!"
<Greeting name="Bob" enthusiasm={3} /> // "Hello Bob!!!"

🎯 Summary:

  1. Event Delegation = One listener handles many elements = Better performance
  2. Event parameter naming = Use any name you want (e, event, evt, v, etc.)
  3. Event methods: preventDefault() stops default behavior, stopPropagation() stops bubbling
  4. Event properties: target = what triggered event, currentTarget = what has listener
  5. Props = Data passed from parent to child components

Let’s see in Part 5. Happy React Development! 🚀

Guide: Integrating React ⚛️ into a Rails 8 Application – Part 3 | Start developing react

Let’s move on to quick development of more react components now. Before that let’s check what we have now and understand it very clear.

📄 File 1:

Our app/javascript/components/App.jsx file:

import React from 'react';

function App() {
  return (
    <div>
      <h1>React is working fine!</h1>
      <p>Welcome to Rails + React App</p>
    </div>
  );
}

export default App;

Let’s examine this React component step by step:

Line 1: Import React

import React from 'react';
  • import – ES6 module syntax to bring in external code
  • React – The main React library
  • from 'react' – Importing from the npm package named “react”
  • Why needed? Even though we use --jsx=automatic, we still import React for any hooks or React features we might use.

Function Component: Line 3-9

A React function component is a simple JavaScript function that serves as a building block for user interfaces in React applications. These components are designed to be reusable and self-contained, encapsulating a specific part of the UI and its associated logic.

function App() {
  return (
    <div>
      <h1>React is working fine!</h1>
      <p>Welcome to Rails + React App</p>
    </div>
  );
}

🔍 Breaking this down:

Line 3: Component Declaration

function App() {
  • function App() – This is a React Function Component
  • Component naming – Must start with capital letter (App, not app)
  • What it is – A JavaScript function that returns JSX (user interface)

Line 4-8: JSX Return

return (
  <div>
    <h1>React is working fine!</h1>
    <p>Welcome to Rails + React App</p>
  </div>
);
  • return – Every React component must return something
  • JSX – Looks like HTML, but it’s actually JavaScript
  • <div> – Must have one parent element (React Fragment rule)
  • <h1> & <p> – Regular HTML elements, but processed by React

Line 11: Export

export default App;
  • export default – ES6 syntax to make this component available to other files
  • App – The component name we’re exporting
  • Why needed? So application.js can import and use this component

📄 File 2:

Our app/javascript/application.js file:

// Entry point for the build script in your package.json
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './components/App';

document.addEventListener('DOMContentLoaded', () => {
  const container = document.getElementById('react-root');

  if(container) {
    const root = createRoot(container);
    root.render(<App />);
  }
});

This is the entry point that connects React to your Rails app:

    Imports: Line 2-4

    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import App from './components/App';
    

    🔍 Breaking down each import:

    Line 2:

    import React from 'react';
    
    • Same as before – importing the React library

    Line 3:

    import { createRoot } from 'react-dom/client';
    
    • { createRoot } – Named import (notice the curly braces)
    • react-dom/client – ReactDOM library for browser/DOM manipulation
    • createRoot – New React 18+ API for rendering components to DOM

    Line 4:

    import App from './components/App';
    
    • App – Default import (no curly braces)
    • ./components/App – Relative path to our App component
    • Note: We don’t need .jsx extension, esbuild figures it out

    DOM Integration: Line 6-12

    document.addEventListener('DOMContentLoaded', () => {
      const container = document.getElementById('react-root');
    
      if(container) {
        const root = createRoot(container);
        root.render(<App />);
      }
    });
    

    🔍 Step by step breakdown:

    Line 6:

    document.addEventListener('DOMContentLoaded', () => {
    
    • document.addEventListener – Standard browser API
    • 'DOMContentLoaded' – Wait until HTML is fully loaded
    • () => { – Arrow function (ES6 syntax)
    • Why needed? Ensures the HTML exists before React tries to find elements

    Line 7:

    const container = document.getElementById('react-root');
    
    • const container – Create a variable to hold the DOM element
    • document.getElementById('react-root') – Find HTML element with id="react-root"
    • Where is it? In your Rails view file: app/views/home/index.html.erb

    Line 9:

    if(container) {
    
    • Safety check – Only proceed if the element exists
    • Prevents errors – If someone visits a page without react-root element

    Line 10-11:

    const root = createRoot(container);
    root.render(<App />);
    
    • createRoot(container) – Create a React “root” at the DOM element
    • root.render(<App />) – Render our App component inside the container
    • <App /> – JSX syntax for using our component (self-closing tag)

    🎯 Key React Concepts You Just Learned:

    1. Components

    • Functions that return JSX
    • Must start with capital letter
    • Reusable pieces of UI

    2. JSX

    • Looks like HTML, actually JavaScript
    • Must return single parent element
    • Processed by esbuild into regular JavaScript

    3. Import/Export

    • Default exports: export default App → import App from './App'
    • Named exports: export { createRoot } → import { createRoot } from 'package'

    4. React DOM

    • createRoot() – Modern way to mount React apps (React 18+)
    • render() – Display components in the browser

    5. Rails Integration

    • Rails serves the HTML page
    • React takes over the #react-root element
    • esbuild bundles everything together

    🚀 This pattern is the foundation of every React app! We create components, import them, and render them to the DOM.


    📚 Step-by-Step React Learning with Todo List

    Now let’s build a Todo List app step by step. I’ll explain each React concept thoroughly as we go. Here’s our learning roadmap:

    Step 1: Understanding JSX and Basic Component Structure

    First, let’s update our App.jsx to create the basic structure of our Todo app:

    import React from 'react';
    
    function App() {
      return (
        <div className="todo-app">
          <h1>My Todo List</h1>
          <p>Let's learn React by building a todo app!</p>
    
          {/* This is a JSX comment */}
          <div className="todo-container">
            <h2>Add a new todo</h2>
            <input type="text" placeholder="Enter a todo..." />
            <button>Add Todo</button>
    
            <h2>My Todos</h2>
            <ul>
              <li>Learn React basics</li>
              <li>Build a todo app</li>
              <li>Master React hooks</li>
            </ul>
          </div>
        </div>
      );
    }
    
    export default App;
    

    🎯 Key Concepts Explained:

    JSX (JavaScript XML):

    • JSX lets you write HTML-like syntax directly in JavaScript
    • It’s a syntax extension for JavaScript, not actual HTML
    • JSX gets compiled to JavaScript function calls
    • You can use {} to embed JavaScript expressions inside JSX

    Important JSX Rules:

    • Use className instead of class (because class is a reserved word in JavaScript)
    • You can use single quotes for className values in JSX. Both work perfectly fine:
    // Both of these are valid:
    <div className='todo-app'>    // Single quotes ✅
    <div className="todo-app">    // Double quotes ✅
    

    Quote Usage in JSX/JavaScript:

    Single quotes vs Double quotes:

    • JavaScript treats them identically
    • It’s mostly a matter of personal/team preference
    • The key is to be consistent throughout your project

    Common conventions:

    // Option 1: Single quotes for JSX attributes
    <div className='todo-app'>
      <input type='text' placeholder='Enter todo...' />
    </div>
    
    // Option 2: Double quotes for JSX attributes  
    <div className="todo-app">
      <input type="text" placeholder="Enter todo..." />
    </div>
    
    // Option 3: Mixed (but stay consistent within each context)
    const message = 'Hello World';  // Single for JS strings
    <div className="todo-app">      // Double for JSX attributes
    

    When you MUST use specific quotes:

    // When the string contains the same quote type
    <div className="It's a great day">        // Double quotes needed
    <div className='He said "Hello"'>        // Single quotes needed
    
    // Or use escape characters
    <div className='It\'s a great day'>       // Escaping single quote
    <div className="He said \"Hello\"">      // Escaping double quote
    

    💡 Tip: Many teams use tools like Prettier or ESLint to automatically format and enforce consistent quote usage across the entire project.

    • All tags must be closed (self-closing tags need / at the end)
    • JSX comments use {/* */} syntax
    • Return a single parent element (or use React Fragment <>...</>)

    Try updating our App.jsx with this code and see it in your browser!


    Step 2: Introduction to State with useState

    Now let’s add state to make our app interactive. State is data that can change over time.

    import React, { useState } from 'react';
    
    function App() {
      // useState Hook - creates state variable and setter function
      const [todos, setTodos] = useState([
        { id: 1, text: 'Learn React basics', completed: false },
        { id: 2, text: 'Build a todo app', completed: false },
        { id: 3, text: 'Master React hooks', completed: true }
      ]);
    
      const [inputValue, setInputValue] = useState('');
    
      return (
        <div className="todo-app">
          <h1>My Todo List</h1>
    
          <div className="todo-container">
            <h2>Add a new todo</h2>
            <input 
              type="text" 
              placeholder="Enter a todo..." 
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
            />
            <button>Add Todo</button>
    
            <h2>My Todos ({todos.length})</h2>
            <ul>
              {todos.map(todo => (
                <li key={todo.id}>
                  {todo.text} {todo.completed ? '✅' : '⏳'}
                </li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
    
    export default App;
    

    🎯 Key Concepts Explained:

    useState Hook:

    • useState is a React Hook that lets you add state to functional components
    • It returns an array with two elements: [currentValue, setterFunction]
    • const [todos, setTodos] = useState([]) creates a state variable todos and a function setTodos to update it
    • The initial value is passed as an argument to useState

    Controlled Components:

    • The input field is now “controlled” by React state
    • value={inputValue} makes the input show what’s in state
    • onChange={(e) => setInputValue(e.target.value)} updates state when user types

    Array.map() for Rendering Lists:

    • todos.map() transforms each todo into a JSX element
    • Each list item needs a unique key prop for React’s optimization
    • {todo.text} embeds the todo text using JSX expressions

    Try this code and notice how the input field now responds to typing!


    Step 3: Event Handling and Adding Todos

    Let’s make the “Add Todo” button work:

    import React, { useState } from 'react';
    
    function App() {
      const [todos, setTodos] = useState([
        { id: 1, text: 'Learn React basics', completed: false },
        { id: 2, text: 'Build a todo app', completed: false },
        { id: 3, text: 'Master React hooks', completed: true }
      ]);
    
      const [inputValue, setInputValue] = useState('');
    
      // Function to add a new todo
      const addTodo = () => {
        if (inputValue.trim() !== '') {
          const newTodo = {
            id: Date.now(), // Simple ID generation
            text: inputValue,
            completed: false
          };
    
          setTodos([...todos, newTodo]); // Spread operator to add new todo
          setInputValue(''); // Clear the input field
        }
      };
    
      // Function to handle Enter key press
      const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
          addTodo();
        }
      };
    
      return (
        <div className="todo-app">
          <h1>My Todo List</h1>
    
          <div className="todo-container">
            <h2>Add a new todo</h2>
            <input 
              type="text" 
              placeholder="Enter a todo..." 
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
            />
            <button onClick={addTodo}>Add Todo</button>
    
            <h2>My Todos ({todos.length})</h2>
            <ul>
              {todos.map(todo => (
                <li key={todo.id}>
                  {todo.text} {todo.completed ? '✅' : '⏳'}
                </li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
    
    export default App;
    

    🎯 Key Concepts Explained:

    Event Handlers:

    • onClick={addTodo} – function runs when button is clicked
    • onKeyPress={handleKeyPress} – function runs when key is pressed
    • Event handlers receive an event object (e) with information about the event

    State Updates:

    • setTodos([...todos, newTodo]) – creates a new array with all existing todos plus the new one
    • Important: Always create new arrays/objects instead of mutating existing ones
    • React compares old and new state to determine if re-render is needed

    Spread Operator (...):

    • ...todos spreads out all elements of the todos array
    • This is the React way to add items to an array in state

    Try adding new todos now!

    🎯 Function Syntax Options in JavaScript:

    const addTodo = () => {} is a function syntax – specifically an arrow function. Let me explain why it’s declared as const and the different ways to write functions in JavaScript.

    1. Function Declaration (Traditional)
    function addTodo() {
      // function body
    }
    
    2. Function Expression with Arrow Function
    const addTodo = () => {
      // function body
    };
    
    3. Function Expression (Traditional)
    const addTodo = function() {
      // function body
    };
    

    🤔 Why use const for functions?

    Arrow functions are expressions, not declarations:

    // This is a DECLARATION - creates a function named addTodo
    function addTodo() { }
    
    // This is an EXPRESSION - creates a function and assigns it to a variable
    const addTodo = () => { };
    

    Why const specifically?

    // ❌ Could be reassigned accidentally
    let addTodo = () => { };
    addTodo = "oops"; // Function is now gone!
    
    // ❌ Could be reassigned accidentally  
    var addTodo = () => { };
    addTodo = null; // Function is now gone!
    
    // ✅ Cannot be reassigned - prevents bugs
    const addTodo = () => { };
    addTodo = "something"; // ERROR: Assignment to constant variable
    

    📚 Key Differences:

    Function Declaration vs Arrow Function:

    // Function Declaration
    function addTodo() {
      console.log("Adding todo");
    }
    
    // Arrow Function (assigned to const)
    const addTodo = () => {
      console.log("Adding todo");
    };
    

    Hoisting Behavior:

    // ✅ This works - function declarations are "hoisted"
    sayHello(); // "Hello!"
    
    function sayHello() {
      console.log("Hello!");
    }
    
    // ❌ This doesn't work - arrow functions are not hoisted
    sayGoodbye(); // Error: Cannot access 'sayGoodbye' before initialization
    
    const sayGoodbye = () => {
      console.log("Goodbye!");
    };
    

    this Binding:

    // Function declaration has its own 'this'
    function regularFunction() {
      console.log(this); // 'this' can change based on how it's called
    }
    
    // Arrow function inherits 'this' from surrounding scope
    const arrowFunction = () => {
      console.log(this); // 'this' is inherited from parent scope
    };
    

    🚀 In React Context:

    In React functional components, we typically use arrow functions with const because:

    1. Prevents accidental reassignment – our function won’t get overwritten
    2. Consistent with modern JavaScript – ES6+ standard
    3. Cleaner syntax – less verbose than traditional function expressions
    4. Better for event handlers – this behavior is more predictable

    All these are equivalent in React:

    // Option 1: Arrow function with const (most common)
    const addTodo = () => {
      if (inputValue.trim() !== '') {
        // ... logic
      }
    };
    
    // Option 2: Traditional function declaration
    function addTodo() {
      if (inputValue.trim() !== '') {
        // ... logic  
      }
    }
    
    // Option 3: Function expression with const
    const addTodo = function() {
      if (inputValue.trim() !== '') {
        // ... logic
      }
    };
    

    💡 Why React developers prefer arrow functions:

    1. Shorter syntax for simple functions
    2. Consistent variable declaration (everything uses const)
    3. No hoisting confusion – functions are defined before they’re used
    4. Better with modern tooling – ESLint, Prettier handle them well

    So yes, const addTodo = () => {} is definitely a function! It’s just a modern way to write functions that prevents accidental reassignment and has cleaner syntax.

    🎯 What is Hoisting?

    Hoisting is a fundamental JavaScript concept that can be confusing at first. Let me explain it clearly with examples.

    Hoisting is JavaScript’s behavior of moving declarations to the top of their scope during the compilation phase, before the code is executed.

    Think of it like JavaScript “hoists” (lifts up) your variable and function declarations to the top of their scope.

    📚 How Hoisting Works:

    Function Declarations are Hoisted:

    // This works even though we call the function before declaring it!
    sayHello(); // Outputs: "Hello!"
    
    function sayHello() {
      console.log("Hello!");
    }
    

    Behind the scenes, JavaScript treats it like this:

    // JavaScript internally reorganizes it like this:
    function sayHello() {
      console.log("Hello!");
    }
    
    sayHello(); // Now it makes sense!
    

    Variable Declarations (with var) are Hoisted:

    console.log(myVar); // Outputs: undefined (not an error!)
    var myVar = "Hello";
    console.log(myVar); // Outputs: "Hello"
    

    Behind the scenes:

    // JavaScript internally treats it like this:
    var myVar; // Declaration is hoisted to the top
    console.log(myVar); // undefined (declared but not assigned)
    myVar = "Hello"; // Assignment stays in place
    console.log(myVar); // "Hello"
    

    🚫 What is NOT Hoisted:

    let and const variables:

    // ❌ This throws an error!
    console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
    let myLet = "Hello";
    
    // ❌ This also throws an error!
    console.log(myConst); // ReferenceError: Cannot access 'myConst' before initialization
    const myConst = "Hello";
    

    Arrow Functions (Function Expressions):

    // ❌ This throws an error!
    sayGoodbye(); // ReferenceError: Cannot access 'sayGoodbye' before initialization
    
    const sayGoodbye = () => {
      console.log("Goodbye!");
    };
    

    Function Expressions:

    // ❌ This throws an error!
    myFunc(); // TypeError: myFunc is not a function
    
    var myFunc = function() {
      console.log("Hello!");
    };
    

    🎭 Visual Examples:

    Example 1: Function Declaration Hoisting

    // What you write:
    console.log("1. Start");
    myFunction(); // This works!
    console.log("3. End");
    
    function myFunction() {
      console.log("2. Inside function");
    }
    
    // Output:
    // 1. Start
    // 2. Inside function  
    // 3. End
    

    Example 2: Variable Hoisting with var

    // What you write:
    console.log("Value is:", myVar); // undefined
    var myVar = 42;
    console.log("Value is:", myVar); // 42
    
    // What JavaScript internally does:
    var myVar; // Hoisted to top
    console.log("Value is:", myVar); // undefined
    myVar = 42; // Assignment stays here
    console.log("Value is:", myVar); // 42
    

    Example 3: Why let and const are different

    // Temporal Dead Zone
    console.log("Before declaration");
    
    // ❌ This area is the "Temporal Dead Zone" for myLet
    console.log(myLet); // ReferenceError!
    
    let myLet = "Hello"; // Declaration and initialization
    console.log(myLet); // "Hello"
    

    🎯 Practical Implications:

    Why Function Declarations work everywhere:

    // This is valid JavaScript
    function main() {
      helper(); // Can call helper before it's defined
    
      function helper() {
        console.log("Helper function");
      }
    }
    

    Why Arrow Functions must be defined first:

    // ❌ This doesn't work
    const main = () => {
      helper(); // Error! helper is not defined yet
    
      const helper = () => {
        console.log("Helper function");
      };
    };
    
    // ✅ This works
    const main = () => {
      const helper = () => {
        console.log("Helper function");
      };
    
      helper(); // Now it works!
    };
    

    💡 Best Practices:

    1. Use const and let instead of var to avoid hoisting confusion
    2. Define functions before using them (even though function declarations are hoisted)
    3. Use arrow functions for consistency and to avoid hoisting surprises
    4. Initialize variables when you declare them

    🔗 Back to Our React Example:

    // This is why we use const for arrow functions
    const App = () => {
      // ✅ Good: Function defined before use
      const addTodo = () => {
        // function logic
      };
    
      // ❌ Bad: Would cause error if we tried to call it here
      // deleteTodo(); // Error!
    
      const deleteTodo = () => {
        // function logic
      };
    
      return (
        <div>
          <button onClick={addTodo}>Add</button>
          <button onClick={deleteTodo}>Delete</button>
        </div>
      );
    };
    

    Hoisting is JavaScript’s way of making function declarations available throughout their scope, but it doesn’t apply to modern variable declarations (let, const) or arrow functions. That’s why we define our functions with const and make sure to declare them before we use them!


    Step 4: Toggling Todo Completion

    Let’s add the ability to mark todos as complete/incomplete:

    import React, { useState } from 'react';
    
    function App() {
      const [todos, setTodos] = useState([
        { id: 1, text: 'Learn React basics', completed: false },
        { id: 2, text: 'Build a todo app', completed: false },
        { id: 3, text: 'Master React hooks', completed: true }
      ]);
    
      const [inputValue, setInputValue] = useState('');
    
      const addTodo = () => {
        if (inputValue.trim() !== '') {
          const newTodo = {
            id: Date.now(),
            text: inputValue,
            completed: false
          };
    
          setTodos([...todos, newTodo]);
          setInputValue('');
        }
      };
    
      // Function to toggle todo completion
      const toggleTodo = (id) => {
        setTodos(todos.map(todo => 
          todo.id === id 
            ? { ...todo, completed: !todo.completed } // Toggle completed status
            : todo // Keep todo unchanged
        ));
      };
    
      const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
          addTodo();
        }
      };
    
      return (
        <div className="todo-app">
          <h1>My Todo List</h1>
    
          <div className="todo-container">
            <h2>Add a new todo</h2>
            <input 
              type="text" 
              placeholder="Enter a todo..." 
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              onKeyPress={handleKeyPress}
            />
            <button onClick={addTodo}>Add Todo</button>
    
            <h2>My Todos ({todos.length})</h2>
            <ul>
              {todos.map(todo => (
                <li key={todo.id}>
                  <span 
                    onClick={() => toggleTodo(todo.id)}
                    style={{ 
                      textDecoration: todo.completed ? 'line-through' : 'none',
                      cursor: 'pointer',
                      color: todo.completed ? '#888' : '#000'
                    }}
                  >
                    {todo.text}
                  </span>
                  {todo.completed ? ' ✅' : ' ⏳'}
                </li>
              ))}
            </ul>
          </div>
        </div>
      );
    }
    
    export default App;
    

    🎯 Key Concepts Explained:

    Array.map() for Updates:

    • todos.map() creates a new array where each todo is either updated or kept the same
    • todo.id === id ? { ...todo, completed: !todo.completed } : todo
    • This pattern is very common in React for updating items in arrays

    Conditional Rendering:

    • todo.completed ? '✅' : '⏳' – ternary operator for conditional display
    • textDecoration: todo.completed ? 'line-through' : 'none' – conditional styling

    Arrow Functions in JSX:

    • onClick={() => toggleTodo(todo.id)} – arrow function to pass arguments to event handlers
    • Without the arrow function, toggleTodo(todo.id) would execute immediately

    Now you can click on todos to toggle their completion status!


    🤔 What we’ve learned so far:

    1. ✅ JSX syntax and rules
    2. ✅ useState hook for state management
    3. ✅ Event handling (onClick, onChange, onKeyPress)
    4. ✅ Controlled components
    5. ✅ Array mapping for rendering lists
    6. ✅ Conditional rendering
    7. ✅ State updates with spread operator

    Next Steps: In the following steps, we’ll cover:

    • Deleting todos
    • Component composition (breaking into smaller components)
    • Props passing
    • Filtering todos
    • More advanced state management

    Let’s see in Part 4. Happy React Development! 🚀

    Guide: Integrating React.js ⚛️ into a Rails 8 Application – Part 2: Install React | Add esbuild, Jsx | Integrate React View

    Throw back:

    rails new design_studio_react --database=postgresql -j esbuild --skip-hotwire
    

    Here’s what our Rails app looks like after skipping Hotwire with the --skip-hotwire flag:

    ✅ Current JavaScript/Node.js Setup (Clean & Minimal)

    📦 Package Management:

    • package.json – Clean setup with only esbuild script
    • .node-version – Node.js version 24.1.0
    • No dependencies – Ready for React installation

    📁 JavaScript File Structure (Ultra-Clean):

    app/javascript/
    └── application.js          # Empty entry point (2 lines total!)
    

    app/javascript/application.js content:

    // Entry point for the build script in your package.json
    

    🚫 What Got Successfully Removed:

    • ❌ No Turbo/Stimulus imports in application.js
    • ❌ No controllers/ directory at all
    • ❌ No Hotwire gems in Gemfile (only jsbundling-rails remains)
    • ❌ No @hotwired/turbo-rails or @hotwired/stimulus dependencies

    ⚙️ Configuration Files (Minimal – Only 4):

    1. package.json – esbuild build script only
    2. .node-version – Node.js version pinning
    3. Procfile.dev – Development processes (js: yarn build --watch)
    4. app/javascript/application.js – Empty entry point

    🔧 esbuild Configuration:

    {
      "scripts": {
        "build": "esbuild app/javascript/*.* --bundle --sourcemap --format=esm --outdir=app/assets/builds --public-path=/assets"
      }
    }
    

    📂 Build Output:

    • app/assets/builds/ – Contains only .keep file (empty, ready for bundles)

    🎯 HTML Integration:

    <!-- Still includes the JavaScript module correctly -->
    <%= javascript_include_tag "application", "data-turbo-track": "reload", type: "module" %>
    

    (Note: data-turbo-track is just an HTML attribute for cache busting, not the Turbo library)

    # create db
    ✗ rails db:migrate
    
    # run react-rails-app in port 3001
    ✗ rails s -p 3001
    

    🚀 Next Steps: Install & Setup React

    Step 1: Install react, react-dom

    Your app is now perfectly clean for React! Just run:

    brew install yarn
    yarn add react react-dom # check node_modules/ folder for what is installed
    yarn add --dev @types/react @types/react-dom  # Optional: for TypeScript support, check node_modules/@types folder
    

    Status: ✅ Minimal JavaScript foundation – No Hotwire bloat, perfect React starting point!

    Now that we have a clean Rails app with esbuild setup, here’s our step-by-step roadmap to get React working:

    Step 2: Create Your First React Component

    Create a simple React component to test the setup:

    mkdir app/javascript/components
    

    Then create app/javascript/components/App.jsx:

    import React from 'react';
    
    function App() {
      return (
        <div>
          <h1>React is Working!</h1>
          <p>Welcome to your Rails + React app</p>
        </div>
      );
    }
    
    export default App;
    

    Step 3: Update JavaScript Entry Point

    Modify app/javascript/application.js to render React:

    // Entry point for the build script in your package.json
    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import App from './components/App';
    
    document.addEventListener('DOMContentLoaded', () => {
      const container = document.getElementById('react-root');
      if (container) {
        const root = createRoot(container);
        root.render(<App />);
      }
    });
    

    Step 4: Create a Controller & Route

    Generate a home controller:

    rails generate controller Home index
    

    Step 5: Add React Root to View

    Update app/views/home/index.html.erb:

    <div id="react-root"></div>
    

    Step 6: Set Root Route

    Update config/routes.rb:

    Rails.application.routes.draw do
      root "home#index"
      # ... other routes
    end
    

    Step 7: Start Development

    # update Procfile.dev assign port 3001
    web: env RUBY_DEBUG_OPEN=true bin/rails server -p 3001
    
    # run our rails-react app by
    
    ✗ bin/dev
    21:15:27 web.1  | started with pid 12619
    21:15:27 js.1   | started with pid 12620
    21:15:27 js.1   | yarn run v1.22.22
    21:15:27 js.1   | $ esbuild app/javascript/*.* --bundle --sourcemap --format=esm --outdir=app/assets/builds --public-path=/assets --watch
    21:15:27 js.1   | /bin/sh: esbuild: command not found
    21:15:27 js.1   | error Command failed with exit code 127.
    21:15:27 js.1   | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
    21:15:27 web.1  | => Booting Puma
    ..........
    

    🎯 What This Gives Us:

    • ✅ React components in app/javascript/components/
    • ✅ esbuild automatically bundles JSX
    • ✅ Hot reloading with yarn build --watch
    • ✅ Rails serves your React app

    🚨 Error Analysis:

    1. Rails server started fine ✅ (port 3001)

    🔧 Solution: Install JavaScript Dependencies

    You need to install esbuild and other JavaScript dependencies first:

    yarn install
    

    📋 Files yarn install Checks:

    1. Primary: package.json

    {
      "name": "app",
      "private": true,
      "scripts": {
        "build": "esbuild app/javascript/*.* --bundle --sourcemap --format=esm --outdir=app/assets/builds --public-path=/assets"
      },
      "dependencies": {
        "react": "^19.1.0",           # ✅ Already added
        "react-dom": "^19.1.0"       # ✅ Already added  
      },
      "devDependencies": {
        "@types/react": "^19.1.8",      # ✅ Already added
        "@types/react-dom": "^19.1.6"   # ✅ Already added
      }
    }
    

    2. Lockfile: yarn.lock

    • Ensures exact versions for reproducible installs
    • Contains resolved URLs and integrity hashes

    🚨 The Problem: Missing esbuild!

    Our package.json calls esbuild in the build script, but esbuild is not listed as a dependency anywhere!

    Rails should have added it, but didn’t. We need to add esbuild:

    yarn add --dev esbuild
    

    🔧 What yarn install does:

    1. Reads package.json for dependency list
    2. Reads yarn.lock for exact versions (if exists)
    3. Downloads packages to node_modules/
    4. Updates yarn.lock with new resolutions

    Current issue: Our build script expects esbuild command, but it’s not installed in node_modules/.bin/esbuild

    Solution: Add esbuild as a dev dependency!

    Solved~ and start servers: Error Again!

    x bin/dev
    
    * Listening on http://[::1]:3001
    22:54:43 web.1  | Use Ctrl-C to stop
    22:54:44 js.1   | ✘ [ERROR] The JSX syntax extension is not currently enabled
    22:54:44 js.1   |
    22:54:44 js.1   |     app/javascript/application.js:11:16:
    22:54:44 js.1   |       11 │     root.render(<App />);
    22:54:44 js.1   |          ╵                 ^
    22:54:44 js.1   |
    22:54:44 js.1   |   The esbuild loader for this file is currently set to "js" but it must be set to "jsx" to be able to parse JSX syntax. You can use "--loader:.js=jsx" to do that.
    22:54:44 js.1   |
    22:54:44 js.1   | 1 error
    22:54:44 js.1   | [watch] build finished, watching for changes..
    

    This error occurs because esbuild doesn’t know how to handle JSX syntax! The <App /> is JSX, but esbuild needs to be configured to transform it.

    🚨 Problem: esbuild can’t process JSX syntax

    Your application.js contains JSX (<App />), but esbuild isn’t configured to transform JSX!

    JSX (JavaScript XML) is a syntax extension for JavaScript, commonly used with React, that allows you to write HTML-like code within JavaScript files.

    🔧 Solution: Configure esbuild for JSX

    Update your package.json build script to handle JSX:

    # add this to build
    --jsx=automatic --loader:.js=jsx 
    

    ✅ Fixed! Added JSX support:

    What I added:

    • --jsx=automatic – Enables React’s automatic JSX runtime
    • --loader:.js=jsx – Treats .js files as JSX files

    📝 What this means:

    • ✅ esbuild can now process <App /> syntax
    • ✅ You don’t need to import React in every JSX file
    • ✅ Your .js files can contain JSX
    bin/dev
    

    Whola!!

    Let’s see in Part 3. Happy React configuration! 🚀

    Guide: Integrating React.js ⚛️ into a Rails 8 Application | Node.js | ESBuild | Virtual DOM- Part 1

    1. Introduction and Motivation

    Why React?

    • Declarative UI: build complex interfaces by composing small, reusable components.
    • Virtual DOM: efficient updates, smoother user experience.
    • Rich ecosystem: hooks, context, testing tools, and libraries like Redux.
    • Easy to learn once you grasp JSX and component lifecycle.

    Why use React in Rails?

    • Leverage Rails’ backend power (ActiveRecord, routing, authentication) with React’s frontend flexibility.
    • Build single-page-app-like interactions within a Rails monolith or progressively enhance ERB views.

    2. Prerequisites

    • Ruby 3.4.x installed (recommend using rbenv or RVM or Mise).
    • Rails 8.x (we’ll install below).
    • Node.js (>= 16) and npm or Yarn.
    • Code editor (VS Code, RubyMine, etc.).

    Why Node.js is Required for React

    React’s ecosystem relies on a JavaScript runtime and package manager:

    • Build tools (ESBuild, Webpack, Babel) run as Node.js scripts to transpile JSX/ES6 and bundle assets.
    • npm/Yarn fetch and manage React and its dependencies from the npm registry.
    • Script execution: Rails generators and custom npm scripts (e.g. rails javascript:install:react, npm run build) need Node.js to execute.

    Without Node.js, you cannot install packages or run the build pipeline necessary to compile and serve React components.

    What is Node.js?

    Node.js is an open-source, cross-platform JavaScript runtime built on Chrome’s V8 engine. It enables JavaScript to be executed on the server (outside the browser) and provides:

    • Server-side scripting: build web servers, APIs, and backend services entirely in JavaScript.
    • Command-line tools: run scripts for tasks like building, testing, or deploying applications.
    • npm ecosystem: access to hundreds of thousands of packages for virtually any functionality, from utility libraries to full frameworks.
    • Event-driven, non-blocking I/O: efficient handling of concurrent operations, making it suitable for real-time applications.

    Node.js is the backbone that powers React’s tooling, package management, and build processes.

    3. Installing Ruby 3.4 and Rails 8

    1. Install Ruby 3.4.0 (example using rbenv):

    # install rbenv and ruby-build if not yet installed
    brew install rbenv ruby-build
    rbenv install 3.4.0
    rbenv global 3.4.0
    ruby -v   # => ruby 3.4.0p0
    

    Check the post for using Mise as version manager: https://railsdrop.com/2025/02/11/installing-and-setup-ruby-3-rails-8-vscode-ide-on-macos-in-2025/

    2. Install Rails 8:

    gem install rails -v "~> 8.0"
    rails -v   # => Rails 8.0.x
    

    4. Generating a New Rails 8 App

    We’ll scaffold a fresh project using ESBuild for JavaScript bundling, which integrates seamlessly with React.

    rails new design_studio_react \
      --database=postgresql \
      -j esbuild
    cd design_studio_react
    
    • --database=postgresql: sets PostgreSQL as the database adapter.
    • -j esbuild: configures ESBuild for JS bundling (preferred for React in Rails 8).

    4.1 About ESBuild

    ESBuild is a next-generation JavaScript bundler and minifier written in Go. Rails 8 adopted ESBuild by default for JavaScript bundling due to its remarkable speed and modern feature set:

    • Blazing-fast builds: ESBuild performs parallel compilation and leverages Go’s concurrency, often completing bundling in milliseconds even for large codebases.
    • Built‑in transpilation: it supports JSX and TypeScript out of the box, so you don’t need separate tools like Babel unless you have highly custom transforms.
    • Tree shaking: ESBuild analyzes import/export usage to eliminate dead code, producing smaller bundles.
    • Plugin system: you can extend ESBuild with plugins for asset handling, CSS bundling, or custom file types.
    • Simplicity: configuration is minimal—Rails’ -j esbuild flag generates sensible defaults, and you can tweak options in package.json or a separate esbuild.config.js.

    How Rails Integrates ESBuild

    When you run:

    rails new design_studio_react --database=postgresql -j esbuild
    

    Rails will:

    1. Install the esbuild npm package alongside react dependencies.

    2. Generate build scripts in package.json, e.g.:

    "scripts": { 
    "build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds", 
    "build:watch": "esbuild app/javascript/*.* --bundle --sourcemap --watch --outdir=app/assets/builds" 
    }
    

    3. Add a default app/assets/builds output directory and ensure Rails’ asset pipeline picks up the compiled files.

    Customizing ESBuild

    If you need to tweak ESBuild settings:

    Add an esbuild.config.js at your project root:

    const esbuild = require('esbuild')
    
    esbuild.build({
      entryPoints: ['app/javascript/application.js'],
      bundle: true,
      sourcemap: true,
      outdir: 'app/assets/builds',
      loader: { '.js': 'jsx', '.png': 'file' },
      define: { 'process.env.NODE_ENV': '"production"' },
    }).catch(() => process.exit(1))
    

    Update package.json scripts to use this config:

    "scripts": {
      "build": "node esbuild.config.js",
      "build:watch": "node esbuild.config.js --watch"
    }
    

    Why ESBuild Matters for React in Rails

    • Developer experience: near-instant rebuilds let you see JSX changes live without delay.
    • Production readiness: built‑in minification and tree shaking keep your asset sizes small.
    • Future-proof: the plugin ecosystem grows, and Rails can adopt newer bundlers (like SWC or Vite) with a similar pattern.

    With ESBuild, your React components compile quickly, your development loop tightens, and your production assets stay optimized—making it the perfect companion for a modern Rails 8 + React stack.

    5. What is Virtual DOM

    The Virtual DOM is one of React’s most important concepts. Let me explain it clearly with examples.

    🎯 What is the Virtual DOM?

    The Virtual DOM is a JavaScript representation (copy) of the actual DOM that React keeps in memory. It’s a lightweight JavaScript object that describes what the UI should look like.

    📚 Real DOM vs Virtual DOM

    Real DOM (What the browser uses):
    <!-- This is the actual DOM in the browser -->
    <div id="todo-app">
      <h1>My Todo List</h1>
      <ul>
        <li>React List</li>
        <li>Build a todo app</li>
      </ul>
    </div>
    
    Virtual DOM (React’s JavaScript representation):
    // This is React's Virtual DOM representation
    {
      type: 'div',
      props: {
        id: 'todo-app',
        children: [
          {
            type: 'h1',
            props: {
              children: 'My Todo List'
            }
          },
          {
            type: 'ul',
            props: {
              children: [
                {
                  type: 'li',
                  props: {
                    children: 'React List'
                  }
                },
                {
                  type: 'li',
                  props: {
                    children: 'Build a todo app'
                  }
                }
              ]
            }
          }
        ]
      }
    }
    

    🔄 How Virtual DOM Works – The Process

    Step 1: Initial Render
    // Your JSX
    const App = () => {
      return (
        <div>
          <h1>My Todo List</h1>
          <ul>
            <li>React List</li>
          </ul>
        </div>
      );
    };
    
    // React creates Virtual DOM
    const virtualDOM = {
      type: 'div',
      props: {
        children: [
          { type: 'h1', props: { children: 'My Todo List' } },
          { 
            type: 'ul', 
            props: { 
              children: [
                { type: 'li', props: { children: 'React List' } }
              ]
            }
          }
        ]
      }
    };
    
    Step 2: State Changes
    // When you add a new todo
    const App = () => {
      const [todos, setTodos] = useState(['React List']);
    
      const addTodo = () => {
        setTodos(['React List', 'Build Todo App']); // State change!
      };
    
      return (
        <div>
          <h1>My Todo List</h1>
          <ul>
            {todos.map(todo => <li key={todo}>{todo}</li>)}
          </ul>
          <button onClick={addTodo}>Add Todo</button>
        </div>
      );
    };
    
    Step 3: New Virtual DOM is Created
    // React creates NEW Virtual DOM
    const newVirtualDOM = {
      type: 'div',
      props: {
        children: [
          { type: 'h1', props: { children: 'My Todo List' } },
          { 
            type: 'ul', 
            props: { 
              children: [
                { type: 'li', props: { children: 'React List' } },
                { type: 'li', props: { children: 'Build Todo App' } } // NEW!
              ]
            }
          },
          { type: 'button', props: { children: 'Add Todo' } }
        ]
      }
    };
    
    Step 4: Diffing Algorithm
    // React compares old vs new Virtual DOM
    const differences = [
      {
        type: 'ADD',
        location: 'ul.children',
        element: { type: 'li', props: { children: 'Build Todo App' } }
      }
    ];
    
    Step 5: Reconciliation (Updating Real DOM)
    // React updates ONLY what changed in the real DOM
    const ul = document.querySelector('ul');
    const newLi = document.createElement('li');
    newLi.textContent = 'Build Todo App';
    ul.appendChild(newLi); // Only this line runs!
    

    🚀 Why Virtual DOM is Fast

    Without Virtual DOM (Traditional approach):
    // Traditional DOM manipulation
    function updateTodoList(todos) {
      const ul = document.querySelector('ul');
      ul.innerHTML = ''; // Clear everything!
    
      todos.forEach(todo => {
        const li = document.createElement('li');
        li.textContent = todo;
        ul.appendChild(li); // Recreate everything!
      });
    }
    
    With Virtual DOM (React approach):
    // React's approach
    function updateTodoList(oldTodos, newTodos) {
      const differences = findDifferences(oldTodos, newTodos);
    
      differences.forEach(diff => {
        if (diff.type === 'ADD') {
          // Only add the new item
          const li = document.createElement('li');
          li.textContent = diff.todo;
          ul.appendChild(li);
        }
      });
    }
    

    🎭 Real Example with Our Todo App

    Let’s trace through what happens when you add a todo:

    Before Adding Todo:
    // Current state
    const [todos, setTodos] = useState([
      { id: 1, text: 'React List', completed: false },
      { id: 2, text: 'Build Todo App', completed: false }
    ]);
    
    // Virtual DOM representation
    {
      type: 'ul',
      props: {
        children: [
          { type: 'li', key: 1, props: { children: 'React List ⏳' } },
          { type: 'li', key: 2, props: { children: 'Build Todo App ⏳' } }
        ]
      }
    }
    
    After Adding Todo:
    // New state
    const [todos, setTodos] = useState([
      { id: 1, text: 'React List', completed: false },
      { id: 2, text: 'Build Todo App', completed: false },
      { id: 3, text: 'Master React Hooks', completed: false } // NEW!
    ]);
    
    // New Virtual DOM
    {
      type: 'ul',
      props: {
        children: [
          { type: 'li', key: 1, props: { children: 'React List ⏳' } },
          { type: 'li', key: 2, props: { children: 'Build Todo App ⏳' } },
          { type: 'li', key: 3, props: { children: 'Master React Hooks ⏳' } } // NEW!
        ]
      }
    }
    
    React’s Diffing Process:
    // React compares and finds:
    const changes = [
      {
        type: 'INSERT',
        location: 'ul',
        element: { type: 'li', key: 3, props: { children: 'Master React Hooks ⏳' } }
      }
    ];
    
    // React updates ONLY what changed:
    const ul = document.querySelector('ul');
    const newLi = document.createElement('li');
    newLi.textContent = 'Master React Hooks ⏳';
    ul.appendChild(newLi); // Only this operation!
    

    🎯 Key Benefits of Virtual DOM

    1. Performance:
    // Without Virtual DOM: Updates entire list
    document.querySelector('ul').innerHTML = generateEntireList(todos);
    
    // With Virtual DOM: Updates only what changed
    document.querySelector('ul').appendChild(newTodoElement);
    
    2. Predictability:
    // You write declarative code
    const TodoList = ({ todos }) => (
      <ul>
        {todos.map(todo => <li key={todo.id}>{todo.text}</li>)}
      </ul>
    );
    
    // React handles the imperative updates
    // You don't need to manually add/remove DOM elements
    
    3. Batching:
    // Multiple state updates in one event
    const handleButtonClick = () => {
      setTodos([...todos, newTodo]);     // Change 1
      setInputValue('');                 // Change 2
      setCount(count + 1);              // Change 3
    };
    
    // React batches these into one DOM update!
    

    🔧 Virtual DOM in Action – Debug Example

    You can actually see the Virtual DOM in action:

    import React, { useState } from 'react';
    
    const App = () => {
      const [todos, setTodos] = useState(['React List']);
    
      const addTodo = () => {
        console.log('Before update:', todos);
        setTodos([...todos, 'New Todo']);
        console.log('After update:', todos); // Still old value!
      };
    
      console.log('Rendering with todos:', todos);
    
      return (
        <div>
          <ul>
            {todos.map((todo, index) => (
              <li key={index}>{todo}</li>
            ))}
          </ul>
          <button onClick={addTodo}>Add Todo</button>
        </div>
      );
    };
    

    🎭 Common Misconceptions

    ❌ “Virtual DOM is always faster”
    // For simple apps, Virtual DOM has overhead
    // Direct DOM manipulation can be faster for simple operations
    document.getElementById('counter').textContent = count;
    
    ❌ “Virtual DOM prevents all DOM operations”
    // React still manipulates the real DOM
    // Virtual DOM just makes it smarter about WHEN and HOW
    
    ✅ “Virtual DOM optimizes complex updates”
    // When you have many components and complex state changes
    // Virtual DOM's diffing algorithm is much more efficient
    

    🧠 Does React show Virtual DOM to the user?

    No. The user only ever sees the real DOM.
    The Virtual DOM (VDOM) is never shown directly. It’s just an internal tool used by React to optimize how and when the real DOM gets updated.

    🧩 What is Virtual DOM exactly?

    • A JavaScript-based, lightweight copy of the real DOM.
    • Stored in memory.
    • React uses it to figure out what changed after state/props updates.

    👀 What the user sees:

    • The real, visible HTML rendered to the browser — built from React components.
    • This is called the Real DOM.

    🔁 So why use Virtual DOM at all?

    ✅ Because manipulating the real DOM is slow.

    React uses VDOM to:

    1. Build a new virtual DOM after every change.
    2. Compare (diff) it with the previous one.
    3. Figure out the minimum real DOM updates required.
    4. Apply only those changes to the real DOM.

    This process is called reconciliation.

    🖼️ Visual Analogy

    Imagine the Virtual DOM as a sketchpad.
    React draws the new state on it, compares it with the old sketch, and only updates what actually changed in the real-world display (real DOM).

    ✅ TL;DR

    QuestionAnswer
    Does React show the virtual DOM to user?❌ No. Only the real DOM is ever visible to the user.
    What is virtual DOM used for?🧠 It’s used internally to calculate DOM changes efficiently.
    Is real DOM updated directly?✅ Yes, but only the minimal parts React determines from the VDOM diff.

    🧪 Example Scenario

    👤 The user is viewing a React app with a list of items and a button:

    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      ...
      <li>Item 10</li>
    </ul>
    <button>Read More</button>
    
    

    When the user clicks “Read More”, the app adds 10 more items to the list.

    🧠 Step-by-Step: What Happens Behind the Scenes

    ✅ 1. User Clicks “Read More” Button

    <button onClick={loadMore}>Read More</button>
    
    

    This triggers a React state update, e.g.:

    function loadMore() {
      setItems([...items, ...next10Items]); // updates state
    }
    
    

    🔁 State change → React starts re-rendering

    📦 2. React Creates a New Virtual DOM

    • React re-runs the component’s render function.
    • This generates a new Virtual DOM tree (just a JavaScript object structure).

    Example of the new VDOM:

    {
      type: "ul",
      children: [
        { type: "li", content: "Item 1" },
        ...
        { type: "li", content: "Item 20" } // 10 new items
      ]
    }
    
    

    🧮 3. React Diffs New Virtual DOM with Old One

    • Compares previous VDOM (10 <li> items) vs new VDOM (20 <li> items).
    • Finds that 10 new <li> nodes were added.

    This is called the reconciliation process.

    ⚙️ 4. React Updates the Real DOM

    • React tells the browser:
      “Please insert 10 new <li> elements inside the <ul>.”

    ✅ Only these 10 DOM operations happen.
    ❌ React does not recreate the entire <ul> or all 20 items.

    🖼️ What the User Sees

    On the screen (the real DOM):

    <ul>
      <li>Item 1</li>
      ...
      <li>Item 20</li>
    </ul>
    
    

    The user never sees the Virtual DOM — they only see the real DOM updates that React decides are necessary.

    🧠 Summary: Virtual DOM vs Real DOM

    StepVirtual DOMReal DOM
    Before click10 <li> nodes in memory10 items visible on screen
    On clickNew VDOM generated with 20 <li> nodesReact calculates changes
    DiffCompares new vs old VDOMDetermines: “Add 10 items”
    CommitNo UI shown from VDOMOnly those 10 new items added to browser DOM

    ✅ Key Point

    🧠 The Virtual DOM is a tool for React, not something the user sees.
    👁️ The user only sees the final, optimized changes in the real DOM.


    🎯 Summary

    Virtual DOM is React’s:

    1. JavaScript representation of the real DOM
    2. Diffing algorithm that compares old vs new Virtual DOM
    3. Reconciliation process that updates only what changed
    4. Performance optimization for complex applications
    5. Abstraction layer that lets you write declarative code

    Think of it as React’s smart assistant that:

    • Remembers what your UI looked like before
    • Compares it with what it should look like now
    • Makes only the necessary changes to the real DOM

    This is why you can write simple, declarative code like {todos.map(todo => <li>{todo}</li>)} and React handles all the complex DOM updates efficiently!


    🔄 After the Virtual DOM Diff, How React Updates the Real DOM

    🧠 Step-by-Step:

    1. React creates a diff between the new and previous virtual DOM trees.
    2. React then creates a list of “instructions” called the update queue.
      • Examples:
        • “Insert <li>Item 11</li> at position 10″
        • “Remove <div> at index 3″
        • “Change text of button to ‘Read Less'”
    3. These changes are passed to React’s reconciliation engine.
    4. React uses the browser’s DOM APIs (document.createElement, appendChild, removeChild, etc.) to apply only the minimal changes.

    ✅ So instead of doing:

    document.body.innerHTML = newHTML; // inefficient, replaces all
    
    

    React does:

    const newEl = document.createElement("li");
    newEl.textContent = "Item 11";
    ul.appendChild(newEl); // just this
    
    

    ❓ Why Didn’t Browsers Do This Earlier?

    Excellent historical question. The short answer is: Browsers give us the tools, but React gave us the strategy.

    ⚠️ Why browsers didn’t do it automatically:

    ReasonExplanation
    🧱 Low-level APIsThe browser exposes DOM APIs (appendChild, setAttribute), but they’re imperative — devs must write the logic.
    🤯 ComplexityManaging DOM efficiently across many updates (nested, reordered, conditional elements) is hard and bug-prone manually.
    🔁 Manual state syncingBefore React, developers had to manually keep UI in sync with state. That logic got complex and messy fast.
    📦 No built-in abstractionBrowsers don’t offer a built-in “virtual diff engine” or abstraction like React’s VDOM.

    🤖 What React Added That Browsers Don’t

    FeatureBrowser DOMReact (with VDOM)
    Efficient diffing❌ No✅ Yes (reconciliation)
    Declarative UI❌ No✅ Yes (return <UI />)
    Component abstraction❌ No✅ Yes (function/class components)
    State-driven rendering❌ Manual✅ Built-in
    Minimal updates❌ Up to you✅ Automatic via VDOM

    ✅ TL;DR

    • React calculates exactly what changed via the virtual DOM diffing.
    • It then uses native DOM APIs to update only what’s necessary in the real DOM.
    • Browsers give you low-level control, but not an optimized strategy for updating UI based on state — React filled that gap beautifully.

    Now Let’s break down how a React app starts after you run:

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

    What actually happens behind the scenes? Let’s unpack it step-by-step 👇

    ⚙️ Step 1: npx create-react-app — What It Does

    This command:

    • Downloads and runs the latest version of the create-react-app tool (CRA).
    • Sets up a project with:
      • A preconfigured Webpack + Babel build system
      • Development server
      • Scripts and dependencies
    • Installs React, ReactDOM, and a bunch of tools inside node_modules.

    Key folders/files created:

    my-app/
    ├── node_modules/
    ├── public/
    ├── src/
    │   └── index.js       👈 main entry point
    ├── package.json
    
    

    Step 2: npm start — How the App Runs

    When you run:

    npm start
    
    

    It’s actually running this line from package.json:

    "scripts": {
      "start": "react-scripts start"
    }
    
    

    So it calls:

    react-scripts start
    
    

    🧠 What is react-scripts?

    react-scripts is a package from Facebook that:

    • Runs a development server using Webpack Dev Server
    • Compiles JS/JSX using Babel
    • Watches your files for changes (HMR)
    • Starts a browser window at http://localhost:3000

    It configures:

    • Webpack
    • Babel
    • ESLint
    • PostCSS
    • Source maps
      … all behind the scenes, so you don’t have to set up any configs manually.

    📦 Libraries Involved

    Tool / LibraryPurpose
    ReactCore UI library (react)
    ReactDOMRenders React into actual DOM (react-dom)
    WebpackBundles your JS, CSS, images, etc.
    BabelConverts modern JS/JSX to browser-friendly JS
    Webpack Dev ServerStarts dev server with live reloading
    react-scriptsRuns all the above with pre-made configs

    🏗️ Step 3: Entry Point — src/index.js

    The app starts here:

    // src/index.js
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    
    const root = ReactDOM.createRoot(document.getElementById('root'));
    root.render(<App />);
    
    
    • ReactDOM.createRoot(...) finds the <div id="root"> in public/index.html.
    • Then renders the <App /> component into it.
    • The DOM inside the browser updates — and the user sees the UI.

    ✅ TL;DR

    StepWhat Happens
    npx create-react-appSets up a full React project with build tools
    npm startCalls react-scripts start, which runs Webpack dev server
    react-scriptsHandles build, hot reload, and environment setup
    index.jsLoads React and renders your <App /> to the browser DOM
    Browser OutputYou see your live React app at localhost:3000

    6. Installing and Configuring React

    Rails 8 provides a generator to bootstrap React + ESBuild.

    1. Run the React installer:
      rails javascript:install:react
      This will:
      • Install react and react-dom via npm.
      • Create an example app/javascript/components/HelloReact.jsx component.
      • Configure ESBuild to transpile JSX.
    2. Verify your application layout:
      In app/views/layouts/application.html.erb, ensure you have:
      <%= javascript_include_tag "application", type: "module", defer: true %>
    3. Mount the React component:
      Replace (or add) a div placeholder in an ERB view, e.g. app/views/home/index.html.erb:<div id="hello-react" data-props="{}"></div>
    4. Initialize mount point
      In app/javascript/application.js:
    import "./components"
    

    In app/javascript/components/index.js:

    import React from "react"
    import { createRoot } from "react-dom/client"
    import HelloReact from "./HelloReact"
    
    document.addEventListener("DOMContentLoaded", () => {
      const container = document.getElementById("hello-react")
      if (container) {
        const root = createRoot(container)
        const props = JSON.parse(container.dataset.props || "{}")
        root.render(<HelloReact {...props} />)
      }
    })
    

    Your React component will now render within the Rails view!

    See you in Part 2 … 🚀