🤯 I learned something today that completely changed how I see React. I've been using React for a while. But today I finally understood what's happening UNDER THE HOOD. Let me break it down 👇 🌳 The Problem with the Real DOM When your browser loads a page, it builds a tree of every element — buttons, divs, headings. That's the DOM. Every time something changes, the browser rebuilds parts of that tree. And touching the real DOM is SLOW. Imagine repainting one brick but rebuilding the entire wall to do it. 😩 ⚛️ So React created the Virtual DOM React keeps a lightweight copy of the DOM in JavaScript memory — invisible to the browser. Think of it as a blueprint of your house. Not the house itself. 🔄 What happens when state changes: 1️⃣ React takes a snapshot of the current Virtual DOM 2️⃣ Creates a new Virtual DOM with the update applied 3️⃣ Diffs the two — finds exactly what changed 4️⃣ Updates ONLY those parts in the real DOM Not the whole page. Just the diff. 🎯 The analogy that made it click: Bad way → Rewrite the entire Google Doc every time you fix a typo. React's way → Just fix the typo. Nothing else changes. That's the Virtual DOM. Every single update. 📌 DR: → React creates a Virtual DOM in memory → On state change, diffs old vs new → Updates ONLY what changed in the real DOM → Result = fast, smooth, efficient UI Most people use React for months before understanding this. Once you get it — everything makes sense. What's one concept that clicked for you late? Drop it below 👇 #React #ReactJS #JavaScript #WebDevelopment #Frontend #100DaysOfCode #LearnInPublic Sheryians Coding School Daneshwar Verma Devendra Dhote Ritik Rajput
React's Virtual DOM: Efficient UI Updates
More Relevant Posts
-
Today I learned about the useRef hook and how it helps us access DOM elements and persist values without re-rendering. 🔹 What is useRef? useRef is a React Hook that returns a mutable object with a .current property. It is mainly used for: • Accessing DOM elements • Storing values without causing re-render • Keeping previous values 🔹 Accessing DOM Elements We can directly access an element using useRef. import { useRef } from "react"; function App(){ const inputRef = useRef(); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={focusInput}>Focus</button> </> ); } Here React gives direct access to the input element. 🔹 Storing Values Without Re-render Unlike state, updating useRef does NOT re-render the component. const countRef = useRef(0); countRef.current++; This is useful when we want to store values without updating UI. 🔹 useRef vs useState • useState → causes re-render • useRef → does NOT cause re-render 💡 Key Takeaway useRef is useful when: ✔ You need direct access to DOM ✔ You want to store values without re-render ✔ You want better performance in some cases 📌 Day 16 of my 21 Days JavaScript / React Learning Challenge #ReactJS #JavaScript #ReactHooks #FrontendDevelopment #LearningInPublic
To view or add a comment, sign in
-
-
🌐 What is DOM in React.js? Before understanding React deeply, it’s important to understand the DOM (Document Object Model). The DOM represents a web page as a tree structure, where every HTML element is a node that JavaScript can interact with. 🧠 In simple terms: 👉 DOM = Structure of your web page 👉 It allows you to read, update, style, and handle events ⚙️ How it works: When a browser loads a webpage: 1️⃣ HTML is parsed 2️⃣ Converted into a DOM tree 3️⃣ JavaScript can interact with it 🚀 Why it matters in React? Directly updating the DOM is slow and expensive. That’s why React uses: ✔ Virtual DOM ✔ Efficient updates ✔ Reconciliation to update only the changed parts of the UI 💡 Key Takeaway Understanding DOM is the first step to understanding how React actually works behind the scenes. Still learning. Still building. 🚀 — Anuj Pathak #reactjs #javascript #webdevelopment #frontenddevelopment #softwareengineering #developersoflinkedin #programming #techlearning #coding #learninginpublic
To view or add a comment, sign in
-
-
React fundamentals to get right early Understanding onClick and onChange is key to handling events correctly in React A common pattern to be aware of: onClick={handleClick(id)} This executes immediately during render --- Correct approach: onClick={() => handleClick(id)} This runs only when the user clicks --- Why? React expects a function reference, not a function call - handleClick → correct - handleClick() → executes immediately --- Same concept applies to onChange: onChange={handleChange(value)} // executes immediately Better: onChange={(e) => handleChange(e.target.value)} --- Simple rule: If you need to pass arguments → use an arrow function --- Things to watch out for: - Functions running on every render - Unintended API calls - Difficult-to-debug behavior --- Benefits of correct usage: - Runs only on user interaction - More predictable component behavior - Cleaner and maintainable code --- Additional note: onClick={handleClick} (if your function expects arguments) This may result in "undefined" --- Example: {users.map(user => ( <button onClick={() => handleClick(user.id)}> Click </button> ))} --- Focusing on fundamentals like this helps build more reliable React applications #ReactJS #JavaScript #Frontend #WebDevelopment
To view or add a comment, sign in
-
-
How I Learned to Optimize 100k+ Items in React One day I built a simple list in React. Everything was fine… until I loaded 100,000+ items 😅 Suddenly: • UI became slow • Scrolling lagged • My laptop fan started acting like a jet engine ✈️ I thought: 👉 “React is slow.” But I was wrong. 🧠 Then I asked a better question 👉 Do users really need to see 100,000 items at once? The answer was obvious: ❌ No. Users only see what’s on the screen. 💡 That’s when it clicked Instead of rendering everything, I should render only visible items. This concept is called: 👉 Virtualization 🧠 Human version of this Imagine a long book 📖 You don’t read all pages at once. You only read the current page. Same idea. 🚀 What I changed Instead of: ❌ Rendering 100k items I did: ✅ Render only 20–30 visible items ✅ Load more as user scrolls 🔧 Tools that helped me • react-window • react-virtualized These libraries handle everything smartly. ⚡ Extra optimizations I learned • Use useMemo for heavy calculations • Use useCallback for stable functions • Avoid unnecessary re-renders • Keep components lightweight 💡 The biggest lesson Performance is not about doing more. It’s about doing less… smartly. Now whenever my app slows down, I ask: 👉 Am I rendering more than needed? Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook #Performance
To view or add a comment, sign in
-
-
🚀 What is a Polyfill in JavaScript? (And why every frontend dev should care) Ever tried using a modern JS feature… and it just breaks in older browsers? 😅 That’s where Polyfills come in. 👉 A polyfill is a piece of code that adds support for features that a browser doesn’t natively support. 💡 Simple idea: “If the browser doesn’t support it, I’ll implement it.” 🔧 Example: Array.includes() polyfill if (!Array.prototype.includes) { Array.prototype.includes = function (value) { return this.indexOf(value) !== -1; }; } ✔️ Now even older browsers can use includes()! ⚙️ Why Polyfills Matter Ensure cross-browser compatibility Let you use modern JavaScript safely Critical for production-grade apps 🧠 Polyfill vs Transpiler Polyfill → Adds missing functionality Transpiler (Babel) → Converts modern syntax to older syntax 👉 You often need both in real-world apps. 📦 Pro Tip Instead of writing polyfills manually: Use core-js Use CDN like polyfill.io Let Babel handle it automatically ⚠️ Be mindful Polyfills can increase bundle size — use them only when necessary. 🔥 Takeaway Polyfills help you write modern code without breaking older environments — making your app more reliable and user-friendly. #JavaScript #WebDevelopment #Frontend #Coding #SoftwareEngineering #DevTips #100DaysOfCode #Programming #Tech #Developers
To view or add a comment, sign in
-
-
🚀 Understanding Class Components in React One concept that helped me understand how components work internally was Class Components. Before Hooks became popular, class components were the primary way to manage state and lifecycle methods in React applications. A class component is simply a JavaScript class that extends React.Component and must contain a render() method that returns JSX. Example: import React, { Component } from "react"; class Welcome extends Component { render() { return <h1>Hello World</h1>; } } export default Welcome; In class components: 🔹 Props are accessed using this.props 🔹 State is managed using this.state 🔹 State updates are done with this.setState() 🔹 Lifecycle methods like componentDidMount() allow us to run code when the component mounts, updates, or unmounts. Example with state: class Counter extends Component { state = { count: 0 }; increase = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <button onClick={this.increase}> {this.state.count} </button> ); } } Today, most developers prefer Functional Components with Hooks like useState and useEffect, but understanding Class Components is still valuable because: ✅ Many legacy React projects still use them ✅ They help you understand React's lifecycle deeply ✅ Some interview questions still cover them Learning both approaches gives you a stronger foundation in React. Sometimes, understanding the old way helps you appreciate the modern way even more. #React #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic
To view or add a comment, sign in
-
⚛️ In React, these three onClick patterns look almost identical… but behave very differently. onClick={handleAddItem} onClick={handleAddItem(item)} onClick={() => handleAddItem(item)} At a glance they seem similar, but the execution timing is completely different. 🔹 onClick={handleAddItem} Passes the function reference → runs only when the click event occurs. 🔹 onClick={handleAddItem(item)} Executes immediately during render, not on click. This can lead to unexpected behavior like unnecessary API calls or extra re-renders. 🔹 onClick={() => handleAddItem(item)} Creates a callback function that runs on click and allows you to pass parameters. ✅ Rule of thumb • No parameters → onClick={handleAddItem} • Need parameters → onClick={() => handleAddItem(item)} • Avoid → onClick={handleAddItem(item)} 💡 One more interesting detail Arrow functions create a new function on every render. In most cases this is perfectly fine. However, in large lists or memoized components (React.memo), this can sometimes trigger unnecessary re-renders. That’s why some developers use useCallback or pre-defined handlers for optimization. 👨💻 How do you usually handle this in your projects? Arrow functions, useCallback, or another pattern? #React #JavaScript #FrontendDevelopment
To view or add a comment, sign in
-
7 React Hooks You Must Master React Hooks replaced class components and changed how every React developer thinks about state, side effects, and performance. Master these 7 and you can handle 95 percent of React challenges. -> useState Your component's memory. Stores local state and triggers a re-render when it changes. The most used hook in React by a significant margin. -> useEffect Handles everything that happens outside the render cycle. API calls, subscriptions, timers, and DOM manipulation all live here. Runs after every render unless you control its dependency array. -> useContext Access global state without passing props through every level of the component tree. Works perfectly with the Context API for theme, auth, and shared configuration. -> useRef Two jobs: access DOM elements directly without a re-render, and store values that persist across renders without causing re-renders. More powerful than most developers realize when they first learn it. -> useMemo Memorizes the result of an expensive calculation. Only recalculates when its dependencies change. Use it when a computation is genuinely expensive and runs on every render. -> useCallback Memorizes a function reference between renders. When you pass a callback to a child component, useCallback prevents the child from re-rendering because it receives a new function reference every render. -> useReducer Complex state logic that involves multiple sub-values or state transitions that depend on the previous state. Think of it as a mini Redux built directly into React. More predictable than multiple useState calls for complex state. These seven hooks cover state management, side effects, performance optimization, and DOM interaction. Everything else in React builds on these foundations. Which of these seven do you use least and think you should probably use more? #React #ReactHooks #FrontendDevelopment #JavaScript #WebDevelopment #Developers
To view or add a comment, sign in
-
-
A very common React mistake I see developers make: Mutating State When I was learning React, one concept that changed the way I write code was this rule: 👉 React state must never be mutated.its always immutable. But why? React does not deeply compare objects or arrays when state updates. Instead, it performs a reference(memory) comparison. That means React checks: Old State === New State ? If the reference is the same, React assumes nothing changed and skips re-rendering. Example of a mistake: cart.push(product) // ❌ Mutating state setCart(cart) Here we modified the same array in memory, so React may not detect the change because the memory location is same.so no re-render..no UI update. The correct approach is immutability: setCart([...cart, product]) // ✅ Creating a new array Now React sees a new reference, triggers reconciliation, and updates the UI correctly. 💡 Why React prefers immutability: • Faster change detection • Predictable state updates • Easier debugging • Better performance This small concept explains why patterns like: map() filter() spread operator (...) are used so frequently in React. because all this returns new object or array... Understanding this helped me write cleaner and more reliable React components. What React concept took you the longest to understand? 🤔 #React #Frontend #JavaScript #WebDevelopment #ReactJS
To view or add a comment, sign in
-
-
Understanding why a component re-renders in React, even when it seems nothing has changed, is crucial for optimizing performance. In the example of the Parent component, we have: ```javascript function Parent() { const [count, setCount] = useState(0); const handleClick = () => { console.log("Clicked"); }; return <Child onClick={handleClick} />; } ``` Even when the Child component is wrapped with React.memo, it still re-renders. The reason is that functions in JavaScript are re-created on every render. Therefore, on each render, `handleClick` is not equal to the previous `handleClick`, leading React to perceive it as a new prop. As a result, the Child component receives a new function reference, prompting React to think the props have changed, which causes the Child to re-render. To prevent this, we can use `useCallback` to memoize the function: ```javascript const handleClick = useCallback(() => { console.log("Clicked"); }, []); ``` This way, React retains the same function reference between renders. Key Insight: React compares references, not function logic. However, it's important to note that `useCallback` should not be overused. It is best utilized when: - Passing functions to child components - Optimizing performance with React.memo #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CodingJourney #LearninglnPublic #DeveloperLife #ReactInternals #FrontendEngineer #TechInterview #StateManagement #ReactHooks
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development