<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Kalpesh Desai</title>
    <description>The latest articles on Forem by Kalpesh Desai (@kalpesh_desai_5017).</description>
    <link>https://forem.com/kalpesh_desai_5017</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2160314%2F681751e2-df04-4378-8cd7-b0ff1f42f792.png</url>
      <title>Forem: Kalpesh Desai</title>
      <link>https://forem.com/kalpesh_desai_5017</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kalpesh_desai_5017"/>
    <language>en</language>
    <item>
      <title>WebSockets : Real-Time Magic Beyond REST</title>
      <dc:creator>Kalpesh Desai</dc:creator>
      <pubDate>Mon, 14 Apr 2025 10:47:00 +0000</pubDate>
      <link>https://forem.com/kalpesh_desai_5017/websockets-real-time-magic-beyond-rest-2a7d</link>
      <guid>https://forem.com/kalpesh_desai_5017/websockets-real-time-magic-beyond-rest-2a7d</guid>
      <description>&lt;h1&gt;
  
  
  What are WebSockets?
&lt;/h1&gt;

&lt;p&gt;(We will cover everything in very short and but in detail.)&lt;/p&gt;

&lt;p&gt;WebSockets provide a persistent, full-duplex communication channel between client and server.  Once the handshake is done over HTTP, the connection upgrades to WebSocket. &lt;/p&gt;

&lt;p&gt;Why WebSockets?&lt;br&gt;
Because REST is slow for certain use cases. Think:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Real-time dashboards&lt;/li&gt;
&lt;li&gt;Chat apps&lt;/li&gt;
&lt;li&gt;Live collaboration tools (like Google Docs)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Things You Might Not Know About WebSockets
&lt;/h2&gt;

&lt;h4&gt;
  
  
  They’re Not Just for Chat
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Stock trading platforms &lt;/li&gt;
&lt;li&gt;Server log monitors &lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  WebSockets Need a Heartbeat
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Connections can silently die due to firewalls or network issues we have to send message in interval.
Eg-:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setInterval(() =&amp;gt; {
  socket.send(JSON.stringify({ type: 'ping' }));
}, 30000);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  No Built-In Auth After Handshake
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Unlike HTTP headers, you can't send custom headers once the WS connection is established. You’ll have to Include tokens in the query string during the handshake.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Socket.io Or WebSocket
&lt;/h2&gt;

&lt;p&gt;Most devs assume Socket.IO is just a wrapper for WebSockets. But it’s more like a custom protocol that can use WebSocket under the hood. Big difference.&lt;/p&gt;

&lt;h2&gt;
  
  
  Example websocket code -:
&lt;/h2&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Backend =&amp;gt;
const WebSocket = require('ws'); 
const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) =&amp;gt; {
  console.log('A new client connected'); 

  ws.on('message', (message) =&amp;gt; {
    console.log('Received: %s', message); 
  });

  ws.send('Hello from server');
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Frontend=&amp;gt;
import React, { useState, useEffect } from 'react';

const WebSocketClient = () =&amp;gt; {
  const [socket, setSocket] = useState(null);
  const [message, setMessage] = useState('');
  const [messages, setMessages] = useState([]);

  useEffect(() =&amp;gt; {
    const ws = new WebSocket('ws://localhost:8080'); // Connect to server
    setSocket(ws);

    ws.onmessage = (event) =&amp;gt; {
      setMessages((prev) =&amp;gt; [...prev, `Server: ${event.data}`]);
    };

    return () =&amp;gt; {
      ws.close();
    };
  }, []);

  const sendMessage = () =&amp;gt; {
    if (socket &amp;amp;&amp;amp; message) {
      socket.send(message); // Send message to server
      setMessages((prev) =&amp;gt; [...prev, `Client: ${message}`]);
      setMessage('');
    }
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;input value={message} onChange={(e) =&amp;gt; setMessage(e.target.value)} /&amp;gt;
      &amp;lt;button onClick={sendMessage}&amp;gt;Send&amp;lt;/button&amp;gt;
      &amp;lt;ul&amp;gt;{messages.map((msg, idx) =&amp;gt; &amp;lt;li key={idx}&amp;gt;{msg}&amp;lt;/li&amp;gt;)}&amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default WebSocketClient;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Easy code above let me know if you have any doubt or correction.&lt;/p&gt;

&lt;p&gt;Thank You and Stay real-time, devs. Just like webSocket. ⏱️&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>programming</category>
      <category>javascript</category>
      <category>node</category>
    </item>
    <item>
      <title>Decoding Next.js: When to Use use client vs. use server.</title>
      <dc:creator>Kalpesh Desai</dc:creator>
      <pubDate>Thu, 03 Oct 2024 07:26:54 +0000</pubDate>
      <link>https://forem.com/kalpesh_desai_5017/decoding-nextjs-when-to-use-use-client-vs-use-server-1jp0</link>
      <guid>https://forem.com/kalpesh_desai_5017/decoding-nextjs-when-to-use-use-client-vs-use-server-1jp0</guid>
      <description>&lt;p&gt;We all know when to use "use client" and "use server" in Next.js or we can learn and go through in short here. But how to integrate "use client" and "use server" components in each other. If you have an idea about basic "use client" and "use server" you can jump on &lt;strong&gt;chapter 3&lt;/strong&gt; below.&lt;/p&gt;

&lt;h3&gt;
  
  
  Next.js is built on top of React.js, which is primarily a client-side library
&lt;/h3&gt;

&lt;h4&gt;
  
  
  Chapter 1: "use client" &lt;a&gt;&lt;/a&gt;
&lt;/h4&gt;

&lt;h5&gt;
  
  
  What is "use client"?
&lt;/h5&gt;

&lt;p&gt;The "use client" directive in Next.js is used to indicate that a specific component should be rendered on the client side.&lt;/p&gt;

&lt;h5&gt;
  
  
  When to use "use client"?
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Client-Side Interactivity: Like buttons.&lt;/li&gt;
&lt;li&gt;State Management: Like useState.&lt;/li&gt;
&lt;li&gt;Dynamic Data Fetch :data fetching based on user interaction.&lt;/li&gt;
&lt;li&gt;Third-Party Libraries: Like gsap;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";

import { useState } from 'react';

function ClientCounter() {
  const [count, setCount] = useState(0);

  const increment = () =&amp;gt; setCount(count + 1);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Count: {count}&amp;lt;/p&amp;gt;
      &amp;lt;button onClick={increment}&amp;gt;Increment&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default ClientCounter;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Chapter 2: "use server" &lt;a&gt;&lt;/a&gt;
&lt;/h4&gt;

&lt;h5&gt;
  
  
  What is "use server"?
&lt;/h5&gt;

&lt;p&gt;The "use server" directive in Next.js is used to indicate that a specific component should be rendered on the server side. &lt;/p&gt;

&lt;h5&gt;
  
  
  When to use "use server"?
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Data Fetching on the Server: fetch data before rendering the component.&lt;/li&gt;
&lt;li&gt;Static Content: displaying static content.&lt;/li&gt;
&lt;li&gt;Server-Side Logic: execute logic that must happen before rendering.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use server";

import React from 'react';

async function fetchData() {
  return new Promise((resolve) =&amp;gt; {
    setTimeout(() =&amp;gt; {
      resolve("Hello from the server!");
    }, 1000);
  });
}

async function ServerGreeting() {
  const data = await fetchData();

  return &amp;lt;div&amp;gt;{data}&amp;lt;/div&amp;gt;;
}

export default ServerGreeting;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Chapter 3: Integration &lt;a&gt;&lt;/a&gt;
&lt;/h4&gt;

&lt;p&gt;Any other tutorial will teach that we can use "use client" component inside "use server" component. As "use client" deals with user interactions. We can use "use client" inside "use server" without rendering problems.&lt;/p&gt;

&lt;p&gt;But how can we use "use server" component in "use client" component? is it good idea?&lt;/p&gt;

&lt;p&gt;First we will see examples:&lt;/p&gt;

&lt;h6&gt;
  
  
  Server component.
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Here we created a simple server component
"use server";

async function fetchUsers() {
  const response = await fetch('https://jsonplaceholder.typicode.com/users');
  return await response.json();
}

export async function ServerUserList() {
  const users = await fetchUsers();

  return (
    &amp;lt;ul&amp;gt;
      {users.map(user =&amp;gt; (
        &amp;lt;li key={user.id}&amp;gt;{user.name}&amp;lt;/li&amp;gt;
      ))}
    &amp;lt;/ul&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Client component where we imported server component.
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"use client";
// Importing server component
import { ServerUserList } from './ServerUserList';

function UserList() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;User List&amp;lt;/h1&amp;gt;
      &amp;lt;ServerUserList /&amp;gt; {/* Server component used here */}
      &amp;lt;p&amp;gt;This is a client component that allows for additional interactivity!&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default UserList;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  App/page.tsx
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// HomePage
// Here we are importing UserList which is cliet componet.
import UserList from './components/UserList';

export default function HomePage() {
  return (
    &amp;lt;main&amp;gt;
      &amp;lt;UserList /&amp;gt;
    &amp;lt;/main&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Here we are using server component inside client component.&lt;/li&gt;
&lt;li&gt;Here server component became client component ? No.&lt;/li&gt;
&lt;li&gt;&lt;p&gt;What happend here (ServerUserList) is the server component uses the "use server" directive, fetches user data from the API, and renders it as an unordered list. This data fetching happens on the server side.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The client component (UserList) uses the "use client" directive and imports ServerUserList. This means that ServerUserList is executed on the server, and its rendered output is sent to the client.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The HomePage component uses the UserList component, integrating both server and client components.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;This code structure shows how to effectively use server components within client components in Next.js. The server component handles data fetching, while the client component can manage user interactions and additional logic.&lt;/strong&gt; &lt;/p&gt;

</description>
      <category>nextjs</category>
      <category>frontend</category>
      <category>webdev</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
