How to Implement Soft Delete and Restore in a React Admin Table with a Trash View

How to Implement Soft Delete and Restore in a React Admin Table with a Trash View

by | Nov 23, 2026 | Uncategorized | 0 comments

In brief: soft delete and restore in React works best when the server does the remembering and the user interface (UI) only reflects it. Your API marks a row with a deleted_at timestamp instead of removing it, hides marked rows from the default list, and exposes a restore endpoint that clears the timestamp.

The React admin table then gets a Trash view, restore and permanent delete actions, a confirmation step for anything irreversible, and cache updates that keep both lists honest.

This guide covers that front-end half of how to restore deleted data. You’ll find the API contract your table depends on, the trash view and optimistic updates with two popular data libraries. Bulk restore, cascades and the stale cache bugs that show up after a restore follow. The database side gets one section, because a few backend decisions (a partial unique index, a deletion marker on children) decide whether your restore button can ever work reliably.

How soft delete and restore work in React apps, from row to table

A hard delete runs SQL DELETE: the database physically removes the row, and only a backup can bring it back. A soft delete, also called logical deletion, runs an UPDATE that marks the record as deleted instead of physically removing it. The application then agrees to treat marked rows as gone. Restoring is the reverse UPDATE, so the deleted record comes back and preserves its original id, its relations and its history.

The marker can be a boolean such as is_deleted, but a nullable deleted_at timestamp is the better default because it also says when. Add a deleted_by column where your app has users, so the Trash view can show who removed what. A third option, a status column with values like active and archived, suits cases where archiving is a choice the user makes, not a deletion.

Here’s the full path for one click on “Delete” in your table:

  1. The table sends DELETE /projects/42.
  2. The server sets deleted_at = now() and deleted_by on that row.
  3. Every default query filters on deleted_at IS NULL, so lists, counts and exports exclude soft-deleted rows.
  4. The Trash view explicitly asks for deleted rows and shows each one with its deletion date.
  5. A restore sets deleted_at back to null, and a scheduled job hard-deletes rows once the retention window ends.

The catch fits in one sentence: to the database, a soft-deleted row still exists. It keeps its storage, its unique values and its foreign keys, and any query that forgets the filter returns it. Every pitfall later in this article comes from that.

Most server frameworks can apply the default filter for you, so nobody has to remember it in each query:

  • Entity Framework Core (EF Core): a global query filter declared with HasQueryFilter in the DbContext, bypassed with IgnoreQueryFilters() for the Trash. Some teams add an override of SaveChanges that turns every delete of a soft-deletable entity into an update.
  • Laravel: the Eloquent SoftDeletes trait, with onlyTrashed() for the Trash and restore() to bring a model back.
  • Django: a custom model manager whose default queryset excludes deleted rows, plus a second manager for the Trash.

Whichever you use, test related queries too. Django, for example, uses its base manager rather than your default one when code reads a related object such as task.project. A deleted parent can still show up there.

admin dashboard table

When to soft delete, and when a hard delete is the right call

Not everything deserves a trash bin. A useful test is simple: if this record came back tomorrow, would anyone care? If yes, soft delete it. If no, hard delete it and keep your tables lean.

Data Do this Avoid
Content people create: projects, documents, posts, comments Soft delete, Trash view, purge after the retention window A permanent delete behind a single click
Team members, invitations, customer records Soft delete, restore reserved to admins Letting a restored user regain access without a review
Sessions, password reset tokens, revoked API keys Hard delete at once Any “restore” path for credentials
Likes, view counts, cache entries Hard delete Filling a trash table with rows nobody will recover
Invoices, ledger entries, audit events Keep them, and block any cascade from reaching them Both soft and hard delete from the UI
Personal data under an erasure request Hard delete or irreversible anonymization Treating a deleted_at flag as erasure

That last row matters for any app with EU users. Article 17 of the General Data Protection Regulation (GDPR) gives people a right to erasure “without undue delay”. A flagged row that still identifies someone is still personal data you hold.

So keep a real permanent delete path next to the soft one, and don’t send erasure requests through the Trash. Article 5(1)(e) adds the storage limitation principle, which is one more reason to purge the trash on a schedule rather than keep it forever.

Is this worth it for a small app? Our view: yes for anything a customer can delete with a click and might ask for the same day. Restoring a full database backup to recover one project rolls every other user back with it, which is why a backup is not an undo button.

The API contract your React table depends on

