CRUD Operations in React

Create, Read, Update, and Delete data with useState

Create Read Update Delete

Table of Contents

Introduction

CRUD stands for:

OperationMeaning
CreateAdd new data
ReadDisplay data
UpdateEdit existing data
DeleteRemove data

CRUD operations are commonly used in student management systems, todo apps, e-commerce sites, admin dashboards, and employee management systems.

In React, CRUD is usually performed using useState, forms, event handling, and APIs or local state.

Simple CRUD Application Overview

In this tutorial, we build an app that can add users, display users, edit users, and delete users.

Step 1: Import useState

JSXimport React, { useState } from "react";

useState is used to store and update data.

Step 2: Create CRUD Component

JSXfunction App() { }

Step 3: Create State Variables

JSXconst [name, setName] = useState(""); const [users, setUsers] = useState([]); const [editIndex, setEditIndex] = useState(null);
VariablePurpose
nameStores input value
usersStores user list
editIndexTracks editing item

CREATE Operation

Add New User

JSXconst handleAddUser = () => { if (name === "") return; setUsers([...users, name]); setName(""); };
  • Adds new user into the array
  • Clears the input field
  • Uses the spread operator (...users)

Input Form Example

JSX<input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter Name" /> <button onClick={handleAddUser}> Add User </button>

READ Operation

Display Users

JSX<ul> {users.map((user, index) => ( <li key={index}> {user} </li> ))} </ul>
  • map() loops through the array
  • Displays each user
  • key helps React identify elements

DELETE Operation

Delete User

JSXconst handleDelete = (index) => { const updatedUsers = users.filter((_, i) => i !== index); setUsers(updatedUsers); };

Delete Button Example

JSX<button onClick={() => handleDelete(index)}> Delete </button>

filter() removes the selected item and updates state with the remaining users.

UPDATE Operation

Edit User Function

JSXconst handleEdit = (index) => { setName(users[index]); setEditIndex(index); };

Update User Function

JSXconst handleUpdate = () => { const updatedUsers = [...users]; updatedUsers[editIndex] = name; setUsers(updatedUsers); setName(""); setEditIndex(null); };
  • Copies the existing array
  • Updates the selected item
  • Saves the updated array

Edit Button Example

JSX<button onClick={() => handleEdit(index)}> Edit </button>

Complete CRUD Application

JSXimport React, { useState } from "react"; function App() { const [name, setName] = useState(""); const [users, setUsers] = useState([]); const [editIndex, setEditIndex] = useState(null); const handleAddUser = () => { if (name === "") return; setUsers([...users, name]); setName(""); }; const handleDelete = (index) => { const updatedUsers = users.filter((_, i) => i !== index); setUsers(updatedUsers); }; const handleEdit = (index) => { setName(users[index]); setEditIndex(index); }; const handleUpdate = () => { const updatedUsers = [...users]; updatedUsers[editIndex] = name; setUsers(updatedUsers); setName(""); setEditIndex(null); }; return ( <div> <h1>React CRUD Application</h1> <input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder="Enter Name" /> {editIndex === null ? ( <button onClick={handleAddUser}>Add</button> ) : ( <button onClick={handleUpdate}>Update</button> )} <ul> {users.map((user, index) => ( <li key={index}> {user} <button onClick={() => handleEdit(index)}>Edit</button> <button onClick={() => handleDelete(index)}>Delete</button> </li> ))} </ul> </div> ); } export default App;

Output Features

  • Add users
  • Display user list
  • Edit users
  • Delete users

CRUD Flow

Create → Read → Update → Delete

Advantages of CRUD Applications

Real-Time Data Management

Users can manage data dynamically without page reloads.

Reusable Logic

CRUD logic is reusable across many applications.

Better User Experience

Users can modify data instantly.

Foundation for Full-Stack Development

CRUD operations are used in MERN stack apps, admin panels, dashboards, and APIs.

CRUD with APIs

In real projects, CRUD operations connect with backend APIs using Fetch API or Axios.

OperationHTTP Method
CreatePOST
ReadGET
UpdatePUT
DeleteDELETE

Best Practices

  • Use unique IDs instead of array indexes for keys
  • Validate form inputs
  • Use separate components for form and list
  • Connect to a backend database in production apps
  • Handle errors properly

Summary

In this tutorial, you learned:

  • What CRUD is
  • Create, Read, Update, and Delete operations
  • Building a complete CRUD app in React

CRUD operations are one of the most important concepts in React application development.

React CRUD Application MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic React CRUD Application MCQs

1

CRUD stands for:

ACreate Read Update Delete
BCache Render Upload Download
CCompile Run Undo Debug
DCSS React Utility DOM
Explanation: Basic data operations in apps.
2

fetch('/api/items') in useEffect typically:

