so I was recently working on a web app and hit a classic development headache:
How do I make changes to a local copy of my database data without messing up the original?
Whether you're working with forms, dashboards, or temporary updates - this problem always sneaks in.
That's when I discovered a small but powerful package:
π @ungap/structured-clone
It instantly made my workflow cleaner, safer, and a lot less buggy. Here's how.
The Problem: Local Changes, Global Mess
here was my scenario:
- I fetched a complex object form MongoDB.
- I wanted to update some values locally - maybe a field like
status
ortitle
. - But I didn't want to mutate the original data until the changes were confirmed or submitted.
Spred Operator or Object.assign()
? Not Enough.
I tried the usual tricks:
const copy = { ...originalData };
// or
const copy - Object.assign({}, originalData);
These only perform shallow copies - they don't help if your object has nested fiedls, arrays, or objects inside.
One small update in the nested data, and - the original object gets affected too.
What Is @ungap/structured-clone
?
It's a tiny NPM package - a polyfill for the modern structuredClone()
Web API.
(which isn't available in all Node.js versions yet.)
It supports deep cloning of:
- Objects
- Arrays
- Maps & sets
- Dates
- Nested values (yep, even deeply nested structures)
Basically, it's like hitting "Duplicate Everything Safely for any JavaScript value".
How I Used It
Installation
npm install @ungap/structured-clone
Usage in My Project
import structuredClone from '@ungap/structured-clone';
const originalData = await getDataFromDatabase();
const localCopy = structuredClone(originalData);
// Make safe local changes
localCopy.status = "Published";
localCopy.updatedAt = new Date();
// Save only after confirming
await saveToDatabase(localCopy);
Simple. Safe. And it just works.
Why I Loved It
Here are the main benefits I experienced:
- No accidental mutations
- Peace of mind while editing deeply nested structures.
- Great for form editing, draft saving, or statement management
When Should You Use This?
If you're building apps with:
- Form editing with temporary state
- Undo/redo functionlity
- Draft and review workflows
- Any app where users change data before saving
This tiny tool can save you from unexpected bugs and data inconsistencies.
Bonus: It Plays Well with React
if you're into the React or MERN stack world like me, using structured cloning for local state updates (especially in context or reducers) can be a life-saver.
Final Thoughts
sometimes it's the smallest packages that solve the biggest frustrations.
@ungap/structured-clone
gave me the confidence to work with data safely, even in the most complex workflows.
If you're sill manually deep-cloning with weird hacks or libraries, give this a short - I promise you won't regret it.
NPM Link
Have you used structuredClone before? Or faced any horror stories with accidental data mutations?
Letβs chat in the comments π
Top comments (0)