Before you implement soft delete in the interface, make sure the API answers a few questions the same way every time. Decide them once, write them down, and let the table code assume them.

Action Request Success Expected failures
Soft delete DELETE /projects/{id} 204 No Content 404 if unknown, 412 if the version is stale
Active list GET /projects 200, deleted rows excluded None specific
Trash list GET /projects?status=deleted 200, with deleted_at and deleted_by 403 without the trash permission
Restore POST /projects/{id}/restore 200 with the restored resource 409 on a unique value conflict, 404 if already purged
Permanent delete DELETE /projects/{id}?permanent=true 204 403 for non-admins

A few rules make this contract predictable. The HTTP semantics standard, published as Request for Comments (RFC) 9110, defines DELETE as idempotent: repeating it has the same effect as sending it once. A second delete of an already deleted item should therefore not fail loudly. Return 204 again, or 404 if your API treats deleted items as absent, and document the choice.

The restore response should return the full resource, because the table can then put it back in the active list without a second request. Pagination totals must exclude deleted rows by default. Otherwise “Showing 1 to 20 of 23” sits above 20 rows and confuses everyone.

Permissions deserve separate scopes: one to delete, one to read the trash, one to restore. Who may restore is a product decision, not a technical one. In our view, a sensible default lets people restore what they deleted themselves, while admins see the whole bin. In a multi-tenant app, scope both delete and restore to the tenant, or a Trash view becomes a data leak.

On concurrency, the request can carry an If-Match header with an ETag (a version tag the server sends with each resource). If someone else edited the row in the meantime, the server answers 412 Precondition Failed instead of deleting a version the user never saw.

admin dashboard table

Building the trash view in a React admin table

A Trash view is the same table with a different filter, not a separate screen to maintain. Put it behind a tab or a route such as /projects/trash, and drive it from the URL so a link or a refresh lands in the right place.

The columns change slightly. Show the name, “Deleted on”, “Deleted by” and, if you purge on a schedule, “Permanently deleted on”. That last date answers the question users actually have: how long do I have to change my mind?

The row actions change too. Replace Edit and Delete with Restore and Delete permanently. Editing a deleted item rarely makes sense, and it creates odd states where a hidden row changes under everyone’s feet.

The two actions don’t deserve the same friction:

  • A soft delete is reversible, so it needs no confirmation modal. An undo toast is enough and keeps the table fast to use.
  • A permanent delete is not reversible, so it gets a confirmation dialog that names the item and the consequence (“Delete ‘Q3 roadmap’ permanently? This can’t be undone.”).
  • Bulk permanent delete gets the strongest confirmation, such as typing the number of items.

Accessibility rules point the same way. WCAG 2.2, the Web Content Accessibility Guidelines, includes success criterion 3.3.4, which asks that actions deleting user data be reversible, checked or confirmed. XPO Soft-Delete without deleting relations covers this in more depth.

Build the dialog with the WAI-ARIA alertdialog role (WAI-ARIA is the World Wide Web Consortium specification for accessible widgets). Move focus into it and put initial focus on the safe button. Announce the undo toast through a role="status" region so screen reader users hear it.

Finally, give the empty Trash a message rather than an empty grid: “Nothing in the trash. Deleted projects stay here for 30 days.” Users then know the safety net exists before they need it.

Optimistic soft delete and restore with TanStack Query

An optimistic update changes the cache before the server answers, then rolls back if the request fails. For delete and restore, it makes the table feel instant. The pattern in TanStack Query (React Query) uses useMutation with three callbacks: onMutate to snapshot and patch, onError to roll back, and onSettled to refetch.

const queryClient = useQueryClient();
const trashKey = ['projects', { status: 'deleted' }];

const restore = useMutation({
  mutationFn: (id) => api.post(`/projects/${id}/restore`),
  onMutate: async (id) => {
    await queryClient.cancelQueries({ queryKey: ['projects'] });
    const previousTrash = queryClient.getQueryData(trashKey);
    queryClient.setQueryData(trashKey, (old = []) =>
      old.filter((p) => p.id !== id));
    return { previousTrash };
  },
  onError: (error, id, context) => {
    queryClient.setQueryData(trashKey, context.previousTrash);
  },
  onSettled: () =>
    queryClient.invalidateQueries({ queryKey: ['projects'] }),
});

Three details make this work. First, cancelQueries stops an in-flight refetch from overwriting your optimistic patch. Second, the query keys share the ['projects'] prefix, and invalidateQueries matches by prefix, so one call refreshes the active list, the trash and the counts. Third, the rollback restores the snapshot taken before the patch, not a guess.

