Virtual Dom VS Re-Rendering
Understanding how React keeps things fast and efficient.
Virtual DOM: The Lazy Genius Behind React
Imagine your web page is a giant whiteboard. Every time a user clicks a button, types in a field, or drags a slider, something on that board needs to change. Now, if we had to erase and redraw the entire board every time—just to update one tiny sticky note—we’d go insane. That’s the real DOM for you: a bit of a drama queen. It takes every little update way too seriously and repaints the entire scene.
Enter: The Virtual DOM — Your Webpage’s Personal Assistant
- 🗂️ It keeps a perfect copy of your current whiteboard (your webpage).
- 👂 It quietly observes for any changes (“Hmm... a new letter just got typed.”).
- 📝 It scribbles down the changes in a notebook.
- 🔍 Then it compares the new changes with the old whiteboard like a detective solving a mystery.
- ✏️ Finally, it walks over to the real whiteboard and only updates the sticky note that changed.
Why This is Brilliant
Re-rendering – The Overthinker
Now, meet React’s re-rendering. Re-rendering is the process where a component (or part of your UI) is drawn again because something has changed. It’s like that overenthusiastic actor who thinks every scene change deserves a full performance.
React gets anxious:
“OMG! A button was clicked. State might have changed. Re-render EVERYTHING!”
So React starts re-rendering... and here’s where things could go off the rails.
Virtual DOM to the Rescue (Again)
It compares the updated version with the previous one, finds the differences (aka "diffing"), and then tells the real DOM:
“Relax. Just update this button’s color and we’re good.”
How Virtual DOM Saves the Day
1. State or Props Change
When a component's state or props change, React re-runs that component to produce new JSX.
2. New JSX → Virtual DOM
React uses the new JSX to build a new Virtual DOM tree (in-memory version of the real DOM).
3. Diffing Algorithm
React compares the old and new Virtual DOM to find the differences using a diffing algorithm.
4. Minimal DOM Updates
React updates only the changed parts in the real DOM, improving performance and speed.
So in a nutshell
• But thanks to the Virtual DOM, the real DOM only updates what’s truly changed.
• It’s like letting the intern (React) freak out while the assistant (Virtual DOM) quietly handles everything like a pro.