<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Meenakshi Ratnawat on Medium]]></title>
        <description><![CDATA[Stories by Meenakshi Ratnawat on Medium]]></description>
        <link>https://medium.com/@meenakshiratnawat0?source=rss-4bd648b68fc2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-pmHXsTBbmHyhKhK</url>
            <title>Stories by Meenakshi Ratnawat on Medium</title>
            <link>https://medium.com/@meenakshiratnawat0?source=rss-4bd648b68fc2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:30:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@meenakshiratnawat0/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding var, let, and const in JavaScript]]></title>
            <link>https://medium.com/@meenakshiratnawat0/understanding-var-let-and-const-in-javascript-0728101665cd?source=rss-4bd648b68fc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0728101665cd</guid>
            <dc:creator><![CDATA[Meenakshi Ratnawat]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 09:29:50 GMT</pubDate>
            <atom:updated>2026-03-15T09:29:50.349Z</atom:updated>
            <content:encoded><![CDATA[<p>If you have ever written JavaScript and wondered why var, let, and const all exist for declaring variables, you are not alone. At first, they look very similar. But in real code, they behave quite differently. And if those differences are not clear, small bugs can become surprisingly confusing.</p><p>This is why understanding var, let, and const is not just useful for interviews. It is important for writing predictable and bug-free JavaScript.</p><h3><strong>WHY THIS TOPIC MATTERS</strong></h3><p>A weak understanding of var, let, and const can lead to problems like:</p><ul><li>values changing unexpectedly</li><li>variables leaking outside blocks</li><li>confusing loop behavior</li><li>errors before declaration</li><li>accidental reassignment</li></ul><p>That is why modern JavaScript usually prefers let and const over var.</p><h3>A QUICK OVERVIEW</h3><p>Before going deeper, here is the quick intuition:</p><ul><li>var is the older way of declaring variables</li><li>let is used when a variable’s value needs to change</li><li>const is used when a variable should not be reassigned</li></ul><p>That sounds simple, but the real difference is not just about changing values. The real difference comes from scope, hoisting, redeclaration, and reassignment.</p><p>Let’s understand each one properly.</p><h3><strong>var: The Older and Looser Variable Declaration</strong></h3><p>var was the main way to declare variables in JavaScript before ES6.</p><p>Example:</p><pre>function testVar() {<br>var x = 10;<br>if (true) {<br>var x = 20;<br>console.log(&quot;inside block:&quot;, x);<br>}<br>console.log(&quot;outside block:&quot;, x);<br>}<br>testVar();</pre><p>Output:</p><pre>inside block: 20<br>outside block: 20</pre><p>At first glance, this feels strange. Many beginners expect the outer x to remain 10.</p><p>But that does not happen.</p><p><strong>Why?</strong></p><p>Because var is function-scoped, not block-scoped.</p><p>That means an if block, for loop, or curly braces block does not create a separate scope for var. So the x declared inside the if block is not a new variable. It is the same x from the function.</p><p>In other words, this:</p><pre>function testVar() {<br>var x = 10;<br>if (true) {<br>var x = 20;<br>}<br>console.log(x);<br>}</pre><p>behaves almost like this:</p><pre>function testVar() {<br>var x = 10;<br>x = 20;<br>console.log(x);<br>}</pre><p>That is why var can easily create confusing behavior.</p><p>Key properties of var</p><p>var:</p><ul><li>is function-scoped</li><li>can be reassigned</li><li>can be redeclared in the same scope</li><li>is hoisted and initialized with undefined</li></ul><p><strong>Example of redeclaration:</strong></p><pre>var city = &quot;Delhi&quot;;<br>var city = &quot;Bengaluru&quot;;<br>console.log(city); // Bengaluru</pre><p><strong>Example of reassignment:</strong></p><pre>var count = 1;<br>count = 2;<br>console.log(count); // 2</pre><p>This loose behavior is one reason var is avoided in modern code.</p><ol><li>let — safer and block-scoped</li></ol><p>let was introduced in ES6 to fix many of the confusing parts of var.</p><p><strong>Example</strong>:</p><pre>function testLet() {<br>let x = 10;<br>if (true) {<br>let x = 20;<br>console.log(&quot;inside block:&quot;, x);<br>}<br>console.log(&quot;outside block:&quot;, x);<br>}<br>testLet();</pre><p><strong>Output</strong>:</p><pre>inside block: 20<br>outside block: 10</pre><p>Now the result feels much more natural.</p><p><strong>Why</strong>?</p><p>Because let is block-scoped.</p><p>That means the x inside the if block is a completely separate variable from the x outside it.</p><p>So unlike var, let respects block boundaries.</p><p>Key properties of let</p><p>let:</p><ul><li>is block-scoped</li><li>can be reassigned</li><li>cannot be redeclared in the same scope</li><li>is hoisted, but not initialized before declaration</li></ul><p><strong>Example of valid reassignment:</strong></p><pre>let score = 10;<br>score = 20;<br>console.log(score); // 20</pre><p><strong>Example of Invalid Redeclaration</strong></p><pre>let score = 10;<br>let score = 20; // Error</pre><p>That “cannot be redeclared in the same scope” line is very important.</p><p>It means this is not allowed:</p><pre>let name = &quot;Meenakshi&quot;;<br>let name = &quot;Ratnawat&quot;;<br>But this is allowed:<br>let name = &quot;Meenakshi&quot;;<br>name = &quot;Ratnawat&quot;;</pre><p>The first is redeclaration.</p><p>The second is reassignment.</p><p>That difference is small in wording, but huge in understanding.</p><h3>const: Fixed Reference, Not Fixed Object Contents</h3><p>const is also block-scoped like let, but it cannot be reassigned.</p><pre>const age = 25;<br>// age = 30; // Error</pre><p>A const variable must be initialized at the time of declaration:</p><pre>const city = &quot;Bengaluru&quot;;</pre><p>This is invalid:</p><pre>const city; // Error</pre><p>So far, this sounds simple.</p><p>But here comes the part that confuses many people:</p><p>Can a const object still be modified?</p><p>Yes.</p><pre>const user = { name: &quot;Meenakshi&quot; };<br>user.name = &quot;Ratnawat&quot;;<br>console.log(user.name); // Ratnawat</pre><p>This works.</p><p><strong>Why?</strong></p><p><em>Because const protects the variable reference, not the object’s internal properties.</em></p><p>So this is allowed:</p><pre>user.name = &quot;Ratnawat&quot;;</pre><p>But this is not allowed:</p><pre>user = { name: &quot;New User&quot; }; // Error</pre><p><em>This is one of the most important ideas to understand about const.</em>A strong way to remember it is:</p><p>const prevents reassignment, not mutation of object contents.</p><h3>Scope: The Real Game Changer</h3><p>If you understand scope clearly, most of this topic becomes easy.</p><p><strong>var</strong> <strong>is function-scoped</strong></p><pre>function demo() {<br>if (true) {<br>var a = 10;<br>}<br>console.log(a); // 10<br>}<br>demo();</pre><p>The variable declared inside the block is still available outside the block, as long as it is inside the same function.</p><p><strong>let and const are block-scoped</strong></p><pre>function demo() {<br>if (true) {<br>let a = 10;<br>const b = 20;<br>}<br>console.log(a); // Error<br>console.log(b); // Error<br>}<br>demo();</pre><p>This is the safer and more intuitive behavior.</p><p>That is why let and const are usually preferred.</p><h3>Hoisting: Same Idea, Different Behavior</h3><p>All three — var, let, and const — are hoisted.</p><p>But they do not behave the same way.</p><p>var hoisting</p><pre>console.log(a); // undefined<br>var a = 5;</pre><p>This works because JavaScript hoists the declaration and initializes it with undefined.</p><h4>Roughly, JavaScript treats it like this:</h4><pre>var a;<br>console.log(a);<br>a = 5;</pre><h4>let and const Hoisting</h4><pre>console.log(b); // ReferenceError<br>let b = 5;<br><br>console.log(c); // ReferenceError<br>const c = 10;</pre><p>These are also hoisted, but they are not initialized immediately.</p><p>That is why accessing them before declaration throws an error.</p><h3><strong>Temporal Dead Zone (TDZ)</strong></h3><p>This is where let and const become a little more technical.</p><p>The Temporal Dead Zone is the period between:</p><ul><li>entering the scope</li><li>and reaching the declaration line</li></ul><p>During this time, the variable exists, but cannot be accessed.</p><p>Example:</p><pre>{<br>console.log(name); // ReferenceError<br>let name = &quot;Meenakshi&quot;;<br>console.log(name);<br>}</pre><p>The same idea applies to const.</p><p>A strong interview-friendly explanation is:</p><p>let and const are hoisted, but they stay in the Temporal Dead Zone until their declaration is reached, so accessing them earlier throws a ReferenceError.</p><h3>Why let Is Safer Than var Inside Loops</h3><p>This is one of the most famous JavaScript traps.</p><p>Look at this:</p><pre>for (var i = 0; i &lt; 3; i++) {<br>setTimeout(() =&gt; console.log(i), 1000);<br>}</pre><p>Output:</p><pre>3<br>3<br>3</pre><p>Many learners expect:</p><pre>0<br>1<br>2</pre><p>But that is not what happens.</p><h4>Why?</h4><p>Because var is function-scoped, so the loop uses one shared i variable.</p><p>The setTimeout callbacks do not run immediately. The loop finishes first. By the time the callbacks run, i has already become 3.</p><p>So all callbacks print the same final value.</p><p>Now look at the let version:</p><pre>for (let i = 0; i &lt; 3; i++) {<br>setTimeout(() =&gt; console.log(i), 1000);<br>}</pre><p>Output:</p><pre>0<br>1<br>2</pre><h4>Why does this work?</h4><p>Because let creates a new binding for each loop iteration. So each callback gets its own i.</p><p>This is a very practical reason why let is safer than var.</p><h3>Reassignment vs redeclaration</h3><p>These two are often mixed up, so let’s separate them clearly.</p><h4>Reassignment</h4><p>Changing the value of an already declared variable:</p><p>let score = 10;</p><p>score = 20;</p><h4>Redeclaration</h4><p>Declaring the variable again in the same scope:</p><pre>let score = 10;<br>let score = 20; // Error</pre><h4><strong>Now</strong> compare all three:</h4><p>var</p><ul><li>reassignment allowed</li><li>redeclaration allowed</li></ul><p>let</p><ul><li>reassignment allowed</li><li>redeclaration not allowed in same scope</li></ul><p>const</p><ul><li>reassignment not allowed</li><li>redeclaration not allowed</li></ul><p>Once this distinction is clear, many confusions disappear.</p><h4>Which one should you use?</h4><p>A simple modern rule is:</p><p>Use const by default</p><p>If the variable reference does not need to change, use const.</p><p>Use let when reassignment is needed</p><p>If the variable value needs to change later, use let.</p><p>Avoid var</p><p>Because it is less predictable and easier to misuse.</p><p>This does not mean var is bad in itself. It means modern JavaScript gives us safer tools.</p><h3><strong>Final takeaway</strong></h3><p>If you only remember a few things from this topic, remember these:</p><ul><li>var is function-scoped and can behave unexpectedly inside blocks</li><li>let is block-scoped and safer when values need to change</li><li>const is block-scoped and prevents reassignment</li><li>const does not make objects fully immutable</li><li>let and const are hoisted, but stay in the Temporal Dead Zone before declaration</li><li>let is much safer than var in loops and callbacks</li></ul><p>That is the real practical understanding.</p><p><strong>Questions for readers</strong></p><p>Try answering these yourself before looking anything up:</p><ol><li>Why does var ignore block boundaries?</li><li>Why does let throw an error before declaration even though it is hoisted?</li><li>Why can a const object still be modified?</li><li>What is the difference between reassignment and redeclaration?</li><li>Why is let safer than var inside loops?</li><li>Why is const usually preferred in modern JavaScript?</li></ol><p>Try these output questions too:</p><pre>function demo() {<br>var x = 10;<br>if (true) {<br>var x = 20;<br>}<br>console.log(x); <br>}<br>demo(); <br><br>function demo() {<br>let x = 10;<br>if (true) {<br>let x = 20;<br>console.log(&quot;inside:&quot;, x);<br>}<br>console.log(&quot;outside:&quot;, x);<br>}<br>demo();<br>for (var i = 0; i &lt; 3; i++) {<br>setTimeout(() =&gt; console.log(i), 1000);<br>}<br>for (let i = 0; i &lt; 3; i++) {<br>setTimeout(() =&gt; console.log(i), 1000);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0728101665cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need to Know About Socket.IO — With a Practical Chat App Example]]></title>
            <link>https://medium.com/@meenakshiratnawat0/everything-you-need-to-know-about-socket-io-with-a-practical-chat-app-example-f779364827cc?source=rss-4bd648b68fc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f779364827cc</guid>
            <dc:creator><![CDATA[Meenakshi Ratnawat]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 19:26:37 GMT</pubDate>
            <atom:updated>2025-06-09T04:49:41.871Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building a Realtime Chat App with Socket.IO — A Practical Guide</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GU5artZi65SBYGF3dc35dw.png" /></figure><p>Realtime communication is everywhere today — chat apps, multiplayer games, collaborative tools, live notifications…</p><p>But how do these apps instantly send and receive data without constant refreshing?</p><p>The answer often lies in WebSockets — and more practically, in tools like Socket.IO, which make WebSockets easy to use.</p><h3>In this article, we will understand:</h3><ul><li>What is Socket.IO?</li><li>Why not just use HTTP?</li><li>How does Socket.IO work?</li><li>Key concepts in Socket.IO</li><li>Example: How we use Socket.IO in our chat app (real production example)</li><li>All realtime events used</li><li>Tips and best practices</li></ul><p><strong>GitHub Repo:</strong> <a href="https://github.com/Meenakshiratnawat/pingme-chat-application">Link</a></p><h3>What is Socket.IO?</h3><p>Socket.IO is a JavaScript library that enables bidirectional, realtime communication between client and server.</p><p>It’s built on top of WebSockets — but adds many useful features:</p><ul><li>Automatic reconnection</li><li>Fallback to other transports if WebSocket is not available</li><li>Event-based API</li><li>Works great with Node.js</li><li>Plays well with authentication and CORS</li></ul><p>In short: It makes realtime programming easy and reliable.</p><h3>Why not just use HTTP?</h3><p>Classic HTTP is:</p><ul><li>Request-response: The client must request data from the server.</li><li>One-way: The server cannot push data to the client unless the client polls it.</li></ul><p>But for realtime apps like:</p><ul><li>Chat</li><li>Notifications</li><li>Live dashboards</li><li>Collaborative editing</li><li>Games</li></ul><p>…you want the server to push data to the client instantly — which HTTP doesn’t support well.</p><p>This is why WebSockets are used — they provide a persistent, bidirectional connection.</p><h3>How does Socket.IO work?</h3><p>At a high level:</p><p>Frontend → Socket.IO Client</p><p>Backend → Socket.IO Server</p><ol><li>The client (browser) connects to the server using the Socket.IO client library.</li><li>The server (Node.js + Socket.IO server) accepts the connection.</li><li>The client and server can now emit events to each other:</li></ol><pre>socket.emit(&quot;eventName&quot;, data);<br><br>socket.on(&quot;eventName&quot;, callback);</pre><p>4. The connection stays open — so both sides can send data anytime.</p><h3>Key concepts in Socket.IO</h3><h3>Events</h3><p>Communication is event-based — both client and server can emit and listen for events:</p><pre>socket.emit(&quot;message&quot;, { text: &quot;Hello!&quot; });<br><br>socket.on(&quot;message&quot;, (data) =&gt; {<br>  console.log(data.text);<br>});</pre><h3>Rooms</h3><p>Sockets can join rooms — useful for:</p><ul><li>Group chat</li><li>Game rooms</li><li>Private channels</li></ul><pre>socket.join(&quot;roomId&quot;);<br><br>io.to(&quot;roomId&quot;).emit(&quot;newMessage&quot;, message);</pre><h3>Reconnection</h3><p>If the connection drops (ex: network change), Socket.IO automatically reconnects.</p><h3>Fallbacks</h3><p>If WebSockets are not supported, Socket.IO falls back to:</p><ul><li>Long-polling</li><li>Other transports</li></ul><p>This ensures maximum compatibility.</p><h3>Example: How We Use Socket.IO in Our Chat App</h3><p>Let me show you a real example — how we use Socket.IO to power realtime chat in our app.</p><h3>Architecture Overview</h3><p>Frontend → Socket.IO Client</p><p>Backend → Socket.IO Server</p><p>Each user’s browser establishes a persistent socket connection to the backend.</p><p>The server tracks which users are online and emits events:</p><ul><li>New messages</li><li>Typing indicators</li><li>Read receipts</li><li>Contact requests</li><li>Contact request acceptance</li></ul><h3>Our Frontend Code</h3><p>Simplified example from our React app:</p><pre>connectSocket: () =&gt; {<br>  const { authUser } = get();<br>  if (!authUser || get().socket?.connected) return;<br><br>  const socket = io(BASE_URL, {<br>    query: {<br>      userId: authUser._id,<br>    },<br>  });<br><br>  socket.connect();<br><br>  set({ socket: socket });<br><br>  socket.on(&quot;getOnlineUsers&quot;, (userIds) =&gt; {<br>    set({ onlineUsers: userIds });<br>  });<br>},</pre><p>Flow:</p><ol><li>After login, we call connectSocket().</li><li>The client connects and sends userId.</li><li>The server adds this user to userSocketMap and emits getOnlineUsers.</li><li>The client listens for getOnlineUsers and updates UI.</li></ol><h3>Our Backend Code</h3><p>Simplified socket.js:</p><pre>const io = new Server(server, {<br>  cors: {<br>    origin: [&quot;http://localhost:5173&quot;],<br>    credentials: true<br>  },<br>});<br><br>const userSocketMap = {};<br><br>io.on(&quot;connection&quot;, (socket) =&gt; {<br>  const userId = socket.handshake.query.userId;<br>  if (userId) userSocketMap[userId] = socket.id;<br><br>  io.emit(&quot;getOnlineUsers&quot;, Object.keys(userSocketMap));<br><br>  socket.on(&quot;disconnect&quot;, () =&gt; {<br>    delete userSocketMap[userId];<br>    io.emit(&quot;getOnlineUsers&quot;, Object.keys(userSocketMap));<br>  });<br><br>  socket.on(&quot;contact-request&quot;, ({ senderId, receiverId, senderName }) =&gt; {<br>    io.to(receiverId).emit(&quot;contact-request-received&quot;, {<br>      senderId,<br>      senderName,<br>      message: `${senderName} wants to add you as a contact.`,<br>    });<br>  });<br><br>  socket.on(&quot;typing&quot;, ({ senderId, receiverId }) =&gt; {<br>    const receiverSocketId = userSocketMap[receiverId];<br>    if (receiverSocketId) {<br>      io.to(receiverSocketId).emit(&quot;typing&quot;, { senderId });<br>    }<br>  });<br><br>  socket.on(&quot;stopTyping&quot;, ({ senderId, receiverId }) =&gt; {<br>    const receiverSocketId = userSocketMap[receiverId];<br>    if (receiverSocketId) {<br>      io.to(receiverSocketId).emit(&quot;stopTyping&quot;, { senderId });<br>    }<br>  });<br><br>  socket.on(&quot;chat-opened&quot;, async ({ readerId, senderId }) =&gt; {<br>    // Mark messages as read, emit messages-read<br>  });<br><br>  socket.on(&quot;contact-accept&quot;, ({ senderId, receiverId }) =&gt; {<br>    io.to(senderId).emit(&quot;contact-accepted&quot;, { contactId: receiverId });<br>    io.to(receiverId).emit(&quot;contact-accepted&quot;, { contactId: senderId });<br>  });<br>});</pre><h3>All Realtime Events We Used</h3><ul><li><strong>getOnlineUsers</strong> — Track online users</li><li><strong>newMessage</strong> — Deliver new messages</li><li><strong>typing</strong> — Typing indicator</li><li><strong>stopTyping</strong> — Stop typing indicator</li><li><strong>chat-opened</strong> — Trigger read receipts</li><li><strong>messages-read</strong> — Notify sender of read messages</li><li><strong>contact-request</strong> — Send contact request</li><li><strong>contact-request-received</strong> — Receive contact request notification</li><li><strong>contact-accept</strong> — Accept contact request</li><li><strong>contact-accepted</strong> — Notify both users of contact acceptance</li></ul><h3>Tips and Best Practices</h3><ul><li>Use userSocketMap or similar to track online users.</li><li>Handle disconnect carefully — update presence status.</li><li>Watch out for multiple tabs — one userId may map to multiple socket IDs.</li><li>Use rooms for scalable group messaging if needed.</li><li>Keep socket logic modular — don’t pollute main server logic.</li><li>Implement error handling and log socket events for debugging.</li></ul><h3>Final Thoughts</h3><p>Socket.IO is one of the best ways to add realtime features to your app:</p><ul><li>Realtime chat</li><li>Live notifications</li><li>Multiplayer games</li><li>Collaborative apps</li></ul><p>In our app, it powers the entire chat experience:</p><ul><li>Who is online</li><li>Who is typing</li><li>Instant message delivery</li><li>Contact requests + live notifications</li><li>Contact acceptance sync</li><li>Read receipts</li></ul><p>And it’s fast, reliable, and easy to extend.</p><p>If you haven’t tried it yet — I highly recommend exploring Socket.IO for your next realtime project.</p><h3>References</h3><ul><li><a href="https://socket.io/docs/v4/">https://socket.io/docs/v4/</a></li></ul><p>If this helped you — feel free to add a star on <a href="https://github.com/Meenakshiratnawat/pingme-chat-application">Github</a> Repository 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f779364827cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner’s Guide to Infinite Scroll in React: Scrolling Down]]></title>
            <link>https://medium.com/@meenakshiratnawat0/beginners-guide-to-infinite-scroll-in-react-scrolling-down-dce7510e1859?source=rss-4bd648b68fc2------2</link>
            <guid isPermaLink="false">https://medium.com/p/dce7510e1859</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[infinite-scroll]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Meenakshi Ratnawat]]></dc:creator>
            <pubDate>Sat, 08 Feb 2025 17:06:36 GMT</pubDate>
            <atom:updated>2025-02-08T17:06:36.153Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*GvxqxxhT0sjKy_Zydxmt7g.jpeg" /></figure><p>Infinite scrolling is a popular technique in modern web applications that loads additional content as the user scrolls down, eliminating the need for traditional pagination. In this guide, we will walk through how to implement infinite scroll in a React application, focusing on scrolling-down logic.</p><h3>Overview of the Implementation</h3><p>To achieve infinite scrolling, we need to:</p><ol><li><strong>Manage state</strong>: Track the list of items, loading status, and the current page.</li><li><strong>Handle scroll events</strong>: Detect when the user has scrolled near the bottom of the container.</li><li><strong>Fetch data from an API</strong>: Append the results to the list as the user scrolls.</li></ol><h3>Step-by-Step Breakdown</h3><h3>1. Setting Up the Component</h3><p>First, we set up our component and import the necessary dependencies:</p><pre>import React, { useState, useEffect, useRef } from &quot;react&quot;;<br>import axios from &quot;axios&quot;;<br>const InfiniteScroll = () =&gt; {<br>  const [items, setItems] = useState([]);<br>  const [page, setPage] = useState(1);<br>  const [loading, setLoading] = useState(false);<br>  const [hasMore, setHasMore] = useState(true);<br>  const containerRef = useRef(null);</pre><h3>2. Fetching Data from the API</h3><p>We create a fetchData function to load data progressively by making an API call based on the page state:</p><pre>const fetchData = async () =&gt; {<br>  if (loading || !hasMore) return;<br>  setLoading(true);<br><br>try {<br>    const response = await axios.get(<br>      `https://jsonplaceholder.typicode.com/posts?_limit=10&amp;_page=${page}`<br>    );<br>    <br>    setItems((prevItems) =&gt; [...prevItems, ...response.data]);<br>    <br>    if (response.data.length &lt; 10) {<br>      setHasMore(false);<br>    }<br>  } catch (error) {<br>    console.error(&quot;Error fetching data:&quot;, error);<br>  }<br>  setLoading(false);<br>};</pre><h3>3. Handling the Scroll Event</h3><p>To detect when the user scrolls near the bottom, we attach a scroll event listener:</p><pre>const handleScroll = () =&gt; {<br>  const container = containerRef.current;<br>  if (!container || loading || !hasMore) return;<br><br>// Extract relevant properties from the container<br>  const { scrollTop, scrollHeight, clientHeight } = container;<br>  <br>  /*<br>   * scrollTop: The vertical scroll position (how far the user has scrolled from the top).<br>   * clientHeight: The visible height of the scroll container.<br>   * scrollHeight: The total height of the content inside the container, including scrolled-out content.<br>   *<br>   * The condition below checks if the user has scrolled close to the bottom of the container.<br>   * If `scrollTop + clientHeight` (current position from top + visible height) is greater<br>   * than or equal to `scrollHeight - 5`, we trigger the next page load.<br>   */<br>  if (scrollTop + clientHeight &gt;= scrollHeight - 5) {<br>    setPage((prevPage) =&gt; prevPage + 1);<br>  }<br>};</pre><h3>4. Triggering Data Fetch on Page Change</h3><p>We use useEffect to fetch data whenever the page state changes:</p><pre>useEffect(() =&gt; {<br>  fetchData();<br>}, [page]);</pre><h3>5. Attaching the Scroll Event Listener</h3><p>We attach the handleScroll function to the container&#39;s scroll event:</p><pre>useEffect(() =&gt; {<br>  const container = containerRef.current;<br>  if (!container) return;<br>container.addEventListener(&quot;scroll&quot;, handleScroll);<br>  return () =&gt; container.removeEventListener(&quot;scroll&quot;, handleScroll);<br>}, [loading, hasMore]);</pre><h3>6. Rendering the Items and Loading State</h3><p>We render the list of items and display loading messages:</p><pre>return (<br>  &lt;div ref={containerRef} style={{ width: &quot;500px&quot;, height: &quot;600px&quot;, overflowY: &quot;auto&quot; }}&gt;<br>    &lt;h2&gt;Infinite Scroll&lt;/h2&gt;<br>    &lt;ul&gt;<br>      {items.map((item) =&gt; (<br>        &lt;li key={item.id}&gt;<br>          &lt;h4&gt;{item.title}&lt;/h4&gt;<br>          &lt;p&gt;{item.body}&lt;/p&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>    {loading &amp;&amp; &lt;p&gt;Loading more items...&lt;/p&gt;}<br>    {!hasMore &amp;&amp; &lt;p&gt;No more items to load.&lt;/p&gt;}<br>  &lt;/div&gt;<br>);</pre><h3>Key Takeaways</h3><ul><li><strong>Scroll Detection</strong>: The handleScroll function detects when the user is near the bottom and triggers a new data fetch.</li><li><strong>State Management</strong>: We track the list of items, current page, and loading status to optimize API calls.</li><li><strong>Performance Optimization</strong>: This implementation minimizes unnecessary API calls and ensures smooth data loading.</li></ul><p><strong>Source Code:</strong> <a href="https://github.com/Meenakshiratnawat/Infinite-Scroll">GitHub</a></p><p><strong>Contact Me:</strong> <a href="https://www.linkedin.com/in/meenakshi-ratnawat-aa71771b2/">LinkedIn</a></p><p>Happy coding! ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dce7510e1859" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>