The soft delete mutation mirrors this: remove the row from the active list in onMutate, roll back in onError, invalidate in onSettled. For paginated or infinite lists, patch every cached page, or skip the optimistic step and rely on invalidation alone. A half-patched cache is worse than a 200-millisecond wait.

The official TanStack Query guide to optimistic updates also shows a lighter variant that renders the pending mutation’s variables instead of touching the cache.

The same flow with Redux Toolkit Query

Redux Toolkit (RTK) ships its own data-fetching layer, RTK Query, which handles cache freshness with tags instead of query keys. Declare a tag type, let both lists provide it, and let every mutation invalidate it:

export const api = createApi({
  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
  tagTypes: ['Project'],
  endpoints: (build) => ({
    getProjects: build.query({
      query: (status = 'active') => `projects?status=${status}`,
      providesTags: ['Project'],
    }),
    restoreProject: build.mutation({
      query: (id) => ({ url: `projects/${id}/restore`, method: 'POST' }),
      invalidatesTags: ['Project'],
    }),
  }),
});

After a restore, both the active list and the Trash refetch, so neither shows a stale row. For an optimistic version, use onQueryStarted on the mutation, patch the trash list with api.util.updateQueryData('getProjects', 'deleted', draft => ...), and call patchResult.undo() if queryFulfilled rejects.

Which one to pick? Use whatever your app already uses. The soft delete logic lives on the server, and both libraries need only two things from it. They need a restore endpoint that returns the resource, and lists that share an invalidation key.

admin dashboard table

Undo toast or trash view: you need both

The Gmail-style “Item deleted. Undo” toast is the fastest recovery path, and it’s tempting to build it purely on the client. Keep the item in local state, start a timer, and send the real delete only when the toast disappears.

That approach breaks in a common case. If the user closes the tab or navigates away before the timer fires, the request may never leave the browser, and the item the user “deleted” is still there tomorrow. It also means a second device never sees the deletion.

The sturdier pattern sends the soft delete immediately. The toast’s Undo button then calls the restore endpoint, the same one the Trash view uses. You get one code path, one source of truth, and an undo that keeps working after the toast disappears.

Keep the toast short and never make it the only way back. People who read slowly or use a screen reader can miss a toast that vanishes after a few seconds. The Trash view is the long-lived safety net, and the toast is the shortcut to it. Soft Deletes and Restore is a useful companion to this.

Bulk restore and bulk permanent delete

Bulk actions need more care, because one request now carries many outcomes. Send the selected ids in one call, such as POST /projects/restore with {"ids": [12, 15, 19]}, and have the server answer per item rather than all or nothing.

A useful response lists the restored items and the failed ones, with a reason for each failure. Example: of three projects, two restore and one fails because an active project already uses its slug. The table should then:

  • remove the two restored rows from the Trash;
  • keep the failed row selected, with the reason shown inline;
  • offer a fix where one exists, such as “Restore with a new name”.

Clear the selection only after the response arrives. Clearing it on click leaves users unable to retry the items that failed. For very large selections, cap the batch size on the server and process the rest in a background job. A long transaction holds its row locks until it commits, so other edits to those rows wait.

Cascades: restore a parent without resurrecting its children

This bug is easy to miss in testing. Picture a project with tasks, where a user deletes two tasks on Monday. On Friday, someone deletes the whole project, which soft-deletes all its remaining tasks.

Next week, an admin restores the project, and the restore brings back every task, including the two deleted on purpose. The cause is that “restore children” usually means “restore every deleted child”. The fix is to record why each child left:

  • stamp children deleted by a cascade with the parent’s exact deleted_at value, or with a shared deletion id;
  • on restore, bring back only children that carry the parent’s marker;
  • leave children deleted on their own in the Trash, where users can still restore them one by one.

Database cascades won’t help here. An ON DELETE CASCADE rule fires on a real DELETE, and a soft delete is an UPDATE, so foreign keys never hear about it. Referential integrity across deleted and live rows becomes your API’s job. It should block restoring a child whose parent is still deleted, or return a clear 409 that the UI can explain.

Framework helpers stop at one model. Laravel’s restore(), for instance, brings back the model you call it on, so cascading restores across relations need your own code or a package.

admin dashboard table

Unique values and stale cache after a restore