ALoads list on mount
BDeletes database
CStyles page
DReplaces Router
Explanation: GET request for Read operation.
3

POST request usually:

ACreates new resource on server
BOnly reads data
CDeletes all
DUpdates CSS
Explanation: Send JSON body with method POST.
4

PUT or PATCH often used for:

AUpdate existing resource
BCreate only
CLogout only
DRouting
Explanation: PUT full replace; PATCH partial update.
5

DELETE request:

ARemoves resource by id
BCreates duplicate
CCompiles JSX
DInstalls npm
Explanation: fetch(url, { method: 'DELETE' }).
6

Loading state during fetch shows:

ASpinner or skeleton UI
BNothing required
CAlways error
DFull page reload
Explanation: isLoading flag improves UX.
7

Error state from failed API should:

ADisplay message to user
BSilently fail always
CCrash app
DDelete all data
Explanation: catch errors and set error state.
8

Optimistic UI updates:

AUpdate UI before server confirms
BNever show changes
CSkip server
DDisable state
Explanation: Rollback if server fails.
9

JSON API Content-Type header:

Aapplication/json
Btext/html only
Cimage/png
Dmultipart only always
Explanation: Send JSON with proper headers.
10

Form submit for create often:

Aprevents default and POSTs new item
Breloads window always
Cuses only GET
Dskips validation
Explanation: handleSubmit + fetch POST pattern.

10 Advanced React CRUD Application MCQs

1

AbortController in CRUD list prevents:

AsetState on unmounted component after slow fetch
BAll CRUD
CJSON parsing
DKeys
Explanation: Abort fetch in effect cleanup.
2

Normalizing API list to id map helps:

AO(1) update/delete by id
BSlower updates
CRemove keys
DSkip React
Explanation: entities: { [id]: item } pattern.
3

React Query / RTK Query vs manual fetch:

ABuilt-in cache, refetch, loading states
BNo difference
CCannot do CRUD
DReplaces React
Explanation: Libraries reduce boilerplate and race bugs.
4

Pagination in CRUD table uses:

Apage/limit query params + state
Bonly client slice always for millions of rows
CMath.random keys
DinnerHTML
Explanation: Server pagination for large datasets.
5

Validation before create should:

ACheck required fields client-side; validate server-side too
BTrust client only
CSkip server
DUse innerHTML
Explanation: Never rely on client validation alone.
6

Idempotent DELETE means:

ARepeated delete has same effect
BCreates new rows
CUpdates twice
DCaches forever
Explanation: Deleting missing resource may return 404 OK.
7

HTTP 201 status means:

AResource created
BNot found
CServer error
DUnauthorized
Explanation: Often returned after successful POST.
8

Bearer token in Authorization header:

AAuthenticates API requests
BStyles CSS
CReplaces JSX
DKeys lists
Explanation: Authorization: Bearer <token>.
9

Concurrent edit conflict handled by:

AETags, versioning, or last-write-wins policy
BIgnoring server
CDeleting React
DRandom keys
Explanation: Design update strategy for conflicts.
10

Modal confirm before delete improves:

AUX and prevents accidental data loss
BPerformance only
CSEO
DJSX compile
Explanation: Confirm destructive actions.

15 React CRUD Application Interview Questions & Answers

Easy Medium Hard
1What is a React CRUD app?easy
Answer: UI to create, read, update, and delete records via API or backend.
2How fetch list of items?easy
Answer: useEffect + fetch GET, setItems on success, handle loading/error.
3How add new item?medium
Answer: POST with JSON body, append or refetch list on success.
4How update item?medium
Answer: PUT/PATCH to /items/:id with updated fields.
5How delete item?medium
Answer: DELETE /items/:id then filter state or refetch.
6Why handle loading and error states?easy
Answer: Better UX and debugging when network fails.
7What is optimistic update?hard
Answer: Update UI immediately, revert if server request fails.
8REST vs GraphQL for CRUD?hard
Answer: REST uses HTTP verbs on resources; GraphQL uses single endpoint with queries/mutations.
9Secure CRUD best practices?hard
Answer: Auth tokens, HTTPS, server validation, sanitize input, role checks.
10Prevent race in search/filter fetch?medium
Answer: Abort prior request or ignore stale responses with flag.
11Local state vs global for CRUD?medium
Answer: Local fine for single page; Redux/Query for shared cached data.
12Form state for create/edit?medium
Answer: Controlled inputs; reset on success; populate when editing.
13HTTP status codes to handle?medium
Answer: 400 validation, 401 auth, 404 not found, 500 server error.
14Refresh list after mutation?easy
Answer: Refetch GET or update local cache immutably.
15Testing CRUD components?hard
Answer: Mock fetch with MSW; assert UI for success/error paths.