<?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 Thurunu Yasanga Marasinghe on Medium]]></title>
        <description><![CDATA[Stories by Thurunu Yasanga Marasinghe on Medium]]></description>
        <link>https://medium.com/@marasinghe.ty?source=rss-70b9dd348bd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1mwKiqDEXV5J4jMourAusA.jpeg</url>
            <title>Stories by Thurunu Yasanga Marasinghe on Medium</title>
            <link>https://medium.com/@marasinghe.ty?source=rss-70b9dd348bd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:05:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marasinghe.ty/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[Building a Multilingual React App with i18next]]></title>
            <link>https://medium.com/@marasinghe.ty/building-a-multilingual-react-app-with-i18next-0acd2416f8ec?source=rss-70b9dd348bd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0acd2416f8ec</guid>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[language-translation]]></category>
            <dc:creator><![CDATA[Thurunu Yasanga Marasinghe]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 06:00:37 GMT</pubDate>
            <atom:updated>2026-08-14T07:21:32.049Z</atom:updated>
            <content:encoded><![CDATA[<h3>A step-by-step guide to domain-based translation namespaces, Zustand state persistence, and accessible language selectors.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UQ5DMzx0ITKwOqEse-cLA.png" /></figure><p><strong>i18next</strong> is a popular, lightweight internationalization (i18n) framework for JavaScript applications designed to translate web and mobile platforms into multiple languages seamlessly. It provides a complete runtime solution for managing language resources, supporting advanced features such as variable interpolation, pluralization, context-based translations, locale fallbacks, and modular namespace loading. Through framework integrations like react-i18next, it enables front-end applications to dynamically adapt interface text, notifications, and locale formatting to users worldwide without altering core component logic.</p><p>Internationalization (i18n) is often added late in development, leading to messy translation files, state synchronization bugs, and poor accessibility. Here is a simplified guide to building a scalable, production-ready translation system using <strong>React</strong>, <strong>TypeScript</strong>, <strong>i18next</strong>, and <strong>Zustand</strong>.</p><h3>1. Directory Structure: Domain-Based Namespaces</h3><p>Avoid putting all text into one large translation.json file. Split your translation files by feature domain:</p><pre>src/<br>└── locals/<br>    ├── en/<br>    │   ├── auth.json<br>    │   └── common.json<br>    ├── ko/<br>    │   ├── auth.json<br>    │   └── common.json<br>    └── index.ts<br></pre><h4>Domain Translation File Example</h4><p>Here is how domain JSON files reflect identical key structures across locales.</p><p><strong>src/locals/en/auth.json</strong>:</p><pre>{<br>  &quot;signin&quot;: {<br>    &quot;main_Title&quot;: &quot;Welcome!&quot;,<br>    &quot;main_subtitle&quot;: &quot;Good to see you again.&quot;,<br>    &quot;title&quot;: &quot;Sign In&quot;,<br>    &quot;sub_title&quot;: &quot;Welcome back to&quot;,<br>    &quot;password&quot;: &quot;Enter password&quot;,<br>    &quot;password_placeholder&quot;: &quot;Please enter your password&quot;<br>  }<br>}</pre><p><strong>src/locals/ko/auth.json</strong>:</p><pre>{<br>  &quot;signin&quot;: {<br>    &quot;main_Title&quot;: &quot;환영합니다!&quot;,<br>    &quot;main_subtitle&quot;: &quot;다시 만나서 반갑습니다.&quot;,<br>    &quot;title&quot;: &quot;로그인&quot;,<br>    &quot;sub_title&quot;: &quot;다시 오신 것을 환영합니다&quot;,<br>    &quot;password&quot;: &quot;비밀번호 입력&quot;,<br>    &quot;password_placeholder&quot;: &quot;비밀번호를 입력해 주세요&quot;<br>  }<br>}</pre><h3>2. Centralized i18next Initialization</h3><p>The core translation configuration lives in a single entry point: src/locals/index.ts. Here, we import the domain JSON bundles, wire up react-i18next, set up locale fallbacks, and attempt to hydrate the initial language choice from localStorage.</p><p><strong>src/locals/index.ts</strong>:</p><pre>import i18n from &#39;i18next&#39;;<br>import { initReactI18next } from &#39;react-i18next&#39;;<br>import enAuth from &#39;@/locals/en/auth.json&#39;;<br>import koAuth from &#39;@/locals/ko/auth.json&#39;;<br>import enCommon from &#39;@/locals/en/common.json&#39;;<br>import koCommon from &#39;@/locals/ko/common.json&#39;;<br><br>i18n.use(initReactI18next).init({<br>  resources: {<br>    en: {<br>      common: enCommon,<br>      auth: enAuth,      <br>    },<br>    ko: {<br>      common: koCommon,<br>      auth: koAuth,<br>    },<br>  },<br>  lng: localStorage.getItem(&#39;lng&#39;) || &#39;en&#39;,<br>  fallbackLng: &#39;en&#39;,<br>  interpolation: {<br>    escapeValue: false, // React already escapes values by default<br>  },<br>});<br>export default i18n;</pre><h4>How the System Identifies &amp; Resolves Languages</h4><p>To manage translations reliably across different regions and user preferences, the application establishes a strict <strong>language identification protocol</strong> based on standard ISO 639–1 language codes, resolution priority hierarchies, and localized display name mappings.</p><p>“en” : English</p><p>“ko” : Korean</p><p>“ja” : Japanese</p><p>“zh” : Chinese</p><p>“es” : Spanish</p><p>“fr” : French</p><p>“de”: German</p><h3>3. Synchronizing State with Zustand &amp; LocalStorage</h3><p>While i18next keeps track of its internal language state, standard React applications often use global state management stores like Zustand to coordinate state updates across UI components.</p><p>To avoid state desynchronization between i18next, local storage, and React UI components, we create a dedicated Zustand slice and integrate the slice into our main store composition.</p><p><strong>src/store/languageSlice.ts</strong>:</p><pre>import { StateCreator } from &#39;zustand&#39;;<br>import i18n from &#39;i18next&#39;;<br><br>export interface LanguageState {<br>  language: string;<br>  changeLanguage: (lng: string) =&gt; void;<br>}<br><br>export const createLanguageSlice: StateCreator&lt;LanguageState, [], [], LanguageState&gt; = (set) =&gt; ({<br>  language: localStorage.getItem(&#39;lng&#39;) || i18n.language || &#39;en&#39;,<br>  changeLanguage: (lng) =&gt; {<br><br>    // 1. Update i18next runtime instance<br>    i18n.changeLanguage(lng);<br><br>    // 2. Persist to browser storage for session continuity<br>    localStorage.setItem(&#39;lng&#39;, lng);<br><br>    // 3. Trigger Zustand state update to re-render subscribed React components<br>    set({ language: lng });<br>  },<br>});</pre><p>When a user selects a new language, calling changeLanguage(&#39;ko&#39;) executes three distinct operations in a single atomic action:</p><ol><li>i18n.changeLanguage(&#39;ko&#39;) changes the active translation dictionary inside i18next.</li><li>localStorage.setItem(&#39;lng&#39;, &#39;ko&#39;) saves the setting for future browser reloads.</li><li>set({ language: &#39;ko&#39; }) notifies all React components listening to useStore to re-render smoothly.</li></ol><p>The <strong>language change dropdown</strong></p><p>This serves as the central UI control for switching the application’s active locale (e.g., between English and Korean). When a user selects a language, the dropdown dispatches a single Zustand action that simultaneously updates the i18next runtime engine, persists the new language code in browser localStorage for future sessions, and updates the global store state. Because UI components and custom hooks throughout the app consume localized text using react-i18next hooks, this single state update triggers an instant, reactive re-render across every pages, tables, form fields, and toast notifications in the entire application, translating the entire interface seamlessly without requiring a full page reload.</p><h3>4. Consuming Translations in React Components</h3><p>Once the foundation is laid, consuming translations throughout the codebase is clean and expressive. Changing the language does not require the page to be reloaded. Instead, the language change flows through i18next and react-i18next, which then causes the relevant React components to render again.</p><ul><li>When you select a new language, the toggler calls i18n.changeLanguage(&#39;ko&#39;). i18next updates its internal active language setting and immediately emits a global event named <strong>languageChanged</strong>.</li><li>When the languageChanged event fires, react-i18next notifies React that the translation state has changed.</li><li>React flags all subscribed components and triggers a <strong>re-render</strong>.</li><li>As each component re-renders, t(&#39;key&#39;) is executed again, returning the string for the new language.</li><li>React compares the new Virtual DOM tree (containing Korean text) against the previous Virtual DOM tree (containing English text).</li><li>It identifies the exact text nodes that changed (e.g., changing &quot;Sign In&quot; to &quot;로그인&quot;).</li><li>React updates <strong>only those specific text nodes</strong> in the real browser DOM.</li></ul><h4>A. Scoped Namespace Usage inside Components</h4><p>When rendering a specific page, pass the namespace string to useTranslation().</p><pre>import { useTranslation } from &#39;react-i18next&#39;;<br>import TextField from &#39;@/components/Input/Textfield&#39;;<br><br>const Signin = () =&gt; {<br>  // Pass default namespace for this page<br>  const { t } = useTranslation(&#39;auth&#39;);<br><br>  return (<br>    &lt;div className=&quot;p-8 bg-white rounded-lg&quot;&gt;<br>      &lt;h2&gt;{t(&#39;signin.title&#39;)}&lt;/h2&gt;<br>      &lt;p&gt;{t(&#39;signin.sub_title&#39;)}&lt;/p&gt;<br><br>      {/* Access explicit cross-namespace keys using &#39;namespace:key&#39; syntax */}<br>      &lt;TextField<br>        labelKey=&quot;common:common.email&quot;<br>        placeholderKey=&quot;common:common.email_placeholder&quot;<br>        name=&quot;email&quot;<br>      /&gt;<br>      &lt;TextField<br>        labelKey=&quot;auth:signin.password&quot;<br>        placeholderKey=&quot;auth:signin.password_placeholder&quot;<br>        name=&quot;password&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>B. Dynamic Toast Notifications in React Query Hooks</h4><p>Translation hooks can also be used inside custom asynchronous mutation hooks to provide localized user feedback. By calling useTranslation() directly inside custom React Query / TanStack Query mutation hooks, lifecycle callbacks like onSuccess and onError can dynamically fetch translation strings (t(&#39;profile.update_success&#39;), t(&#39;profile.update_error&#39;)). When the active language changes, future notifications automatically render in the updated language.</p><pre>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br>import { useTranslation } from &#39;react-i18next&#39;;<br>import { toast } from &#39;sonner&#39;;<br><br>interface UserProfileData {<br>  name: string;<br>  email: string;<br>}<br><br>// 1. Standard API function<br>const updateUserProfileApi = async (data: UserProfileData) =&gt; {<br>  const response = await fetch(&#39;/api/user/profile&#39;, {<br>    method: &#39;PUT&#39;,<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>    body: JSON.stringify(data),<br>  });<br><br>  if (!response.ok) throw new Error(&#39;Failed to update profile&#39;);<br>  return response.json();<br>};<br><br>// 2. Custom Mutation Hook<br>export const useUpdateProfile = () =&gt; {<br>  const { t } = useTranslation(&#39;profile&#39;);<br>  const queryClient = useQueryClient();<br><br>  return useMutation({<br>    mutationFn: updateUserProfileApi,<br><br>    // Localized success notification<br>    onSuccess: () =&gt; {<br>      toast.success(t(&#39;profile.update_success&#39;)); <br>      <br>      // English: &quot;Profile updated successfully!&quot;<br>      // Korean:  &quot;프로필이 성공적으로 수정되었습니다.&quot;<br><br>      queryClient.invalidateQueries({ queryKey: [&#39;userProfile&#39;] });<br>    },<br><br>    // Localized error notification<br>    onError: (error) =&gt; {<br>      toast.error(t(&#39;profile.update_error&#39;));<br> <br>      // English: &quot;Failed to update profile. Please try again.&quot;<br>      // Korean:  &quot;프로필 수정에 실패했습니다. 다시 시도해 주세요.&quot;<br>    },<br>  });<br>};</pre><p>i18next also allows dynamic runtime data (such as item names, user names, or counts) to be passed directly into translation strings:</p><pre>// Translation key : &quot;deleted_item&quot;: &quot;Successfully deleted {{name}}&quot;<br><br>toast.success(t(&#39;deleted_item&#39;, { name: item.title }));</pre><ul><li><strong>English output</strong>: &quot;Successfully deleted Project Alpha&quot;</li><li><strong>Korean output</strong>: &quot;Project Alpha이(가) 성공적으로 삭제되었습니다.&quot;</li></ul><h3>Summary &amp; Key Takeaways</h3><p>By pairing <strong>i18next</strong> with <strong>Zustand</strong>, you get the best of both worlds:</p><ul><li><strong>Scalable Architecture</strong>: Domain-based namespace organization prevents bloated configuration files and speeds up development.</li><li><strong>Synchronized State</strong>: A unified Zustand action ensures i18next, local storage, and component states stay perfectly in sync.</li><li><strong>Clean Developer Experience</strong>: Expressive namespaces and explicit namespace:key lookups keep component code legible and maintainable.</li></ul><p><em>Thank you for reading! How do you handle multi-language translations and global state synchronization in your React projects? Share your thoughts and approaches in the comments below!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0acd2416f8ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetching Data Without the useEffect Boilerplate: A Guide to TanStack Query]]></title>
            <link>https://medium.com/@marasinghe.ty/fetching-data-without-the-useeffect-boilerplate-a-guide-to-tanstack-query-5578cd4d648a?source=rss-70b9dd348bd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5578cd4d648a</guid>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[react-hook-useeffect]]></category>
            <category><![CDATA[tanstack]]></category>
            <dc:creator><![CDATA[Thurunu Yasanga Marasinghe]]></dc:creator>
            <pubDate>Wed, 20 May 2026 11:36:21 GMT</pubDate>
            <atom:updated>2026-05-20T11:36:21.520Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve spent any time building modern web applications, you know the routine. You create a component, open a useEffect hook, spin up three separate useState hooks for your data, loading, and error states, and try to make sure you don&#39;t accidentally cause an infinite re-render loop.</p><p>It looks a little something like this:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>function ProductList() {<br>  const [data, setData] = useState([]);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    let isMounted = true;<br>    <br>    fetch(&#39;/api/products&#39;)<br>      .then((res) =&gt; {<br>        if (!res.ok) throw new Error(&#39;Failed to fetch&#39;);<br>        return res.json();<br>      })<br>      .then((data) =&gt; {<br>        if (isMounted) {<br>          setData(data);<br>          setLoading(false);<br>        }<br>      })<br>      .catch((err) =&gt; {<br>        if (isMounted) {<br>          setError(err.message);<br>          setLoading(false);<br>        }<br>      });<br><br>    return () =&gt; { isMounted = false; }; // Cleaning up race conditions<br>  }, []);<br><br>  if (loading) return &lt;div&gt;Loading products...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error}&lt;/div&gt;;<br><br>  return &lt;ul&gt;{data.map(p =&gt; &lt;li key={p.id}&gt;{p.title}&lt;/li&gt;)}&lt;/ul&gt;;<br>}</pre><p>While this works, it’s a lot of plumbing just to display a list of items. Worse, it’s fragile. It doesn’t handle data caching, it doesn’t retry if the network hiccups, and if the user switches tabs and comes back, they’re looking at stale data unless they manually refresh.</p><p>The core issue is that we are using <strong>client-state</strong> tools (useState) to manage <strong>server-state</strong> data.</p><p>Enter <strong>TanStack Query</strong> (formerly React Query). It isn’t a data fetching library like Axios or Fetch, it is an asynchronous server-state manager that deletes this boilerplate from your codebase. Let’s break down the fundamentals you need to know to transition to cleaner data management.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOHMc6HMa4H2mq7ZcZC4xw.png" /></figure><h3>1. The Engine Room: QueryClient and Provider</h3><p>Before you can fetch anything, you need to create a centralized place where your application stores its cached server data. Think of the QueryClient as an in memory database that lives entirely within your user’s browser tab.</p><p>You initialize it once at the root of your application and wrap your tree in a provider:</p><pre>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;;<br>import ProductList from &#39;./ProductList&#39;;<br><br>const queryClient = new QueryClient();<br><br>export default function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;ProductList /&gt;<br>      {/* Visual tool to inspect your cache in development */}<br>      &lt;ReactQueryDevtools initialIsOpen={false} /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><p>Always include the ReactQueryDevtools when setting up a project. It gives you a visual dashboard directly in the browser to see exactly what data is cached, what is fresh, and what is stale.</p><h3>2. Reading Data Seamlessly with useQuery</h3><p>Now that the infrastructure is set up, let’s look at how much simpler our ProductList component becomes when we swap the boilerplate out for TanStack Query&#39;s useQuery hook.</p><p>The hook requires a single configuration object with two primary attributes:</p><ol><li><strong>queryKey</strong>: An array that uniquely identifies this specific query. It acts as the cache key.</li><li><strong>queryFn</strong>: A function that returns a promise. This function must either successfully resolve your data or throw an error.</li></ol><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br><br>interface Product {<br>  id: number;<br>  title: string;<br>}<br><br>function ProductList() {<br>  const { data, isPending, isError, error } = useQuery&lt;Product[]&gt;({<br>    queryKey: [&#39;products&#39;],<br>    queryFn: async () =&gt; {<br>      const res = await fetch(&#39;/api/products&#39;);<br>      if (!res.ok) {<br>        // Crucial: Standard fetch doesn&#39;t throw on 404/500 errors, <br>        // but TanStack Query needs an explicit error thrown to register it.<br>        throw new Error(&#39;Network response was not ok&#39;);<br>      }<br>      return res.json();<br>    },<br>  });<br><br>  if (isPending) return &lt;div&gt;Loading products...&lt;/div&gt;;<br>  if (isError) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map((product) =&gt; (<br>        &lt;li key={product.id}&gt;{product.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>Look at that transition. The state orchestration disappears. TanStack Query automatically manages the state lifecycle and gives you clean, explicit boolean flags (isPending, isError) out of the box.</p><h3>3. The Lifecycle: “Stale” vs. “Fetching”</h3><p>One behavior that trips up developers new to TanStack Query is its background updating model.</p><p>By default, TanStack Query sets its staleTime to 0. This means that as soon as data is fetched, it is immediately considered &quot;stale&quot; (old). However, <em>stale does not mean empty</em>.</p><p>If a user navigates away from this component and comes back, TanStack Query immediately serves the cached data from the [&#39;products&#39;] key so the user isn&#39;t stuck staring at a blank loading screen. Simultaneously, in the background, it triggers a silent fetch (isFetching) to get the latest data. If the server data has changed, it smoothly swaps it out on screen.</p><p>It also triggers these background updates when:</p><ul><li>The user refocuses their browser window (refetchOnWindowFocus).</li><li>The network disconnects and reconnects (refetchOnReconnect).</li></ul><h3>4. Modifying Data with useMutation</h3><p>When you need to alter data on the server via POST, PUT, or DELETE requests, you switch gears from useQuery to useMutation.</p><p>Unlike queries, mutations don’t run automatically when a component mounts. Instead, they expose a mutate method that you invoke manually, usually during a form submission or button click.</p><pre>import { useMutation } from &#39;@tanstack/react-query&#39;;<br><br>function AddProductForm() {<br>  const { mutate, isPending } = useMutation({<br>    mutationFn: async (newProduct: { title: string }) =&gt; {<br>      const res = await fetch(&#39;/api/products&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify(newProduct),<br>      });<br>      return res.json();<br>    },<br>  });<br><br>  const handleSubmit = () =&gt; {<br>    mutate({ title: &#39;New Wireless Mouse&#39; });<br>  };<br><br>  return (<br>    &lt;button onClick={handleSubmit} disabled={isPending}&gt;<br>      {isPending ? &#39;Adding...&#39; : &#39;Add Product&#39;}<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>5. Connecting the Dots: Query Invalidation</h3><p>If you run the mutation example above, you will hit a logical problem: you click “Add Product”, the data is successfully sent to your server, but your ProductList component on screen doesn’t update. Why? Because the ProductList is still happily reading its cached data under the [&#39;products&#39;] key.</p><p>We need to tell TanStack Query that our cache is invalid. We do this by pulling the useQueryClient hook into our mutation and using its onSuccess callback:</p><pre>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br>function AddProductForm() {<br>  const queryClient = useQueryClient();<br><br>  const { mutate } = useMutation({<br>    mutationFn: createProductOnServer,<br>    onSuccess: () =&gt; {<br>      // Intelligently target the exact cache key to mark it out-of-date<br>      queryClient.invalidateQueries({ queryKey: [&#39;products&#39;] });<br>    },<br>  });<br>  <br>  // ... rest of form implementation<br>}</pre><p>The second invalidateQueries is called, TanStack Query marks [&#39;products&#39;] as stale and triggers an immediate background refetch for any active components listening to that key. Your list updates instantly, without complex global state syncs or forcing a full page reload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvO3pp2DvmFO9asJoNKl4w.png" /></figure><h3>Summary</h3><blockquote>At its most fundamental level, TanStack Query splits server interactions into two distinct paradigms based on HTTP methods and intent:</blockquote><h4><strong>useQuery</strong></h4><blockquote><strong>for </strong><strong>GET requests</strong> (Reading data). It is declarative, meaning it runs automatically when a component mounts to fetch and cache data.</blockquote><h4><strong>useMutation</strong></h4><blockquote><strong>for </strong><strong>POST, </strong><strong>PUT, </strong><strong>PATCH, and </strong><strong>DELETE requests</strong> (Modifying data). It is imperative, meaning it gives you a trigger function (mutate) to execute on-demand (e.g., when clicking a button or submitting a form).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5luomYqgbo676fkGVctUmw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5578cd4d648a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Web : Part 3| Building a basic Chat Application]]></title>
            <link>https://medium.com/@marasinghe.ty/real-time-web-part-3-building-a-basic-chat-application-f38ed85ea2b6?source=rss-70b9dd348bd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f38ed85ea2b6</guid>
            <category><![CDATA[chat-app-development]]></category>
            <dc:creator><![CDATA[Thurunu Yasanga Marasinghe]]></dc:creator>
            <pubDate>Fri, 15 May 2026 10:11:59 GMT</pubDate>
            <atom:updated>2026-05-15T10:11:59.883Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read <a href="https://medium.com/@marasinghe.ty/real-time-web-an-absolute-beginners-guide-to-socket-io-a7b72df23b09">Part 1</a> and <a href="https://medium.com/@marasinghe.ty/real-time-web-part-2-understanding-socket-io-core-concepts-4e943ffd997d">Part 2</a>, go do that first — it covers the theory behind WebSockets and Socket.io that we’ll be putting into practice here.</p><p>To truly understand how our chat app works, let’s stop looking at lines of code for a moment and look at the journey of a single message. Imagine <strong>Alice</strong> wants to send a simple ‘How are you?’ to <strong>Bob</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxuA9bHja88fEwo0vLba6g.png" /></figure><p>There are two channels of communication running in parallel:</p><ol><li><strong>HTTP (REST API):</strong> For auth, fetching message history, and sending messages (which also triggers the socket notification).</li><li><strong>WebSocket (Socket.io):</strong> For real-time events — who’s online, and incoming new messages.</li></ol><p>Notice that HTTP carries the message into the system reliably — it gives Alice a confirmation. Socket.IO carries it <em>out</em> to Bob in real time. Both are necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KcgFd-4rSXsblXmLOznegw.png" /></figure><h3>Step 1: The socket server</h3><p>The socket layer lives in lib/socket.js. It creates the HTTP server <em>manually</em>, rather than letting Express do it internally:</p><pre>const app = express();<br>const server = http.createServer(app);<br>const io = new Server(server, { cors: { origin: [&quot;http://localhost:5173&quot;] } });</pre><p>Why<strong> </strong>http.createServer(app)<strong> </strong>and not just app<strong>?</strong> Socket.io needs to attach itself to a raw Node.js HTTP server, not the Express app object. Express itself <em>uses</em> an HTTP server internally, but it doesn&#39;t expose it. By creating the server ourselves with http.createServer(app), we get access to the underlying server that both Express and Socket.io can share.</p><p>Tracking Online Users</p><p>One of the most important features of any chat app is knowing who’s online. We have used a simple JavaScript object as an in-memory map:</p><pre>const userSocketMap = {};<br>// Structure: { &quot;userId123&quot;: &quot;socketId_abc&quot;, &quot;userId456&quot;: &quot;socketId_xyz&quot; }<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>});</pre><p>Every connected user gets a <strong>socket ID</strong> — a unique string Socket.io generates automatically. We map each user’s MongoDB _id to their current socket ID so we can find and message them later.</p><h3>Step 2: The message controller</h3><p>When Alice hits send, the request lands in sendMessage. Here&#39;s the most important part of that controller . After saving to the database, it decides whether to push in real time:</p><pre>await newMessage.save();<br><br>res.status(200).json(newMessage); // ← Alice&#39;s UI updates here<br><br>const receiverSocketId = getReceiverSocketId(receiverId);<br><br>if (receiverSocketId) {<br>  io.to(receiverSocketId).emit(&quot;newMessage&quot;, newMessage);<br>}</pre><p>The HTTP response goes to Alice <em>first</em> — she gets instant feedback regardless of Bob’s status. Then, if Bob happens to be online, the server pushes the message to his socket. The HTTP path and the socket path are completely independent.</p><p><em>Notice that </em><em>io.to(socketId) is used here, not </em><em>io.emit().</em></p><p><em>io.emit() broadcasts to every connected user. </em><em>io.to(socketId).emit() sends to exactly one client. This is how private messaging works.</em></p><h3>Step 3: Connecting the frontend socket</h3><p>The frontend uses <strong>Zustand, a </strong>lightweight state management library</p><pre>connectSocket: () =&gt; {<br>  const { authUser } = get();<br>  if (!authUser || get().socket?.connected) return;<br><br>  const socket = io(BASE_URL, {<br>    query: { userId: authUser._id },<br>  });<br><br>  socket.connect();<br>  set({ socket });<br><br>  socket.on(&quot;getOnlineUsers&quot;, (userIds) =&gt; {<br>    set({ onlineUsers: userIds });<br>  });<br>},</pre><p>On the frontend, socket connection is managed by useAuthStore — the same store that handles login, logout, and authentication state. The connectSocket function runs automatically whenever a user successfully logs in or their session is verified. The socket instance is saved into Zustand state, making it accessible to any other store in the app</p><h3>Step 4: Subscribing to real-time messages</h3><p>In useChatStore, two functions handle the real-time subscription lifecycle:</p><pre>subscribeToMessages: () =&gt; {<br>  const { selectedUser } = get();<br>  if (!selectedUser) return;<br><br>  const socket = useAuthStore.getState().socket;<br><br>  socket.on(&quot;newMessage&quot;, (newMessage) =&gt; {<br>    const isFromSelectedUser = newMessage.senderId === selectedUser._id;<br>    if (!isFromSelectedUser) return;<br><br>    set({ messages: [...get().messages, newMessage] });<br>  });<br>},<br><br>unsubscribeFromMessages: () =&gt; {<br>  const socket = useAuthStore.getState().socket;<br>  socket.off(&quot;newMessage&quot;);<br>}</pre><h3>Step 5: The chat UI component</h3><pre>useEffect(() =&gt; {<br>  getMessages(selectedUser?._id);<br>  subscribeToMessages();<br>}, [selectedUser._id]);</pre><p>The ChatContainer component wires it all together. It fires two useEffect hooks on mount, The first call fetches the full message history from the database via HTTP — because even if you’ve been receiving real-time events, you need the history from before you opened the chat. The second call attaches the socket listener. From that point forward, new messages arrive via the socket and are appended in real time to the already-loaded history.</p><p>Now, it’s your turn to break this code, improve it, and make it your own. Check out the full repository on <strong>GitHub.</strong></p><p>Source code : <a href="https://github.com/thurunuym/ChatWhiz">GitHub — thurunuym/ChatWhiz</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f38ed85ea2b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Web : Part 2 | Understanding Socket.IO Core Concepts]]></title>
            <link>https://medium.com/@marasinghe.ty/real-time-web-part-2-understanding-socket-io-core-concepts-4e943ffd997d?source=rss-70b9dd348bd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e943ffd997d</guid>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[websocket-server]]></category>
            <dc:creator><![CDATA[Thurunu Yasanga Marasinghe]]></dc:creator>
            <pubDate>Sun, 10 May 2026 13:41:35 GMT</pubDate>
            <atom:updated>2026-05-10T18:54:21.393Z</atom:updated>
            <content:encoded><![CDATA[<h3>Real-Time Web : Part 2| Understanding Socket.IO Core Concepts</h3><p>In our <a href="https://medium.com/@marasinghe.ty/real-time-web-an-absolute-beginners-guide-to-socket-io-a7b72df23b09">last deep dive</a>, we looked at how Socket.io enables two-way communication. Now let’s get into the building blocks of Socket.io. There are three key concepts every beginner needs to understand: <strong>Events</strong>, <strong>Namespaces</strong>, and <strong>Rooms</strong>.</p><h3>1. Events: emit and on</h3><p>Socket.io is built around the concept of <strong>events</strong> — named signals that either the client or server can send and listen for.</p><ul><li><strong>emit</strong> — Send an event (with optional data) to the other side.</li><li><strong>on</strong> — Listen for a specific event and react when it arrives.</li></ul><p>This is identical in spirit to DOM event listeners in the browser (addEventListener), just over a network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5-k_cIX2J7zY9yPSS2EZAw.png" /></figure><p>See how clean that is? You name your events meaningfully (&#39;chat message&#39;, &#39;welcome&#39;), and both sides agree on those names. It reads almost like plain English.</p><h3>2. Namespaces: Separate Communication Channels</h3><p>Imagine you’re building a platform that has a <strong>chat section</strong> and a <strong>live dashboard</strong> section. You probably don’t want chat events mixing with dashboard events — that would be messy.</p><p><strong>Namespaces</strong> let you split a single Socket.io connection into multiple isolated channels, each with their own event handlers.</p><pre>// Server: define separate namespaces<br>const chatNamespace      = io.of(&#39;/chat&#39;);<br>const dashboardNamespace = io.of(&#39;/dashboard&#39;);<br><br>chatNamespace.on(&#39;connection&#39;, (socket) =&gt; {<br>  // Only chat-related events here<br>});<br><br>dashboardNamespace.on(&#39;connection&#39;, (socket) =&gt; {<br>  // Only dashboard-related events here<br>});</pre><pre>// Client: connect to a specific namespace<br>const chatSocket      = io(&#39;/chat&#39;);<br>const dashboardSocket = io(&#39;/dashboard&#39;);</pre><p>Think of namespaces like different departments in a company, each with their own internal communication, all running over the same office building (your server).</p><h3>3. Rooms: Temporary Groups Within a Namespace</h3><p>Within a namespace, you can organize sockets into <strong>Rooms</strong> — dynamic, temporary groups.</p><p>A real-world example: imagine a multiplayer game where you match players into separate game lobbies. Or a chat app where users can join different topic channels. Rooms are perfect for this.</p><pre>// Server: a user joins a room<br>socket.on(&#39;join room&#39;, (roomName) =&gt; {<br>  socket.join(roomName);<br>  console.log(`User joined room: ${roomName}`);<br>});<br><br>// Server: send a message to ONLY users in a specific room<br>io.to(&#39;game-lobby-42&#39;).emit(&#39;game update&#39;, { score: 5 });<br></pre><p>The beauty: users in &#39;game-lobby-42&#39; get the update. Everyone else? Unaffected.</p><p>Here’s a visual summary of how these three concepts nest together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQP4qWh457DpLgJu5Eh7LA.png" /></figure><p>In the next chapter, we’ll build a basic real-world project and walk through the codebase together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e943ffd997d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-Time Web : Part 1 | An Absolute Beginner’s Guide to Socket.IO]]></title>
            <link>https://medium.com/@marasinghe.ty/real-time-web-an-absolute-beginners-guide-to-socket-io-a7b72df23b09?source=rss-70b9dd348bd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7b72df23b09</guid>
            <category><![CDATA[websocket-vs-socketio]]></category>
            <category><![CDATA[socket-io-client]]></category>
            <category><![CDATA[socketio]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[http-vs-websocket]]></category>
            <dc:creator><![CDATA[Thurunu Yasanga Marasinghe]]></dc:creator>
            <pubDate>Sun, 10 May 2026 08:44:19 GMT</pubDate>
            <atom:updated>2026-05-10T09:09:59.495Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re using a group chat app. You type a message, hit send, and then you have to <em>refresh the page</em> to see if anyone replied.</p><p>Sounds absurd, right? Yet that was the reality of the early web. Today, messages appear instantly, dashboards update live, and multiplayer games run smoothly in the browser. The technology powering much of this real-time magic? <strong>Socket.io.</strong></p><p>In this article, we’ll walk through why real-time communication on the web is hard and how WebSockets solve it.</p><h3>HTTP Was Never Built for This</h3><p>The foundation of the web is <strong>HTTP</strong> (HyperText Transfer Protocol). Every time you load a webpage, your browser sends an HTTP <em>request</em> to a server, the server processes it, and sends back a <em>response</em>. Done. Connection closed. This is called the <strong>request-response cycle</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o4ibK2A0oBZ9qoiEV9dyNQ.png" /></figure><p>This works beautifully for loading static pages or submitting forms. But what if you need the <em>server</em> to push new information to you <em>without you asking</em>? Like a new chat message, or a live stock price update?</p><p>HTTP has no native way to do this. So developers got creative and a bit hacky.</p><h3>The Polling Workaround (and Why It Hurts)</h3><p>One classic workaround is <strong>polling</strong>: the client repeatedly asks the server “anything new?” on a timer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jcu1lDhzHSgNl5GISSSloQ.png" /></figure><p>This works, but it’s deeply inefficient:</p><ul><li><strong>Wasted requests:</strong> 99% of the time, the server says “nothing new.”</li><li><strong>Latency:</strong> There’s always a delay. If your poll interval is 2 seconds, a message can arrive up to 2 seconds late.</li><li><strong>Server load:</strong> Imagine 10,000 users all hammering your server every 2 seconds. That’s 5,000 requests per second just to say “nope.”</li></ul><p>A fancier variant, <strong>long-polling</strong>, has the server <em>hold</em> the connection open until new data arrives, then immediately respond. It’s better, but still involves repeatedly re-establishing connections. It’s like calling a friend, putting them on hold until they have news, then hanging up and calling again.</p><h3>The Solution: WebSockets + Socket.io</h3><h4>What Are WebSockets?</h4><p><strong>WebSockets</strong> are a communication protocol that upgrades an HTTP connection into a persistent, full duplex (two way) channel between the client and the server.</p><p>Think of it like the difference between sending letters (HTTP) and having a phone call (WebSocket):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fetYakoSiM1KzoJq6rxWig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kLp87169b4O0ij8FJTRgMg.png" /></figure><h3>So What Is Socket.io, Exactly?</h3><p>WebSockets are powerful, but raw WebSockets have rough edges:</p><ul><li>What happens if the connection drops? You have to manually reconnect.</li><li>Some older browsers or corporate firewalls don’t support WebSockets.</li><li>There’s no built-in way to send messages to <em>groups</em> of users.</li></ul><p><strong>Socket.io</strong> is a JavaScript library (available for both Node.js servers and browser clients) that wraps WebSockets and smooths out all these rough edges. Think of it as WebSockets with a safety net and a supercharger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*osbb9MN8IMyoo6J-m-Sd5g.png" /></figure><p>The fallback mechanism deserves a special mention. If a user’s browser or network doesn’t support WebSockets, Socket.io <em>automatically</em> falls back to long-polling, so your app still works just slightly less efficiently. This is huge for reliability in the real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvVxIOtvx1HLs-TOb2j8Qw.png" /></figure><p>In the next article, we’ll explore how Socket.IO works in a real-world application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7b72df23b09" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>