A deleted row still holds its unique values. A user deletes the customer “[email protected]”, then creates a new one with the same email, and the database rejects it. Later, restoring the old one would create a duplicate. The database fix, on PostgreSQL, is a partial unique index that only covers active rows:

CREATE UNIQUE INDEX uniq_customers_email_active
  ON customers (lower(email))
  WHERE deleted_at IS NULL;

With that index, creating the new customer works, and restoring the old one fails with a constraint error that your API turns into a 409. The React side then shows a real choice instead of a generic “Something went wrong”.

The other family of bugs is stale data. These are the ones to check first, each written as symptom, cause and correction:

  • Restored row only appears after a refresh: you patched the trash cache but not the active list. Invalidate the shared prefix or tag.
  • Detail page still shows “deleted”: the detail query has its own key. Include it in the invalidation, or write the restored resource from the response into it.
  • Deleted item still appears in search: nothing told the search index. Remove the document on delete and re-index it on restore.
  • Another tab shows the old state: its cache is still fresh. Refetch on window focus, which TanStack Query does by default.
  • A CDN serves the trash list to the wrong user: a content delivery network cached a response that varies by permission. Mark trash responses as private and never cache them publicly.

Retention, purge and audit

Soft deletion without a purge only postpones the delete forever, and the table keeps growing. Pick a retention window, show it in the UI, and run a scheduled job that hard-deletes expired rows in small batches. Google Drive and Gmail both use 30 days for their trash, which makes it a familiar default for users.

Batch the purge to keep locks short. Note that PostgreSQL’s DELETE has no LIMIT clause, unlike MySQL’s, so a batch needs a subquery:

DELETE FROM projects
WHERE id IN (
  SELECT id FROM projects
  WHERE deleted_at < now() - interval '30 days'
  LIMIT 1000
);

Run it off-peak and repeat until it deletes nothing. If some records are under a legal hold, exclude them in the inner query rather than in a separate process.

For auditing, deleted_at and deleted_by answer “when” and “who”. If you also need “why” and a record of restores, write each delete and restore as an event in a separate audit log. A restore should log as a restore, never as a fresh create, so automations that run on “record created” don’t fire twice.

A checklist for your React trash view

  1. Classify each table: soft delete, hard delete, or never deletable from the UI.
  2. Add a nullable deleted_at and a deleted_by column.
  3. Make the active filter the default for lists, counts, exports and search.
  4. Replace plain unique indexes with partial ones on active rows.
  5. Define the API contract: delete, trash list, restore, permanent delete, status codes.
  6. Separate the delete, read-trash and restore permissions, scoped to the tenant.
  7. Add the Trash tab with deletion date, author and purge date.
  8. Send the soft delete immediately and wire Undo to the restore endpoint.
  9. Confirm permanent deletes in an accessible alertdialog.
  10. Invalidate every list and detail key after delete and restore.
  11. Mark cascaded children with the parent’s deletion marker.
  12. Schedule the purge in batches and keep a separate erasure path.

If you build only one thing this week, make it the restore endpoint that returns the resource, plus a default filter that nobody can forget. The Trash tab, the undo toast and the bulk actions are then small pieces of React on top of a contract you trust. For a business web app, we recommend that order every time: server rules first, interface second.

Planning an admin panel or a data-heavy web app? Our other web development guides cover the patterns that sit around this one.

FAQ

Does a trash view replace database backups?

No. A soft-deleted record lives in your current database, while a backup is a separate copy that protects against corruption, bad migrations and lost servers. The trash handles one user’s mistake; backups handle disasters.

Should I use a separate trash table instead of a deleted_at column?

It’s a real alternative. Moving deleted rows into an archive table keeps the main table clean and frees unique values at once. Restores and schema migrations get harder, though, and a move is a real DELETE that triggers database cascades. For most admin apps, a column plus a default filter is simpler to live with.

Is archiving the same as soft deleting?

Not quite. Archiving is a state the user chooses, like closing a project, and it deserves its own status value and its own filter. A soft delete means “I wanted this gone”, so archived items shouldn’t end up in the Trash, and deleted items shouldn’t appear under Archived. There is more on it in restore deleted posts.

How do I test that deleted rows never leak?

Write one test per read path: list, count, export, search and any report. Each test soft-deletes a record and checks that it’s absent, then restores it and checks that it’s back. New endpoints then fail the test suite instead of failing in production.

Can a restored item get a new id?

It shouldn’t. Keeping the original id is what keeps links, comments and history attached. If your design forces a new record, it’s a re-creation, not a restore, and the UI should say so.