<?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 ash on Medium]]></title>
        <description><![CDATA[Stories by ash on Medium]]></description>
        <link>https://medium.com/@skyshots?source=rss-41bbacaeeb75------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ioLbiDK_2pOulRQoU7C38w.jpeg</url>
            <title>Stories by ash on Medium</title>
            <link>https://medium.com/@skyshots?source=rss-41bbacaeeb75------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 04:44:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@skyshots/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[Why Borrow Components When You Can Own Them: Meet shadcn/ui (2026 Edition)]]></title>
            <link>https://medium.com/@skyshots/why-borrow-components-when-you-can-own-them-meet-shadcn-ui-2026-edition-32c60042e716?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/32c60042e716</guid>
            <category><![CDATA[ui-library]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[shadcn]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 17:32:37 GMT</pubDate>
            <atom:updated>2025-10-17T17:32:37.566Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Tired of endlessly tweaking buttons, patching CSS overrides, and navigating bloated UI libraries that slow you down more than they help? Its time for something cleaner.</em></p><p>If you’ve ever wished for a UI library that looks great, works out of the box, and still lets you own your code, you’re about to love this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVWKhhvJ3ygYYsVaYelWew.png" /></figure><blockquote>Welcome to shadcn/ui the frontend game-changer.</blockquote><h3>💠 What Is shadcn/ui?</h3><p>shadcn/ui isn’t your typical component library.<br>It’s a collection of <strong><em>React components</em></strong> built on <a href="https://tailwindcss.com/"><strong><em>Tailwind CSS</em></strong></a> and <a href="https://www.radix-ui.com/"><strong><em>Radix Primitives</em></strong></a><em>,</em> designed for developers who want flexibility and polish.</p><p>Instead of installing a package, you copy the actual component code into your project.</p><p>That means:</p><ul><li>Full control</li><li>No overrides</li><li>No vendor lock</li></ul><blockquote>“It’s not a black box, it’s your box.”</blockquote><h3>💠 The Stack Behind It</h3><p>Every part of shadcn/ui is crafted for <strong>accessibility</strong>, <strong>speed</strong>, and <strong>control</strong>.</p><ol><li><strong>Tailwind CSS</strong>: utility-first styling for rapid design.</li><li><strong>Radix Primitives: </strong>robust accessibility and behavior logic.</li><li><strong>shadcn Layer:</strong> polished React components combining both.</li></ol><p>Together, they create a design system that’s consistent, composable, and production-ready.</p><h3>💠 Why Developers Love It</h3><ul><li><strong><em>Copy–Paste Ownership</em></strong>: You literally own the code.</li><li><strong><em>Tailwind-Powered</em></strong>: Easy to theme, responsive by default.</li><li><strong><em>Radix Accessibility</em></strong>: Keyboard navigation &amp; ARIA baked in.</li><li><strong><em>Modular</em></strong>: Add only what you need.</li><li><strong><em>Editable</em></strong>: Override logic, structure, or styles.</li><li><strong><em>Scalable</em></strong>: Perfect for dashboards, forms, and modals.</li></ul><blockquote>Pro Tip: Think of it as your personal design system that just <em>happens</em> to ship with enterprise-grade accessibility.</blockquote><h3>💠 Getting Started (Quick Setup)</h3><h4>1️⃣ Create a Next.js + Tailwind Project</h4><pre>npx create-next-app@latest my-app<br>cd my-app<br>npm install tailwindcss<br>npx tailwindcss init -p</pre><h4>2️⃣ Initialize shadcn/ui</h4><pre>npx shadcn@latest init</pre><p>This creates your /components/ui folder where all your magic lives.</p><h4>3️⃣ Add Components</h4><pre>npx shadcn add button<br>npx shadcn add input<br>npx shadcn add dialog</pre><h4>4️⃣ Use Them</h4><pre>import { Button } from &quot;@/components/ui/button&quot;;<br><br>export default function Home() {<br>  return &lt;Button&gt;Launch&lt;/Button&gt;;<br>}</pre><blockquote><em>And just like that, your UI is both beautiful and accessible.</em></blockquote><h3>💠 Owning &amp; Customizing Components</h3><blockquote>Here’s the part that sets shadcn/ui apart: you can change literally anything.</blockquote><p>Your components live in your repo, so tweak away without worrying about upgrades or overrides.</p><pre>// components/ui/button.tsx<br>export function Button({ children, className, ...props }) {<br>  return (<br>    &lt;button<br>      className={`bg-indigo-600 text-white px-4 py-2 rounded-md hover:bg-indigo-700 transition ${className}`}<br>      {...props}<br>    &gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><blockquote>Want a gradient? Change it.<br>Want a new variant? Add it.<br>Want animation? Plug it in.</blockquote><blockquote>Common Pitfall: Don’t forget to keep your component patterns consistent, customization is freedom but consistency is scalability.</blockquote><h3>💠 Extending Components</h3><p>Clean, readable, and developer-friendly: here’s how a dialog looks in shadcn/ui.</p><pre>&lt;Dialog&gt;<br>  &lt;DialogTrigger&gt;<br>    &lt;Button&gt;Open Dialog&lt;/Button&gt;<br>  &lt;/DialogTrigger&gt;<br>  &lt;DialogContent className=&quot;p-6 rounded-xl shadow-xl&quot;&gt;<br>    &lt;h2 className=&quot;text-xl font-semibold mb-2&quot;&gt;Heads up!&lt;/h2&gt;<br>    &lt;p&gt;Your session is about to expire. Click below to stay logged in.&lt;/p&gt;<br>    &lt;div className=&quot;mt-4 flex gap-2&quot;&gt;<br>      &lt;Button&gt;Stay Logged In&lt;/Button&gt;<br>      &lt;Button variant=&quot;outline&quot;&gt;Log Out&lt;/Button&gt;<br>    &lt;/div&gt;<br>  &lt;/DialogContent&gt;<br>&lt;/Dialog&gt;</pre><p><strong>Everything</strong>, from the layout to transitions is <strong>editable </strong>and <strong>themeable</strong>.</p><h3>💠 Real-World Use Cases</h3><h4>🔸 Dashboards</h4><p>Quickly build panels, actions, and data displays.</p><pre>&lt;Button variant=&quot;outline&quot;&gt;Filter&lt;/Button&gt;<br>&lt;Card&gt;Revenue: $23,000&lt;/Card&gt;</pre><h4>🔸 Forms</h4><p>Combine Input, Label, and Button for fluid UX.</p><pre>&lt;Label&gt;Email&lt;/Label&gt;<br>&lt;Input placeholder=&quot;you@example.com&quot; /&gt;<br>&lt;Button&gt;Submit&lt;/Button&gt;</pre><h4>🔸 Modals &amp; Dialogs</h4><p>Simple, elegant, and ARIA-compliant.</p><pre>&lt;Dialog&gt;<br>  &lt;DialogTrigger&gt;&lt;Button&gt;Show Details&lt;/Button&gt;&lt;/DialogTrigger&gt;<br>  &lt;DialogContent&gt;&lt;p&gt;Here’s your info.&lt;/p&gt;&lt;/DialogContent&gt;<br>&lt;/Dialog&gt;</pre><h4>🔸 Tabs / Navigation</h4><p>Organize data without reinventing tabs.</p><pre>&lt;Tabs defaultValue=&quot;overview&quot;&gt;<br>  &lt;TabsList&gt;<br>    &lt;TabsTrigger value=&quot;overview&quot;&gt;Overview&lt;/TabsTrigger&gt;<br>    &lt;TabsTrigger value=&quot;analytics&quot;&gt;Analytics&lt;/TabsTrigger&gt;<br>  &lt;/TabsList&gt;<br>  &lt;TabsContent value=&quot;overview&quot;&gt;Overview Content&lt;/TabsContent&gt;<br>&lt;/Tabs&gt;</pre><blockquote>Pro Tip: You can easily wrap these into reusable layout patterns to scale across pages.</blockquote><h3>💠 Why It’s a Game Changer</h3><ul><li><strong>Full ownership</strong>: every line of code belongs to you.</li><li><strong>Accessible by default</strong>: Radix handles it for you.</li><li><strong>Theme effortlessly</strong>: <em>Tailwind </em>makes customization painless.</li><li><strong>Composable architecture</strong>: mix, match, and scale easily.</li><li><strong>Ideal for production</strong>: reliable and maintainable in real apps.</li></ul><blockquote>shadcn/ui is more than a tool. It’s a workflow philosophy:<br><strong>Build faster</strong>. Customize deeper. Own your UI.</blockquote><h3>💠 Final Thoughts</h3><p>If you’re serious about frontend craft, shadcn/ui is the perfect middle ground, design-system quality components with total creative control.</p><p>TL;DR</p><ul><li>Tailwind + Radix + copy-owned components</li><li>Fully overrideable, flexible, and fast</li><li>Ideal for modern apps, dashboards, and SaaS UIs</li><li>Setup in minutes, maintain forever</li></ul><p>For more information, visit <a href="https://ui.shadcn.com/">shadcn/ui documentation</a>.</p><blockquote>And that’s it… Time to roll up your sleeves, build something stunning, and let shadcn/ui make your UI look effortlessly elite. You got this!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32c60042e716" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query Cheat Sheet]]></title>
            <link>https://medium.com/@skyshots/react-query-cheat-sheet-ba14e036def0?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba14e036def0</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 20:27:06 GMT</pubDate>
            <atom:updated>2025-10-10T20:27:06.417Z</atom:updated>
            <content:encoded><![CDATA[<p>React Query simplifies data fetching, caching, synchronization, and updating in React apps so you can focus on your <strong>UI</strong>, not API states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*7d_Ibtzw9Z-IRz6DSfmdjw.png" /></figure><h3>1️⃣ useQuery(): Fetch, Cache &amp; Sync Data</h3><pre>import { useQuery } from &quot;@tanstack/react-query&quot;;<br><br>const { data, isLoading, isError, error, refetch, isFetching } = useQuery({<br>  queryKey: [&quot;todos&quot;], // unique identifier for caching<br>  queryFn: async () =&gt; {<br>    const res = await fetch(&quot;/todos&quot;);<br>    if (!res.ok) throw new Error(&quot;Failed to fetch todos&quot;);<br>    return res.json();<br>  },<br>  enabled: true,        // whether to run automatically<br>  staleTime: 1000 * 60, // data stays “fresh” for 1 min<br>  refetchOnWindowFocus: true, // auto-refetch when window refocuses<br>  retry: 2,             // retry failed requests (default: 3)<br>});</pre><h4>State Flags</h4><ul><li>isLoading : First-time fetch in progress</li><li>isFetching : Any refetch (manual or auto) in progress</li><li>isError : Fetch failed</li><li>error : Error object</li><li>data : Response data</li><li>refetch() : Manually trigger query</li></ul><h3>Advanced Patterns</h3><h4>Dependent Query:</h4><pre>useQuery({<br>  queryKey: [&quot;user&quot;, userId],<br>  queryFn: () =&gt; fetch(`/user/${userId}`).then(res =&gt; res.json()),<br>  enabled: !!userId, // only runs when userId is truthy<br>});</pre><h4>Pagination:</h4><pre>useQuery({<br>  queryKey: [&quot;todos&quot;, page],<br>  queryFn: () =&gt; fetch(`/todos?page=${page}`).then(r =&gt; r.json()),<br>  keepPreviousData: true, // keep old page data until new loads<br>});</pre><h4>Polling / Live Refetch:</h4><pre>refetchInterval: 10000, // refetch every 10s</pre><h3>2️⃣ useMutation(): Create, Update &amp; Delete (Write Ops)</h3><pre>import { useMutation, useQueryClient } from &quot;@tanstack/react-query&quot;;<br><br>const queryClient = useQueryClient();<br><br>const mutation = useMutation({<br>  mutationFn: async (todo) =&gt; {<br>    const res = await fetch(&quot;/todos&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>      body: JSON.stringify(todo),<br>    });<br>    return res.json();<br>  },<br>  onSuccess: () =&gt; {<br>    queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }); // refresh cache<br>  },<br>});</pre><h4>Mutation States</h4><ul><li>isPending : Mutation in progress</li><li>isSuccess : Successfully completed</li><li>isError : Failed mutation</li><li>data : Success response</li><li>error : Error object</li></ul><h4>Triggering Mutations</h4><pre>mutation.mutate({ title: &quot;New Todo&quot; });      // callback style<br>await mutation.mutateAsync({ title: &quot;...&quot; }); // async/await style</pre><h3>3️⃣ CRUD Patterns</h3><h4>Create</h4><ul><li>Method: POST</li><li>eg: addTodoMutation.mutate({ title: “New Todo” })</li></ul><h4>Update</h4><ul><li>Method: PUT / PATCH</li><li>eg: updateTodoMutation.mutate({ id: 1, completed: true })</li></ul><h4>Delete</h4><ul><li>Method: DELETE</li><li>eg: deleteTodoMutation.mutate(1)</li></ul><blockquote>💡 Always invalidate or update cache:</blockquote><pre>queryClient.invalidateQueries([&quot;todos&quot;]);<br>// or<br>queryClient.setQueryData([&quot;todos&quot;], newData);</pre><h3>4️⃣ Optimistic Updates: Instant UI Feedback</h3><pre>useMutation({<br>  mutationFn: toggleTodo,<br>  onMutate: async (updatedTodo) =&gt; {<br>    await queryClient.cancelQueries([&quot;todos&quot;]);<br>    const previousTodos = queryClient.getQueryData([&quot;todos&quot;]);<br><br>    queryClient.setQueryData([&quot;todos&quot;], (old) =&gt;<br>      old.map(t =&gt;<br>        t.id === updatedTodo.id ? { ...t, completed: !t.completed } : t<br>      )<br>    );<br><br>    return { previousTodos };<br>  },<br>  onError: (_err, _todo, context) =&gt; {<br>    queryClient.setQueryData([&quot;todos&quot;], context.previousTodos);<br>  },<br>  onSettled: () =&gt; {<br>    queryClient.invalidateQueries([&quot;todos&quot;]);<br>  },<br>});</pre><h4>Why use it:</h4><ul><li>⚡ Instantly updates the UI for a smooth experience</li><li>🧭 Rolls back if the request fails</li><li>🔁 Keeps data fresh via background refetch</li></ul><h3>5️⃣ useQueryClient(): Manual Cache Control</h3><pre>const queryClient = useQueryClient();<br><br>// Read cached data<br>const todos = queryClient.getQueryData([&quot;todos&quot;]);<br><br>// Write / update cache manually<br>queryClient.setQueryData([&quot;todos&quot;], [...todos, newTodo]);<br><br>// Remove specific query<br>queryClient.removeQueries([&quot;todos&quot;]);</pre><h3>6️⃣ Best Practices</h3><h4>Stable queryKeys</h4><p>Use arrays instead of dynamic string. eg: [&quot;todos&quot;, userId, filters]</p><h4><strong>Minimal mutationFn</strong></h4><p>Only handle API calls. Keep logic in lifecycle callbacks.</p><h4><strong>Selective invalidation</strong></h4><p>Invalidate specific queries, not the entire cache to avoid over-fetching.</p><h4>Dependent queries</h4><p>Use enabled to wait for required data.</p><h4>Optimistic UI</h4><p>Make user experience snappy, especially in CRUD-heavy apps.</p><h4>Background refetch</h4><p>Perfect for dashboards or live metrics.</p><h3>7️⃣ Key Config Options</h3><ul><li>staleTime : Data freshness duration</li><li>cacheTime : How long unused data stays cached</li><li>retry : Number of retries on failure</li><li>enabled : Conditionally run the query</li><li>refetchOnWindowFocus : Auto-refetch when window regains focus</li><li>refetchInterval : Polling interval for live updates</li></ul><h3>8️⃣ Quick Summary Table</h3><h4>useQuery():</h4><ul><li>Purpose: Fetch / cache (GET)</li><li>Trigger: Auto</li><li>Common Flags: isLoading, isError, data</li></ul><h4>useMutation():</h4><ul><li>Purpose: Modify data (POST/PUT/PATCH/DELETE)</li><li>Trigger: Manual</li><li>Common Flags: isPending, isSuccess, isError, data</li></ul><h3>9️⃣ Pro Tips</h3><ul><li>Use <strong>React Query Devtools</strong> for live cache inspection.</li><li>Combine with <strong>Zustand</strong> or <strong>Jotai</strong> for app-wide state</li><li>For SSR: use dehydrate() + Hydrate from React Query.</li></ul><p>For prefetching:</p><pre>await queryClient.prefetchQuery([&quot;todos&quot;], fetchTodos);</pre><p>Clear cache:</p><pre>queryClient.clear();</pre><p>For SSR (Next.js):</p><pre>import { dehydrate, Hydrate } from &quot;@tanstack/react-query&quot;;</pre><h3>TL;DR</h3><p>React Query lets you:</p><ul><li>Fetch data with useQuery()</li><li>Mutate data with useMutation()</li><li>Keep UI synced with cache</li><li>Write cleaner, declarative async logic</li></ul><blockquote>✨ <em>Data management made elegant, performant, and frustration-free.</em></blockquote><p>That’s it for now devs. Keep learning and keep enjoying!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba14e036def0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging React Query’s useQuery() and useMutation() for Real-World Workflows]]></title>
            <link>https://medium.com/@skyshots/bridging-react-querys-usequery-and-usemutation-for-real-world-workflows-db44adb060e2?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/db44adb060e2</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 19:26:57 GMT</pubDate>
            <atom:updated>2025-10-10T19:26:57.217Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>query invalidation, cache updates, dependent queries, pagination, and background refetching</strong>, all with simple code snippets and explanations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H_tO8LUHHPyUlC-XJcWKlw.jpeg" /></figure><p>In our previous blogs, we covered <a href="https://medium.com/@skyshots/react-query-for-beginners-mastering-usequery-515a8c57e743"><strong>useQuery()</strong></a> for fetching data and <a href="https://medium.com/@skyshots/react-querys-usemutation-because-not-everything-s-a-get-request-4cddd13ed375"><strong>useMutation()</strong></a> for creating, updating, and deleting Todos.</p><p>Now it’s time to see how both hooks work <strong>together</strong> in realistic workflows giving your app a clean, responsive, and reliable server-state management structure.</p><p>We’ll explore <strong>query invalidation, cache updates, dependent queries, pagination, and background refetching</strong>, all with simple code snippets and explanations.</p><h3><strong>1️⃣ Refreshing Data After Mutations (Query Invalidation)</strong></h3><p>When you mutate data (create, update, delete), you often want your <strong>list of Todos</strong> to stay up-to-date.<br> React Query provides queryClient.invalidateQueries() for this.</p><pre>const addTodoMutation = useMutation({<br>  mutationFn: async (todo) =&gt; {<br>    const res = await fetch(&quot;/todos&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>      body: JSON.stringify(todo),<br>    });<br>    if (!res.ok) throw new Error(&quot;Failed to add todo&quot;);<br>    return res.json();<br>  },<br>  onSuccess: () =&gt; queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }),<br>});</pre><h4><strong>Explanation:</strong></h4><ul><li>invalidateQueries([“todos”]) marks the cached “todos” data as stale.</li><li>Any component using useQuery([“todos”]) will <strong>refetch automatically</strong>, keeping the UI in sync with the server.</li></ul><h3>2️⃣ <strong>Updating Cache Directly (Optimistic or Instant UI Updates)</strong></h3><p>Instead of waiting for the server, you can <strong>update the cache immediately</strong> using queryClient.setQueryData().</p><pre>const toggleTodoMutation = useMutation({<br>  mutationFn: async (todo) =&gt;<br>    fetch(`/todos/${todo.id}`, {<br>      method: &quot;PATCH&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>      body: JSON.stringify({ completed: !todo.completed }),<br>    }),<br>  onMutate: async (todo) =&gt; {<br>    await queryClient.cancelQueries({ queryKey: [&quot;todos&quot;] });<br>    const previous = queryClient.getQueryData([&quot;todos&quot;]);<br>    const index = previous.findIndex((t) =&gt; t.id === todo.id);<br>    const updated = [...previous];<br>    updated[index] = { ...updated[index], completed: !updated[index].completed };<br>    queryClient.setQueryData([&quot;todos&quot;], updated);<br>    return { previous };<br>  },<br>  onError: (_err, _todo, context) =&gt;<br>    context?.previous &amp;&amp; queryClient.setQueryData([&quot;todos&quot;], context.previous),<br>  onSettled: () =&gt; queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }),<br>});</pre><h4><strong>Explanation:</strong></h4><ul><li>onMutate → runs before the mutation, updates the cache instantly.</li><li>onError → rolls back the change if the mutation fails.</li><li>onSettled → ensures the data is always synchronized with the server.</li></ul><h3>3️⃣ <strong>Dependent Queries (Chained Fetches)</strong></h3><p>Sometimes, one query depends on another query’s data. Use the enabled key to prevent unnecessary calls.</p><pre>const userQuery = useQuery({<br>  queryKey: [&quot;user&quot;, userId],<br>  queryFn: () =&gt; fetch(`/users/${userId}`).then(res =&gt; res.json()),<br>});<br><br>const postsQuery = useQuery({<br>  queryKey: [&quot;posts&quot;, userQuery.data?.id],<br>  queryFn: () =&gt; fetch(`/posts?userId=${userQuery.data.id}`).then(res =&gt; res.json()),<br>  enabled: !!userQuery.data,<br>});</pre><h4><strong>Explanation:</strong></h4><ul><li>postsQuery will only run <strong>after </strong>userQuery<strong> has finished</strong>.</li><li>enabled: !!userQuery.data prevents a query from running when its dependencies are not ready.</li></ul><h3><strong>4️⃣ Pagination Basics</strong></h3><p>For large lists, you can fetch <strong>pages of data</strong> with a page and limit parameter.<br> React Query makes it easy with keepPreviousData.</p><pre>const [page, setPage] = useState(1);<br>const todosQuery = useQuery({<br>  queryKey: [&quot;todos&quot;, page],<br>  queryFn: () =&gt; fetch(`/todos?_page=${page}&amp;_limit=10`).then(res =&gt; res.json()),<br>  keepPreviousData: true,<br>});</pre><p><strong>Explanation:</strong></p><ul><li>keepPreviousData: true → avoids flickering when switching pages.</li><li>todosQuery.data now only contains 10 items per page.</li><li>You can trigger setPage(page + 1) to load the next page.</li></ul><h3>5️⃣ <strong>Background Refetching</strong></h3><p>Keep your UI fresh automatically with refetchOnWindowFocus or refetchInterval.</p><pre>const todosQuery = useQuery({<br>  queryKey: [&quot;todos&quot;],<br>  queryFn: () =&gt; fetch(&quot;/todos&quot;).then(res =&gt; res.json()),<br>  refetchOnWindowFocus: true,   // refetch when user returns to tab<br>  refetchInterval: 30000,       // refetch every 30s<br>});</pre><h4><strong>Explanation:</strong></h4><ul><li>Keeps your Todo list up-to-date in the background.</li><li>Great for dashboards or live-updating feeds.</li></ul><h3>6️⃣ <strong>Full CRUD Flow Example (Snippets)</strong></h3><h4><strong>Fetching Todos:</strong></h4><pre>const todosQuery = useQuery({<br>  queryKey: [&quot;todos&quot;],<br>  queryFn: () =&gt; fetch(&quot;/todos&quot;).then(res =&gt; res.json()),<br>});</pre><h4><strong>Creating a Todo:</strong></h4><pre>const addTodoMutation = useMutation({<br>  mutationFn: async (todo) =&gt; fetch(&quot;/todos&quot;, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify(todo),<br>  }).then(res =&gt; res.json()),<br>  onSuccess: () =&gt; queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }),<br>});</pre><h4><strong>Updating a Todo:</strong></h4><pre>const updateTodoMutation = useMutation({<br>  mutationFn: async (todo) =&gt; fetch(`/todos/${todo.id}`, {<br>    method: &quot;PATCH&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify(todo),<br>  }),<br>  onSuccess: () =&gt; queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }),<br>});</pre><h4><strong>Deleting a Todo:</strong></h4><pre>const deleteTodoMutation = useMutation({<br>  mutationFn: async (id) =&gt; fetch(`/todos/${id}`, { method: &quot;DELETE&quot; }),<br>  onSuccess: () =&gt; queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }),<br>});</pre><h3><strong>7️⃣ Best Practices</strong></h3><ul><li><strong>Stable queryKeys</strong> → always use arrays, e.g., [“todos”, page].</li><li><strong>Optimistic updates</strong> → for instant UI feedback.</li><li><strong>Invalidate selectively</strong> → <strong>don’t</strong> over-invalidate queries.</li><li><strong>Keep </strong>mutationFn<strong> minimal</strong> → only send the request, side-effects go in callbacks.</li><li><strong>Use </strong>enabled<strong> for dependent queries</strong> → prevent unnecessary API calls.</li><li><strong>Refetch wisely</strong> → for live data, dashboards, or when background sync is important.</li></ul><h3>8️⃣ <strong>Mini Component Example (Read + Create)</strong></h3><pre>export default function TodoDashboard() {<br>  const queryClient = useQueryClient();<br><br>  const todosQuery = useQuery({<br>    queryKey: [&quot;todos&quot;],<br>    queryFn: () =&gt; fetch(&quot;/todos&quot;).then(res =&gt; res.json()),<br>  });<br><br>  const addTodoMutation = useMutation({<br>    mutationFn: async (todo) =&gt; fetch(&quot;/todos&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>      body: JSON.stringify(todo),<br>    }).then(res =&gt; res.json()),<br>    onSuccess: () =&gt; queryClient.invalidateQueries({ queryKey: [&quot;todos&quot;] }),<br>  });<br><br>  const handleAdd = () =&gt; addTodoMutation.mutate({ userId: 1, title: &quot;New Todo&quot;, completed: false });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleAdd} disabled={addTodoMutation.isPending}&gt;<br>        {addTodoMutation.isPending ? &quot;Adding...&quot; : &quot;Add Todo&quot;}<br>      &lt;/button&gt;<br><br>      &lt;ul&gt;<br>        {todosQuery.data?.map(todo =&gt; (<br>          &lt;li key={todo.id}&gt;{todo.title}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3><strong>Conclusion</strong></h3><p>By now, you should understand how to:</p><ul><li>Combine useQuery()<strong> </strong>+<strong> </strong>useMutation() for realistic workflows.</li><li>Keep the <strong>cache and UI in sync</strong> using invalidateQueries or setQueryData.</li><li>Handle <strong>dependent queries, pagination, and background refetching</strong>.</li><li>Apply <strong>optimistic updates</strong> and proper error handling.</li></ul><p>This sets the stage for <strong>more advanced React Query features</strong>, like <strong>infinite queries</strong>, <strong>prefetching</strong>, and <strong>React Query Devtools.</strong></p><blockquote>This post completes the <strong>intermediate workflow layer</strong>:<br> read, write, update, delete, keeping everything in sync.</blockquote><p>In the next one, we’ll take a look at a simplified cheatsheet on React Query. Until then, enjoy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db44adb060e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query’s useMutation(): Because Not Everything’s a GET Request]]></title>
            <link>https://medium.com/@skyshots/react-querys-usemutation-because-not-everything-s-a-get-request-4cddd13ed375?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cddd13ed375</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mutation]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 18:27:54 GMT</pubDate>
            <atom:updated>2025-10-09T18:27:54.340Z</atom:updated>
            <content:encoded><![CDATA[<p>useMutation() is designed for <strong>writing or modifying data</strong> such as POST, PUT, PATCH, or DELETE operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvKy8_zgYqBgHPUFY9CRPw.jpeg" /></figure><h3><strong>1️⃣ Introduction</strong></h3><p>In our previous post, we explored <a href="https://medium.com/@skyshots/react-query-for-beginners-mastering-usequery-515a8c57e743">useQuery()</a>. The go-to hook for <strong>fetching and caching data</strong> in React Query.<br> But what about when you need to <strong>send data to the server</strong> like creating, updating, or deleting records?</p><p>That’s where useMutation() steps in.</p><p>While useQuery() focuses on <strong>reading data (GET requests)</strong>,<br> useMutation() is designed for <strong>writing or modifying data</strong> such as POST, PUT, PATCH, or DELETE operations.</p><p>Think of it like this:</p><ul><li>useQuery() → “Get me the current state of data.”</li><li>useMutation() → “Change something on the server.”</li></ul><h3>2️⃣ <strong>What is useMutation()?</strong></h3><p>useMutation() is a React Query hook that helps you manage <strong>side-effect-driven actions</strong> like:</p><ul><li>Submitting a form</li><li>Sending data to an API</li><li>Deleting an item from a list</li><li>Updating an existing resource</li></ul><p>It provides:</p><ul><li><strong>State flags:</strong> isPending, isSuccess, isError</li><li><strong>Lifecycle callbacks:</strong> onSuccess, onError, onSettled</li></ul><p>Unlike useQuery(), mutations are <strong>not automatic. </strong>You explicitly trigger them using mutate() or mutateAsync().</p><h3>3️⃣ <strong>Syntax &amp; Basic Example: </strong>Creating Data (POST Request)</h3><p>Let’s start simple by creating a new Todo.</p><pre>import { useMutation } from &quot;@tanstack/react-query&quot;;<br><br>function AddTodo() {<br>  const addTodoMutation = useMutation({<br>    // The async function that performs the mutation<br>    mutationFn: async (newTodo) =&gt; {<br>      const response = await fetch(&quot;https://jsonplaceholder.typicode.com/todos&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>        body: JSON.stringify(newTodo),<br>      });<br><br>      if (!response.ok) {<br>        throw new Error(&quot;Failed to add todo&quot;);<br>      }<br><br>      return response.json(); // The result of the mutation<br>    },<br><br>    // Called when the mutation succeeds<br>    onSuccess: (data) =&gt; {<br>      console.log(&quot;Todo added successfully:&quot;, data);<br>    },<br><br>    // Called if the mutation fails<br>    onError: (error) =&gt; {<br>      console.error(&quot;Error creating todo:&quot;, error);<br>    },<br><br>    // Called no matter success or failure<br>    onSettled: () =&gt; {<br>      console.log(&quot;Mutation completed.&quot;);<br>    },<br>  });<br><br>  // Function to handle form submission<br>  const handleAddTodo = () =&gt; {<br>    const newTodo = {<br>      userId: 1,<br>      title: &quot;Learn React Query useMutation&quot;,<br>      completed: false,<br>    };<br><br>    // Trigger the mutation<br>    addTodoMutation.mutate(newTodo);<br>  };<br><br>  return (<br>    &lt;div style={{ padding: &quot;1rem&quot; }}&gt;<br>      &lt;button onClick={handleAddTodo} disabled={addTodoMutation.isPending}&gt;<br>        {addTodoMutation.isPending ? &quot;Adding Todo...&quot; : &quot;Add Todo&quot;}<br>      &lt;/button&gt;<br><br>      {addTodoMutation.isError &amp;&amp; (<br>        &lt;p style={{ color: &quot;red&quot; }}&gt;Error: {addTodoMutation.error.message}&lt;/p&gt;<br>      )}<br><br>      {addTodoMutation.isSuccess &amp;&amp; (<br>        &lt;p style={{ color: &quot;green&quot; }}&gt;Todo added successfully!&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>Breaking it Down</strong></h4><p>Let’s go over each part carefully:</p><ul><li>mutationFn → The core function that performs your API request.<br> It must return a promise, and if something goes wrong, it should throw an error.</li><li>mutate() → The function you call to trigger the mutation.<br> It automatically updates states like isPending, isSuccess, and isError.</li><li>onSuccess, onError, onSettled → Lifecycle callbacks to handle post-mutation logic such as showing a toast, clearing inputs, or refreshing queries.</li></ul><h4><strong>Mutation states</strong>:</h4><ul><li>isPending: The mutation is currently running.</li><li>isSuccess: The mutation completed successfully.</li><li>isError: The mutation failed</li><li>data: The successful response data</li><li>error: The error object if mutation failed</li></ul><h3><strong>Key Takeaways So Far</strong></h3><p>🔸useMutation() is <strong>manual</strong>, not automatic, you control when it runs.</p><p>🔸It’s perfect for POST, PUT, PATCH, DELETE requests.</p><p>🔸Offers <strong>state management + lifecycle hooks</strong> out of the box.</p><p>🔸Works great with queryClient.invalidateQueries() .</p><h3>Updating Data (PUT / PATCH Request)</h3><p>We can reuse most of the <strong>Create Todo</strong> code. Only the mutation function and button label change.</p><pre>// Create similar mutationFn as AddTodo<br>const updateTodoMutation = useMutation({<br>  mutationFn: async (updatedTodo) =&gt; {<br>    const response = await fetch(<br>      `https://jsonplaceholder.typicode.com/todos/${updatedTodo.id}`,<br>      {<br>        method: &quot;PUT&quot;, // or &quot;PATCH&quot; if updating specific fields<br>        headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        body: JSON.stringify(updatedTodo),<br>      }<br>    );<br><br>    if (!response.ok) throw new Error(&quot;Failed to update todo&quot;);<br>    return response.json();<br>  },<br>  onSuccess: () =&gt; alert(&quot;Todo updated successfully!&quot;),<br>  onError: (error) =&gt; alert(error.message),<br>});</pre><p>Use inside your component:</p><pre><br>const handleUpdateTodo = () =&gt; {<br>  const updatedTodo = {<br>    id: 1,<br>    title: &quot;Learn useMutation in detail (updated)&quot;,<br>    completed: true,<br>    userId: 1,<br>  };<br><br>  updateTodoMutation.mutate(updatedTodo);<br>};</pre><p>Everything else like UI, button, and states can stay the same as in the <strong>AddTodo</strong> example.</p><h4><strong>Tips:</strong></h4><ul><li>Use PUT when replacing the entire resource.</li><li>Use PATCH when updating only certain fields.</li><li>Same mutation pattern, same lifecycle callbacks just a different HTTP method.</li></ul><h3>Deleting Data (DELETE Request)</h3><p>Again, we’ll reuse the same base component. Only the <strong>mutation function</strong> and <strong>handler</strong> differ.</p><pre>// Create similar mutationFn as AddTodo<br>const deleteTodoMutation = useMutation({<br>  mutationFn: async (todoId) =&gt; {<br>    const response = await fetch(<br>      `https://jsonplaceholder.typicode.com/todos/${todoId}`,<br>      { method: &quot;DELETE&quot; }<br>    );<br><br>    if (!response.ok) throw new Error(&quot;Failed to delete todo&quot;);<br>    return true; // since DELETE APIs often return empty response<br>  },<br>  onSuccess: () =&gt; alert(&quot;Todo deleted successfully!&quot;),<br>  onError: (error) =&gt; alert(error.message),<br>});</pre><p>Use inside your component:</p><pre>// 🗑️ Use inside your component<br>const handleDeleteTodo = () =&gt; {<br>  const todoId = 1; // ID of the item to delete<br>  deleteTodoMutation.mutate(todoId);<br>};</pre><p>UI and structure remain the same, just replace your button label and hook references (deleteTodoMutation instead of addTodoMutation).</p><h4><strong>Tips:</strong></h4><ul><li>Pass only the id of the item to delete.</li><li>You can return true or an empty object depending on your API.</li><li>Use onSuccess to invalidate or refetch queries so your UI updates automatically.</li></ul><h3>4️⃣ Comparing All Three Mutation Types</h3><ul><li>Create: usesPOST method. Used to add a new resource.</li><li>Update: uses PUT /PATCH method. Used to edit or replace resource.</li><li>Delete: usesDELETE method. Used to remove resource.</li></ul><p>Each one:</p><ul><li>Uses a mutationFn that performs the request.</li><li>Triggers with mutate(data) or mutate(id).</li><li>Has the same state tracking (isPending, isSuccess, isError, etc.).</li><li>Can use onSuccess to refresh the data afterward.</li></ul><h3>5️⃣ <strong>Summary</strong></h3><p>You’ve now learned how to:</p><ul><li>Create, update, and delete data using useMutation().</li><li>Understand how mutationFn works with arguments.</li><li>Use onSuccess and onError for post-action handling.</li></ul><blockquote>At its core, useMutation() and useQuery() doesn’t replace your API logic. It <strong>wraps your fetch or Axios calls</strong> with TanStack Query’s smart state management.</blockquote><p>You still write the same API request fetch(), axios.post(), etc., but React Query handles everything around it like <strong>loading states</strong>, <strong>error tracking</strong>, <strong>retries</strong>, and <strong>caching </strong>— and exposes simple boolean flags (isPending, isSuccess, isError, etc.) to make UI handling effortless.</p><p>So instead of you manually managing things like:</p><pre>const [loading, setLoading] = useState(false);<br>const [error, setError] = useState(null);<br>const [data, setData] = useState(null);</pre><p>you can just do this:</p><pre>const mutation = useMutation({ mutationFn: addTodo });</pre><p>And get all that functionality <em>for free</em> through:</p><pre>mutation.isPending<br>mutation.isSuccess<br>mutation.isError<br>mutation.data<br>mutation.error</pre><p>That’s why TanStack Query is often described as:</p><blockquote>“A declarative way to manage server state — without all the manual loading and error juggling.”</blockquote><p>That&#39;s it for now, we shall continue few more concepts regarding React Query in the upcoming posts. Keep learning and keep supporting. <br>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cddd13ed375" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query for Beginners: Mastering useQuery()]]></title>
            <link>https://medium.com/@skyshots/react-query-for-beginners-mastering-usequery-515a8c57e743?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/515a8c57e743</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-state-management]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 16:31:53 GMT</pubDate>
            <atom:updated>2025-10-02T16:31:53.597Z</atom:updated>
            <content:encoded><![CDATA[<p>React Query, now part of the open-source library <strong>TanStack Query</strong>, is a data-fetching and state management library for React applications. It is designed to handle server state, data that comes from a remote source like an API, freeing developers from writing manual fetching, caching, and synchronization logic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lXLC8EpIkKmbXPhYhupYOw.jpeg" /></figure><h3>Key features</h3><p>React Query simplifies complex data-handling scenarios with several built-in features:</p><ul><li><strong>Automatic caching:</strong> It stores fetched data locally with a <strong>unique query key</strong> to prevent unnecessary network requests. When you request the same data again, it is served instantly from the cache while a background refetch is triggered to check for fresh data.</li><li><strong>Background synchronization:</strong> It automatically keeps your client-side data in sync with the server by refetching when the user re-focuses the window or reconnects to the network.</li><li><strong>Optimistic updates:</strong> When a user takes an action, React Query can instantly update the UI as if the change were successful. If the network request fails, it rolls back the UI to its previous state.</li><li><strong>Performance optimizations:</strong> It includes features like request deduplication, which prevents multiple identical requests from being sent simultaneously. It also offers powerful tools for pagination and infinite scrolling.</li><li><strong>Developer tools:</strong> The library includes a suite of developer tools that provide a real-time view of your application’s queries, mutations, and cache, making debugging much easier.</li><li><strong>Dedicated hooks:</strong> It uses two primary hooks for handling data:<br>1. useQuery for fetching and reading data.<br>2. useMutation for creating, updating, or deleting data.</li></ul><p>In this blog we will focus on <strong>useQuery()</strong> and see how it’s used to<strong> fetch and cache server data</strong>.</p><h3>1️⃣ Setting Up React Query</h3><p>Install the packages:</p><pre>npm install @tanstack/react-query @tanstack/react-query-devtools</pre><p>Wrap your app with <strong>QueryClientProvider</strong>:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;;<br><br>const queryClient = new QueryClient();<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)!).render(<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;App /&gt;<br>      &lt;ReactQueryDevtools initialIsOpen={false} /&gt;<br>    &lt;/QueryClientProvider&gt;<br>);</pre><p><strong>Why:</strong></p><ul><li>QueryClient manages <strong>queries, caching, and states</strong>.</li><li>QueryClientProvider makes QueryClient available across your app.</li><li>Devtools are optional but great for beginners to see how queries work.</li></ul><h3>2️⃣ Basics of useQuery() with Object Syntax</h3><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br><br>const fetchTodos = async () =&gt; {<br>  const res = await fetch(&#39;https://jsonplaceholder.typicode.com/todos?_limit=5&#39;);<br>  if (!res.ok) throw new Error(&#39;Failed to fetch todos&#39;);<br>  return res.json();<br>};<br><br>export default function Todos() {<br>  const { data, error, isLoading, isError, isFetching, refetch, status } = useQuery({<br>    queryKey: [&#39;todos&#39;],         // Unique key for caching<br>    queryFn: fetchTodos,         // Function returning a Promise<br>  });<br><br>  if (isLoading) return &lt;p&gt;Loading todos...&lt;/p&gt;;<br>  if (isError) return &lt;p&gt;Error: {(error as Error).message}&lt;/p&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Todo List&lt;/h2&gt;<br>      &lt;button onClick={() =&gt; refetch()}&gt;Refetch Todos&lt;/button&gt;<br>      {isFetching &amp;&amp; &lt;p&gt;Updating todos...&lt;/p&gt;}<br>      &lt;ul&gt;<br>        {data.map((todo: any) =&gt; (<br>          &lt;li key={todo.id}&gt;<br>            {todo.title} {todo.completed ? &#39;✅&#39; : &#39;❌&#39;}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>      &lt;p&gt;Status: {status}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>What is queryKey and queryFn ?</h4><p>queryKey is the unique identifier React Query uses to <strong>cache</strong>, <strong>deduplicate</strong>, <strong>refetch</strong>, and <strong>invalidate</strong> queries. Think of it as the query&#39;s name + parameters.</p><h4>What it gives you:</h4><ul><li><strong>Caching</strong>: results are stored under that key so future components with the same key get the cached result instantly.</li><li><strong>Deduplication</strong>: if two components request the same queryKey at the same time, React Query makes one network call and shares the result.</li><li><strong>Invalidation / Refetch</strong>: you can call queryClient.invalidateQueries({ queryKey }) to mark that key stale and force a refetch.</li><li><strong>Parameterization</strong>: include variables (userId, filters, page) in the key so each distinct dataset has its own cache entry.</li></ul><h3>What is queryFn ?</h3><p>The queryFn (query function) is the <strong>asynchronous function</strong> React Query calls to actually fetch your data.</p><p>Think of it like this:</p><ul><li>queryKey = <em>“What data are we talking about?”</em> (identity &amp; cache key)</li><li>queryFn = <em>“How do we go get that data?”</em> (the fetch instructions)</li></ul><h4>Important details about queryFn:</h4><p>It <strong>must return a promise</strong> that resolves with the data (React Query handles .then/.catch under the hood).</p><p>It is called automatically whenever the query needs to fetch:</p><ul><li>the first mount (if enabled is true)</li><li>when the query becomes <strong>stale</strong></li><li>when you manually refetch()</li><li>after an invalidation (invalidateQueries)</li></ul><p>React Query expects the function to <strong>throw errors</strong> (instead of swallowing them) so it can correctly set isError and error.</p><h4>Examples of queryFn:</h4><p><strong>🔸Simple fetch with Fetch API</strong></p><pre>const todosQuery = useQuery({<br>  queryKey: [&#39;todos&#39;],<br>  queryFn: () =&gt;<br>    fetch(&#39;/api/todos&#39;).then((res) =&gt; {<br>      if (!res.ok) throw new Error(&#39;Network response was not ok&#39;);<br>      return res.json();<br>    }),<br>});</pre><p><strong>🔸Parameterized query (queryKey values as params)</strong></p><pre>const searchQuery = useQuery({<br>  queryKey: [&#39;search&#39;, term],<br>  queryFn: ({ queryKey }) =&gt; {<br>    const [_key, term] = queryKey;<br>    return fetch(`/api/search?q=${term}`).then((res) =&gt; res.json());<br>  },<br>  enabled: term.length &gt; 2,<br>});</pre><p>Notice in this example that queryFn <strong>receives an object</strong> with queryKey.<br>This is useful when your fetch logic depends on key parameters.</p><h4>Best practices for queryFn:</h4><ul><li>Always make it return <strong>clean data</strong> (parse JSON, pick fields, etc.) so components don’t need to transform responses.</li><li>Throw errors inside queryFn so React Query can handle error states.</li><li>Keep it <strong>pure</strong>, don’t mutate outside variables or state inside queryFn.</li><li>Extract fetch logic into a separate function/service for reusability.</li></ul><p>So in summary:</p><ul><li>queryKey = <strong>identity of data</strong></li><li>queryFn = <strong>how to fetch that data</strong></li></ul><h4>Benefits of Object Syntax:</h4><ul><li>Easier to read and manage.</li><li>Allows adding options like staleTime, enabled, refetchOnWindowFocus, etc.</li><li>Makes code more maintainable for intermediate/advanced queries.</li></ul><h3>3️⃣ Useful useQuery() Properties</h3><p>These are some of the properties that are provided by useQuery() and what they do:</p><p>data : Fetched data (or undefined).</p><p>error: Error object if query failed.</p><p>isLoading: True during first fetch.</p><p>isError: True if query failed.</p><p>isFetching: True whenever query fetches (even background).</p><p>isSuccess: True when data successfully loaded.</p><p>refetch: Function to manually refetch.</p><p>isStale: True if cached data is outdated.</p><h3>4️⃣ Controlling Stale Data</h3><p>In React Query, data is considered <strong>stale</strong> when the time set by the staleTime option has elapsed, indicating that the cached data may no longer be fresh or up-to-date.</p><p>Here’s a breakdown of what that means in practice:</p><ul><li><strong>The initial fetch:</strong> When you first query data, React Query fetches it from your API and stores it in its cache.</li><li><strong>Default </strong>staleTime<strong> is </strong>0<strong>:</strong> By default, data is considered stale the very moment it is fetched.</li><li><strong>Behavior with stale data:</strong> When a query’s data is stale, React Query will serve the cached data immediately to give the user a fast response. It will then trigger a <em>background refetch</em> to get the fresh data from the server and update the UI silently.</li></ul><p>This background refetching is triggered automatically on certain events, such as when:</p><ul><li>A new instance of a component using the query mounts.</li><li>The browser window is refocused.</li><li>The network connection is re-established.</li></ul><pre>const { data, isStale } = useQuery({<br>  queryKey: [&#39;todos&#39;],<br>  queryFn: fetchTodos,<br>  staleTime: 10000, // 10 seconds<br>});</pre><ul><li>Fresh for 10 seconds.</li><li>After that, isStale becomes true, meaning data is no longer fresh.</li><li>It can be manually invalidated when needed:</li></ul><pre>import { useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br>const queryClient = useQueryClient();<br>queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] }); // Marks data as stale</pre><h3>5️⃣ Refetch Options</h3><p>By adding refetchOnWindowFocus &amp; refetchInterval you can control refetching respectively.</p><pre>const { data, refetch } = useQuery({<br>  queryKey: [&#39;todos&#39;],<br>  queryFn: fetchTodos,<br>  refetchOnWindowFocus: true, // Auto-refetch when tab gains focus<br>  refetchInterval: 5000,      // Auto-refetch every 5 seconds<br>});</pre><h3>6️⃣ Example With All Common States</h3><pre>const { data, error, isLoading, isError, isFetching, isSuccess, refetch, status } = useQuery({<br>  queryKey: [&#39;todos&#39;],<br>  queryFn: fetchTodos,<br>  staleTime: 5000,<br>});<br><br>return (<br>  &lt;div&gt;<br>    &lt;button onClick={() =&gt; refetch()}&gt;Refetch Todos&lt;/button&gt;<br>    {isLoading &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>    {isError &amp;&amp; &lt;p&gt;Error: {(error as Error).message}&lt;/p&gt;}<br>    {isFetching &amp;&amp; &lt;p&gt;Updating in background...&lt;/p&gt;}<br>    {isSuccess &amp;&amp; (<br>      &lt;ul&gt;<br>        {data.map((todo: any) =&gt; (<br>          &lt;li key={todo.id}&gt;{todo.title}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    )}<br>    &lt;p&gt;Status: {status}&lt;/p&gt;<br>  &lt;/div&gt;<br>);</pre><p>Shows loading, error, success, background fetching clearly.</p><h3>7️⃣ Summary</h3><p>With object syntax for useQuery(), beginners can:</p><ul><li>Fetch server data cleanly.</li><li>Track all query states (isLoading, isFetching, isError, isSuccess).</li><li>Use refetch() for manual refresh.</li><li>Control stale/fresh data and automatic background updates.</li></ul><h3>Conclusion:</h3><p>Now that you’re comfortable with how useQuery() handles declarative data fetching, it&#39;s a great time to move on to useMutation() for performing &quot;write&quot; operations.</p><p>While useQuery() is for reading data (GET requests), useMutation() is used for creating, updating, or deleting data (POST, PUT, or DELETE requests).</p><blockquote>We’ll continue this journey in our next post with useMutation(), where we’ll learn how to manage data changes effectively. Until then, keep experimenting and growing with React Query.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=515a8c57e743" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Taking Zustand Further: Persist, Immer, and DevTools Explained]]></title>
            <link>https://medium.com/@skyshots/taking-zustand-further-persist-immer-and-devtools-explained-ab4493083ca1?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab4493083ca1</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[zustand]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 16:32:07 GMT</pubDate>
            <atom:updated>2025-09-30T16:32:07.499Z</atom:updated>
            <content:encoded><![CDATA[<p>In the <a href="https://medium.com/@skyshots/zustand-effortless-state-management-for-react-ff33f86141f6">previous blog</a>, we introduced Zustand and built a simple store from scratch. We learned what state is, how to create a store, and how components subscribe to it. That was a solid foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*aJZ3Qt6ZwsrEnTu0HIFe7g.png" /><figcaption>zustand part 2</figcaption></figure><p>In real-world apps, state management needs more than just “get and set”.</p><ul><li>Sometimes you want your state to <strong>stick around after refresh</strong> (persist).</li><li>Sometimes your state is <strong>nested or complex</strong>, and writing immutable updates manually is painful (immer).</li><li>Sometimes you’re debugging a tricky flow and need <strong>time-travel and action history</strong> (devtools).</li></ul><p>This is where <strong>Zustand middlewares</strong> come in.</p><p>In this blog, we’ll look at the <strong>three most commonly used middlewares</strong>:</p><ol><li>Persist: saving and hydrating state.</li><li>Immer: simpler updates for nested state.</li><li>Devtools: debugging state changes like a pro.</li></ol><p>We’ll use real-life examples (token &amp; theme, shopping cart, UI filters) to show why these middlewares matter, how to add them, and how they make your code cleaner compared to doing everything manually.</p><h3>1️⃣ Persist: Keep Your State Across Refreshes</h3><h4>What it does</h4><p>Normally, when you refresh a page, Zustand resets to the initial state. That’s fine for ephemeral UI state (like “is modal open?”), but bad for:</p><ul><li>Authentication tokens</li><li>User preferences (theme or language)</li><li>Cart items</li></ul><p>Manually wiring localStorage everywhere quickly becomes messy.</p><h4>Before persist (manual way)</h4><pre>// In your component<br>const [token, setToken] = useState(localStorage.getItem(&quot;token&quot;));<br><br>useEffect(() =&gt; {<br>  localStorage.setItem(&quot;token&quot;, token);<br>}, [token]);</pre><ul><li>Repeated across components.</li><li>Easy to forget hydration logic.</li><li>No central control.</li></ul><h4>After persist (with Zustand)</h4><pre>// src/stores/userStore.ts<br>import { create } from &quot;zustand&quot;;<br>import { persist } from &quot;zustand/middleware&quot;; <br><br>interface UserState {<br>  token: string | null;<br>  theme: &quot;light&quot; | &quot;dark&quot;;<br>  setToken: (t: string) =&gt; void;<br>  toggleTheme: () =&gt; void;<br>}<br>export const useUserStore = create&lt;UserState&gt;()(<br>  persist(<br>    (set) =&gt; ({<br>      token: null,<br>      theme: &quot;light&quot;,<br>      setToken: (token) =&gt; set({ token }),<br>      toggleTheme: () =&gt;<br>        set((s) =&gt; ({ theme: s.theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot; })),<br>    }),<br>    {<br>      name: &quot;user-store&quot;,              // storage key<br>      getStorage: () =&gt;<br>        typeof window !== &quot;undefined&quot; ? localStorage : undefined,<br>      partialize: (s) =&gt; ({ token: s.token, theme: s.theme }), // save only what&#39;s needed<br>    }<br>  )<br>);</pre><h4>How it works under the hood</h4><ul><li>Every time you call set, persist serializes part of your state and writes it to localStorage.</li><li>When your app starts, it <strong>rehydrates</strong> the store with saved data.</li><li>You don’t touch localStorage directly, the middleware handles it.</li></ul><h4>Where to use it in code</h4><ul><li>Wrap your <strong>auth store</strong>, <strong>preferences store</strong>, or <strong>cart store</strong> with persist.</li><li>For ephemeral UI state (like a modal), skip persist, you don’t want to restore “modal open” after refresh.</li></ul><h3>2️⃣ Immer: Make Nested Updates Easy</h3><h4>What it does</h4><p>React state must be updated immutably. Without help, you end up writing lots of spread operators and map/filter boilerplate.</p><p><strong>Immer</strong> (already integrated with Zustand) lets you write code as if you were mutating state directly, while it ensures immutability under the hood.</p><h4>Before immer (manual updates)</h4><pre>set((state) =&gt; ({<br>  items: state.items.map((i) =&gt;<br>    i.id === id ? { ...i, quantity: i.quantity + 1 } : i<br>  ),<br>}));</pre><h4>After immer (with Zustand)</h4><pre>import { create } from &quot;zustand&quot;;<br>import { immer } from &quot;zustand/middleware/immer&quot;;<br><br>interface CartItem { id: string; quantity: number; }<br>interface CartState {<br>  items: CartItem[];<br>  addItem: (id: string) =&gt; void;<br>  removeItem: (id: string) =&gt; void;<br>}<br>export const useCartStore = create&lt;CartState&gt;()(<br>  immer((set) =&gt; ({<br>    items: [],<br>    addItem: (id) =&gt;<br>      set((s) =&gt; {<br>        const existing = s.items.find((i) =&gt; i.id === id);<br>        if (existing) existing.quantity++;<br>        else s.items.push({ id, quantity: 1 });<br>      }),<br>    removeItem: (id) =&gt;<br>      set((s) =&gt; {<br>        s.items = s.items.filter((i) =&gt; i.id !== id);<br>      }),<br>  }))<br>);</pre><h4>Where to use it in code</h4><ul><li>Stores with <strong>nested objects or arrays</strong> that change frequently (cart items, nested filters, dashboards).</li><li>Avoid it for very flat state (like theme: “light” | “dark”), that’s overkill.</li></ul><h3>3️⃣ DevTools: Debug State Like a Pro</h3><h4>What it does</h4><p>Instead of sprinkling console.log() everywhere, you can track all state changes in the <strong>Redux DevTools</strong> browser extension.</p><p>You get:</p><ul><li>Action names</li><li>Before/after state diffs</li><li>Time travel debugging</li></ul><h4>Before devtools (manual)</h4><pre>set((s) =&gt; {<br>  console.log(&quot;toggling filter, before:&quot;, s);<br>  return { showCompleted: !s.showCompleted };<br>});</pre><h4>After devtools</h4><pre>import { create } from &quot;zustand&quot;;<br>import { devtools } from &quot;zustand/middleware&quot;;<br><br>export const useFilterStore = create(<br>  devtools((set) =&gt; ({<br>    showCompleted: false,<br>    toggleCompleted: () =&gt;<br>      set((s) =&gt; ({ showCompleted: !s.showCompleted }), false, &quot;toggleCompleted&quot;),<br>  }), { name: &quot;FilterStore&quot; })<br>);</pre><h4>How to use it in code</h4><ol><li>Install the <strong>Redux DevTools</strong> extension in your browser.</li><li>Open your app, go to DevTools, select FilterStore.</li><li>Toggle a filter → you’ll see the action log:</li></ol><ul><li>Action: toggleCompleted</li><li>State before/after</li><li>Option to jump back in time</li></ul><h4>Where to use it</h4><ul><li>During <strong>development</strong> for complex flows (checkout, multi-step forms).</li><li>Disable in production if you want less noise (though it’s generally safe).</li></ul><h3>Middleware Ordering: Does It Matter?</h3><p>Yes! The order of wrapping changes what each middleware “sees.”</p><pre>create(<br>  devtools(<br>    persist(<br>      immer((set) =&gt; ({ /* state */ })),<br>      { name: &quot;store&quot; }<br>    )<br>  )<br>);</pre><ul><li>immer → makes updates easier.</li><li>persist → saves the final state to storage.</li><li>devtools → logs everything, including hydration and persisted actions.</li></ul><p>That’s the usual, safe order.</p><h3>Here’s a single, simple store that combines persist, immer, and devtools</h3><pre>// src/stores/demoStore.ts<br>import { create } from &quot;zustand&quot;;<br>import { devtools, persist, immer } from &quot;zustand/middleware&quot;;<br><br>interface DemoState {<br>  token: string | null;<br>  theme: &quot;light&quot; | &quot;dark&quot;;<br>  cart: { id: string; quantity: number }[];<br>  setToken: (t: string) =&gt; void;<br>  toggleTheme: () =&gt; void;<br>  addToCart: (id: string) =&gt; void;<br>  clearCart: () =&gt; void;<br>}<br>export const useDemoStore = create&lt;DemoState&gt;()(<br>  devtools(<br>    persist(<br>      immer((set) =&gt; ({<br>        token: null,<br>        theme: &quot;light&quot;,<br>        cart: [],<br>        setToken: (token) =&gt; set({ token }),<br>        toggleTheme: () =&gt;<br>          set((state) =&gt; {<br>            state.theme = state.theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;;<br>          }),<br>        addToCart: (id) =&gt;<br>          set((state) =&gt; {<br>            const item = state.cart.find((i) =&gt; i.id === id);<br>            if (item) item.quantity++;<br>            else state.cart.push({ id, quantity: 1 });<br>          }),<br>        clearCart: () =&gt;<br>          set((state) =&gt; {<br>            state.cart = [];<br>          }),<br>      })),<br>      { name: &quot;demo-store&quot; } // persisted key in localStorage<br>    ),<br>    { name: &quot;DemoStore&quot; } // devtools store name<br>  )<br>);</pre><h4>Usage in a React component:</h4><pre>import React from &quot;react&quot;;<br>import { useDemoStore } from &quot;@/stores/demoStore&quot;;<br><br>export default function Demo() {<br>  const token = useDemoStore((s) =&gt; s.token);<br>  const theme = useDemoStore((s) =&gt; s.theme);<br>  const cart = useDemoStore((s) =&gt; s.cart);<br>  const setToken = useDemoStore((s) =&gt; s.setToken);<br>  const toggleTheme = useDemoStore((s) =&gt; s.toggleTheme);<br>  const addToCart = useDemoStore((s) =&gt; s.addToCart);<br>  const clearCart = useDemoStore((s) =&gt; s.clearCart);<br>  return (<br>    &lt;div style={{ padding: 20 }}&gt;<br>      &lt;h2&gt;Demo Store&lt;/h2&gt;<br>      &lt;section&gt;<br>        &lt;h3&gt;Auth &amp; Theme&lt;/h3&gt;<br>        &lt;p&gt;Token: {token ?? &quot;none&quot;}&lt;/p&gt;<br>        &lt;button onClick={() =&gt; setToken(&quot;abc123&quot;)}&gt;Set Token&lt;/button&gt;<br>        &lt;p&gt;Theme: {theme}&lt;/p&gt;<br>        &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>      &lt;/section&gt;<br>      &lt;section&gt;<br>        &lt;h3&gt;Cart&lt;/h3&gt;<br>        &lt;button onClick={() =&gt; addToCart(&quot;item1&quot;)}&gt;Add Item 1&lt;/button&gt;<br>        &lt;button onClick={() =&gt; addToCart(&quot;item2&quot;)}&gt;Add Item 2&lt;/button&gt;<br>        &lt;button onClick={clearCart}&gt;Clear Cart&lt;/button&gt;<br>        &lt;ul&gt;<br>          {cart.map((i) =&gt; (<br>            &lt;li key={i.id}&gt;<br>              {i.id} - {i.quantity}<br>            &lt;/li&gt;<br>          ))}<br>        &lt;/ul&gt;<br>      &lt;/section&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>What this demo shows:</h4><ul><li><strong>Persist</strong>: token, theme, and cart survive page reloads.</li><li><strong>Immer: </strong>Cart updates are simple (push / quantity++) without messy spreads.</li><li><strong>Devtools: </strong>Every action (setToken, toggleTheme, addToCart, clearCart) is logged in Redux DevTools for easy debugging.</li></ul><p>This is a <strong>minimal but fully functional demo</strong> combining all three middlewares in one store.</p><h3>Final Thoughts</h3><p>Manually persisting state, writing verbose immutable updates, and debugging with logs might work for small toy apps. But in production, it quickly becomes unmaintainable.</p><p>Zustand’s middlewares <strong>persist</strong>, <strong>immer</strong>, and <strong>devtools</strong> let you:</p><ul><li><strong>Persist</strong> critical state with zero boilerplate.</li><li><strong>Simplify</strong> nested updates while keeping immutability.</li><li><strong>Debug</strong> confidently with time-travel and action logs.</li></ul><blockquote>Keep your stores small and focused, apply middleware where it makes sense, and your state layer stays clean, predictable, and easy to reason about.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab4493083ca1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zustand: Effortless State Management for React]]></title>
            <link>https://medium.com/@skyshots/zustand-effortless-state-management-for-react-ff33f86141f6?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff33f86141f6</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 06:46:42 GMT</pubDate>
            <atom:updated>2025-09-25T06:46:42.116Z</atom:updated>
            <content:encoded><![CDATA[<p>A tiny, fast, and scalable state management library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ubufKdqF100vsVyknEsSwA.png" /></figure><h3><strong>Introduction</strong></h3><p>State management is at the heart of every React application. Whether you’re tracking a simple counter or managing complex user sessions, you need a reliable way to store and update state across components.</p><p>Traditionally, developers have relied on the <strong>Context API</strong>, or heavyweight libraries like <strong>Redux</strong>. While powerful, these solutions can often feel <strong>boilerplate-heavy</strong> or <strong>overkill</strong> for small to medium-sized apps.</p><p>This is where Zustand comes in.</p><p>Zustand (German for “state”) is a <strong>tiny, fast, and scalable state management library</strong> built by the creators of Jotai and React Three Fiber. It provides:</p><ul><li>A <strong>minimal API</strong> with no boilerplate.</li><li><strong>Hooks-based stores</strong> (no need for Providers).</li><li><strong>Selective subscriptions</strong> to avoid unnecessary re-renders.</li><li>A <strong>tiny bundle size</strong> (~1kb gzipped).</li></ul><p>In this guide, we’ll cover:</p><ol><li>Installing Zustand.</li><li>Creating your first store.</li><li>Using the store inside components.</li><li>Why Zustand is different from Redux and Context API.</li></ol><h3><strong>1️⃣ Installing Zustand</strong></h3><p>To get started, install Zustand via npm or yarn:</p><pre>npm install zustand<br># or<br>yarn add zustand</pre><h3><strong>2️⃣ Creating a Zustand Store</strong></h3><p>At the core of React applications is state. State is simply data that can change over time and that determines what your UI looks like. For example:</p><ul><li>A counter value (count) that increases when you click a button.</li><li>A user’s logged-in status.</li><li>Items in a shopping cart.</li></ul><p>In React, local state is usually managed with useState or useReducer. But for global state, data shared across multiple components we need a store.</p><h4><strong>What is a Store?</strong></h4><p>A store is a centralized container that holds your state and provides methods to update it. Think of it as a <strong>single source of truth</strong> for part or all of your app’s data.</p><p>In Zustand, creating a store is done via the create function:</p><p>Let’s build a simple example: a <strong>bear counter</strong>.</p><pre>// store.ts<br>import { create } from &quot;zustand&quot;;<br><br>type BearState = {<br>  bears: number;           // The state variable<br>  increase: () =&gt; void;    // Function to update the state<br>}<br><br>const useBearStore = create&lt;BearState&gt;((set) =&gt; ({<br>  bears: 0,                 // Initial state<br>  increase: () =&gt; set((state) =&gt; ({ bears: state.bears + 1 })),<br>}));<br><br>export default useBearStore;</pre><h4><strong>Breaking Down the Store Creation</strong></h4><p><strong>💠 </strong>create&lt;BearState&gt;(…)</p><ul><li>create is a factory function provided by Zustand.</li><li>You pass it a <strong>store initializer</strong>, a function that returns your <strong>initial state</strong> and <strong>state-updating functions</strong>.</li><li>&lt;BearState&gt; is a TypeScript interface that defines the <strong>shape of your state</strong>. Using TypeScript ensures your state and functions are type-safe.</li></ul><p><strong>💠 State Variables (</strong>bears<strong>)</strong></p><ul><li>This is the <strong>actual piece of data</strong> that will be shared across components.</li><li>In our example, bears starts at 0.</li><li>You can add any type of state: numbers, strings, objects, arrays, or even nested objects.</li></ul><p><strong>💠 Updater Functions (increase)</strong></p><ul><li>Functions like increase allow you to <strong>mutate the state safely</strong>.</li><li>In Zustand, you <strong>don’t mutate state directly</strong>; instead, you call the set function.</li><li>The set function takes either:</li><li>A <strong>partial state object</strong> (simple assignment), or</li></ul><p>A <strong>function</strong> that receives the current state and returns a new state object.</p><p>Example:</p><pre>set((state) =&gt; ({ bears: state.bears + 1 }));</pre><p>Here:</p><ul><li>state is the current state of the store.</li><li>We return a <strong>new object</strong> with the updated bears value.</li><li>Zustand then merges it into the store and <strong>triggers any subscribed components to re-render</strong>.</li></ul><h4><strong>In simple:</strong></h4><ul><li>create is Zustand’s factory function.</li><li>set is used to <strong>update state</strong>.</li><li>useBearStore is a custom hook that components can call to read and update the store.</li></ul><h3><strong>3️⃣ Consuming the Store in a Component</strong></h3><p>Now let’s use this store inside a React component:</p><pre>// BearCounter.tsx<br>import useBearStore from &quot;./store&quot;;<br><br>function BearCounter() {<br>  const { bears, increase } = useBearStore();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{bears} bears around here...&lt;/h1&gt;<br>      &lt;button onClick={increase}&gt;Add one&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default BearCounter;</pre><p>This works just like useState, but the state is <strong>shared globally</strong>. Any component that calls useBearStore will be synced with the same state.</p><h4><strong>Selective Subscriptions</strong></h4><p>One of Zustand’s most powerful features is <strong>selective subscriptions</strong>. Instead of subscribing to the entire store, you can subscribe to only the piece of state you need.</p><pre>function BearCount() {<br>  const bears = useBearStore((state) =&gt; state.bears);<br>  return &lt;h1&gt;{bears} bears&lt;/h1&gt;;<br>}<br><br>function Controls() {<br>  const increase = useBearStore((state) =&gt; state.increase);<br>  return &lt;button onClick={increase}&gt;Add one&lt;/button&gt;;<br>}</pre><p>This ensures that when increase changes, only Controls re-renders and not BearCount. This is a <strong>big performance win</strong> compared to Context API or Redux.</p><h3><strong>4️⃣ Why Zustand Over Redux or Context?</strong></h3><ul><li><strong>No Providers:</strong> With Redux or Context, you typically wrap your app in a &lt;Provider&gt;. Zustand stores are <strong>hook-based</strong>, so you just import and use them.</li><li><strong>Less Boilerplate:</strong> No actions, reducers, or dispatch. Just define state and functions.</li><li><strong>Performance: </strong>Zustand uses <strong>shallow equality checks</strong> and selective subscriptions to avoid unnecessary re-renders.</li><li><strong>Small Size:</strong> Redux Toolkit is powerful but heavier. Zustand is ~1kb gzipped.</li></ul><h3><strong>Wrapping Up</strong></h3><p>You’ve now built your first store with Zustand and learned how to consume it in React components. Zustand makes global state feel as easy as local state with useState, but without the boilerplate of Redux or the pitfalls of Context API.</p><blockquote>In the next post, we’ll go deeper into <strong>Zustand middleware</strong> such as persist, immer, and devtools to see how we can add persistence, debugging, and immutability with just a few lines of code.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff33f86141f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Containerizing your React App with Docker]]></title>
            <link>https://medium.com/@skyshots/containerizing-your-react-app-with-docker-645cfa53e1cd?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/645cfa53e1cd</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-image]]></category>
            <category><![CDATA[docker-container]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 12:31:38 GMT</pubDate>
            <atom:updated>2025-06-23T12:32:55.172Z</atom:updated>
            <content:encoded><![CDATA[<p>From Zero to Production: Build &amp; Ship a Rock-Paper-Scissors Game in a Container</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ca-madq9ltsQ7iEkMGISw.png" /></figure><h3><strong>🔹 What We’ll Cover</strong></h3><ul><li>Create a simple Vite + React app (Rock-Paper-Scissors using emojis)</li><li>Build it locally for production</li><li>Use Docker to serve it with Nginx</li><li>Run it locally or on another system</li></ul><blockquote>This guide is a continuation of my previous blog on <a href="https://medium.com/@skyshots/docker-because-your-local-setup-is-not-the-final-boss-627aa617c9ed">Docker fundamentals</a>, where we covered the core concepts and essential commands — now we’ll apply those basics by containerizing a simple React app built with Vite.</blockquote><h3>🧩 <strong>Prerequisites</strong></h3><p>Make sure the following are installed:</p><ul><li><a href="https://nodejs.org/">Node.js</a>: For building React apps</li><li>npm: Dependency manager</li><li><a href="https://www.docker.com/">Docker</a>: For containerization</li></ul><p>Check versions:</p><pre>node -v<br>npm -v<br>docker -v</pre><h3>♻️ Step by Step Guide</h3><h4><strong>1: </strong>Create a Vite + React App</h4><p>Let’s use <strong>Vite</strong> to set up the project.</p><pre><br>npx create vite@latest rps-vite-app -- --template react<br>cd rps-vite-app<br>npm i</pre><h4><strong>2: Build the Rock-Paper-Scissors App</strong></h4><p>Edit src/App.js with this <strong>basic emoji version</strong>:</p><pre>import { useState } from &#39;react&#39;;<br><br>const choices = [&quot;✊&quot;, &quot;🤚&quot;, &quot;✌️&quot;];<br>const getResult = (user, computer) =&gt; {<br>  if (user === computer) return &quot;Draw&quot;;<br>  if (<br>    (user === &quot;✊&quot; &amp;&amp; computer === &quot;✌️&quot;) ||<br>    (user === &quot;🤚&quot; &amp;&amp; computer === &quot;✊&quot;) ||<br>    (user === &quot;✌️&quot; &amp;&amp; computer === &quot;🤚&quot;)<br>  ) {<br>    return &quot;You Win!&quot;;<br>  }<br>  return &quot;You Lose!&quot;;<br>};<br><br>function App() {<br>  const [userChoice, setUserChoice] = useState(null);<br>  const [computerChoice, setComputerChoice] = useState(null);<br>  const [result, setResult] = useState(&quot;&quot;);<br><br>  const play = (choice) =&gt; {<br>    const random = choices[Math.floor(Math.random() * choices.length)];<br>    setUserChoice(choice);<br>    setComputerChoice(random);<br>    setResult(getResult(choice, random));<br>  };<br><br>  return (<br>    &lt;div style={{ textAlign: &quot;center&quot;, marginTop: &quot;3rem&quot; }}&gt;<br>      &lt;h1&gt;Rock Paper Scissors ✊🤚✌️&lt;/h1&gt;<br>      &lt;div&gt;<br>        {choices.map((choice) =&gt; (<br>          &lt;button<br>            key={choice}<br>            onClick={() =&gt; play(choice)}<br>            style={{<br>              fontSize: &quot;2rem&quot;,<br>              margin: &quot;1rem&quot;,<br>              padding: &quot;1rem&quot;,<br>              cursor: &quot;pointer&quot;,<br>            }}<br>          &gt;<br>            {choice}<br>          &lt;/button&gt;<br>        ))}<br>      &lt;/div&gt;<br>      {userChoice &amp;&amp; (<br>        &lt;div&gt;<br>          &lt;p&gt;<br>            You: {userChoice} | Computer: {computerChoice}<br>          &lt;/p&gt;<br>          &lt;h2&gt;{result}&lt;/h2&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>This is a simple, functional version using emojis with zero dependencies.</p><h4>3: Build the App for Production</h4><p>This generates the production-ready files inside the dist folder:</p><pre>npm run build</pre><h4><strong>4: Create the Dockerfile</strong></h4><p>In the root directory (rps-vite-app/), create a file called Dockerfile:</p><blockquote>A <strong>Dockerfile</strong> is a plain text file that contains a list of <strong>instructions</strong> to tell Docker <strong>how to build an image</strong> — which is like a snapshot of your application and everything it needs to run.</blockquote><pre># Step 1: Use an official Nginx image as the base<br>FROM nginx:latest<br><br># Step 2: Copy the built React app from &quot;dist&quot; to the Nginx HTML directory<br>COPY dist /usr/share/nginx/html<br><br># Step 3: Expose port 80 to allow external access<br>EXPOSE 80<br><br># Step 4: Start Nginx when the container runs<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><h4><strong>Understanding the Dockerfile:</strong></h4><h4>🔹 FROM nginx:latest</h4><p><strong>What it does:</strong><br> This tells Docker to use the <strong>official Nginx image</strong> (latest version) from Docker Hub as the <strong>base image</strong>.</p><p><strong>Why it’s used:</strong><br> We don’t need Node.js or Vite anymore after building the app. We just need a <strong>fast, lightweight web server</strong> to serve the static files (HTML, CSS, JS).<br> <strong>Nginx</strong> is perfect for that — it&#39;s efficient, reliable, and widely used for serving frontend apps.</p><h4>🔹 COPY dist /usr/share/nginx/html</h4><p><strong>What it does:</strong><br> This line copies the contents of the dist/ folder (your built Vite app) from your local machine <strong>into the Nginx container</strong>.</p><ul><li>dist : your app’s production-ready files</li><li>/usr/share/nginx/html : Nginx’s default directory to serve static files</li></ul><p><strong>Why it’s used:</strong><br> Once Vite builds your app, everything you need to serve it is inside the dist folder. This command moves those static assets into the folder Nginx uses to serve content.</p><p>So when someone accesses the container via browser, Nginx serves your index.html from the dist/ folder.</p><h4>🔹 EXPOSE 80</h4><p><strong>What it does:</strong><br> This declares that the container will <strong>listen on port 80</strong>.</p><p><strong>Why it’s used:</strong><br> Nginx, by default, runs on port 80. This line doesn’t actually open the port itself (that’s done via the docker run -p command), but it <strong>documents the intention</strong> that port 80 is exposed.</p><blockquote><em>Note: You still need </em><em>docker run -p 3000:80 to map it to your host machine’s port (e.g., port 3000 in your browser).</em></blockquote><h4>🔹 CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</h4><p><strong>What it does:</strong><br> This is the default command that runs when the container starts.</p><ul><li>nginx : starts the Nginx server</li><li>-g daemon off; : tells Nginx to <strong>stay in the foreground</strong> (don&#39;t detach into the background)</li></ul><p><strong>Why it’s used:</strong><br> In Docker, if the main process exits, the container stops. Running nginx in the foreground keeps the container alive and serving your app.</p><blockquote>You’re taking your finished React app and placing it into a lightweight, ready-to-serve web environment using Nginx.<br> Docker then wraps everything, the app and the server into one portable unit.<br> This setup runs the same way on any system, no manual configuration needed.<br> It’s fast, clean, and perfect for consistent deployments anywhere.</blockquote><h4><strong>5: Add </strong><strong>.dockerignore</strong></h4><p>Create .dockerignore to speed up build time and reduce image size:</p><blockquote>.dockerignore is a special file used to <strong>tell Docker which files or folders to ignore</strong> when building your Docker image, similar to how .gitignore works for Git.</blockquote><pre>node_modules<br>dist<br>.vite<br>.git<br>Dockerfile<br>.dockerignore<br>README.md</pre><h4><strong>6: Build the Docker Image</strong></h4><p>From inside rps-vite-app/, run:</p><pre>docker build -t rps-vite-app .</pre><h4>7: Run the App in Docker</h4><pre>docker run -d -p 3000:80 rps-vite-app</pre><p>Open your browser and go to: <a href="http://localhost:3000/">http://localhost:3000</a></p><h4><strong>8: Move to Another System</strong></h4><p>You can either <strong>export/import</strong> the image or <strong>push to Docker Hub</strong>.</p><p><strong>Option A: Export and Import (Offline)</strong></p><p>On your machine:</p><pre>docker save -o rps-vite-app.tar rps-vite-app</pre><p>Transfer rps-vite-app.tar to another system (USB, email, etc.)</p><p>On target system:</p><pre>docker load -i rps-vite-app.tar<br>docker run -d -p 3000:80 rps-vite-app</pre><p><strong>Option B: Docker Hub (Online)</strong></p><ul><li>Push to Docker Hub:</li></ul><pre>docker tag rps-vite-app your-dockerhub-username/rps-vite-app<br>docker push your-dockerhub-username/rps-vite-app</pre><ul><li>Pull on another system:</li></ul><pre>docker pull your-dockerhub-username/rps-vite-app<br>docker run -d -p 3000:80 your-dockerhub-username/rps-vite-app</pre><h3>🧪 Troubleshooting</h3><ul><li><strong>Port already in use</strong>: Use -p 8080:80 or another port.</li><li><strong>Blank screen</strong>: Ensure npm run build was successful.</li><li><strong>App doesn’t respond</strong>: Check Docker logs with docker logs &lt;container_id&gt;.</li></ul><h3>📋 Summary</h3><ul><li>Create app: npm create vite@latest</li><li>Build app: npm run build</li><li>Create Docker image: docker build -t rps-vite-app .</li><li>Run container: docker run -d -p 3000:80 rps-vite-app</li><li>Save for export: docker save -o rps-vite-app.tar rps-vite-app</li><li>Load image elsewhere: docker load -i rps-vite-app.tar</li><li>Push to Docker Hub: docker push &lt;username&gt;/&lt;image&gt;</li></ul><h3>🎯 Conclusion</h3><p>You’ve now:</p><ul><li>Built a React app</li><li>Containerized it using Docker</li><li>Learned how to run it locally and on any system</li></ul><p>This approach is widely used in real-world frontend deployments to ensure <strong>consistency</strong>, <strong>portability</strong>, and <strong>reliability</strong>.</p><blockquote>With just a few simple steps, you’ve learned how to take a React app built with Vite, containerize it using Docker, and serve it anywhere with ease — paving the way for fast, consistent, and scalable front-end deployments.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=645cfa53e1cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Build Micro Frontends with React and Webpack From Scratch & With Total Control]]></title>
            <link>https://medium.com/@skyshots/build-micro-frontends-with-react-and-webpack-from-scratch-with-total-control-e03f321fabd6?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/e03f321fabd6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[micro-front-end]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Fri, 13 Jun 2025 11:01:03 GMT</pubDate>
            <atom:updated>2025-06-13T11:01:03.708Z</atom:updated>
            <content:encoded><![CDATA[<p>A beginner-friendly, step-by-step guide to building a Micro Frontend architecture using React and Webpack Module Federation <strong>without CRA or Vite</strong>. Everything is set up manually for better understanding and control.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*wnvH7MbAwzcxkfUfvibu4g.png" /></figure><h3>What Is Micro Frontend?</h3><p><strong>Micro Frontend (MFE)</strong> is an architectural style where a frontend app is broken down into smaller, independent apps that can be developed and deployed separately, but work together seamlessly.</p><p>With <strong>Webpack Module Federation</strong>, we can load remote components dynamically at runtime and share dependencies like React.</p><h3>⚙️ Tools and Prerequisites</h3><p>Make sure you have the following:</p><ul><li>Node.js (v16+ recommended)</li><li>npm (comes with Node.js)</li><li>Basic understanding of React and JavaScript</li><li>Terminal/CLI access</li></ul><p>We’ll manually create:</p><ul><li>webpack.config.js</li><li>.babelrc</li><li>React files (no CRA)</li></ul><h3>📂 Folder Structure</h3><p>Create a project folder:</p><pre>mkdir mfe-root &amp;&amp; cd mfe-root<br>mkdir host-app header-app</pre><p>We’ll have two apps:</p><pre>mfe-root/<br>├── host-app/       # Main container<br>└── header-app/     # Remote component</pre><h3>🔄 Step-by-Step Setup</h3><h4>1. Initialize Apps</h4><p>Do this inside <strong>both</strong> host-app and header-app folders:</p><pre>npm init -y</pre><p>Install the base dependencies:</p><pre>npm install react react-dom</pre><pre>npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin babel-loader @babel/core @babel/preset-env @babel/preset-react css-loader style-loader @module-federation/webpack-5</pre><h4>2. Configure Babel</h4><p>Create .babelrc in both apps:</p><pre>{<br>  &quot;presets&quot;: [&quot;@babel/preset-env&quot;, &quot;@babel/preset-react&quot;]<br>}</pre><h4>3. Setup Webpack</h4><p>Common Config Parts: In both apps, create a webpack.config.js:</p><pre>const path = require(&quot;path&quot;);<br>const HtmlWebpackPlugin = require(&quot;html-webpack-plugin&quot;);<br>const { ModuleFederationPlugin } = require(&quot;webpack&quot;).container;<br><br>module.exports = {<br>  entry: &quot;./src/index.js&quot;,<br>  mode: &quot;development&quot;,<br>  devServer: {<br>    static: path.join(__dirname, &quot;dist&quot;),<br>    port: 3000, // Change to 3001 for header-app<br>    open: true,<br>    hot: true,<br>  },<br>  output: {<br>    publicPath: &quot;auto&quot;,<br>    clean: true,<br>  },<br>  resolve: {<br>    extensions: [&quot;.js&quot;, &quot;.jsx&quot;],<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.jsx?$/,<br>        exclude: /node_modules/,<br>        use: &quot;babel-loader&quot;,<br>      },<br>      {<br>        test: /\.css$/,<br>        use: [&quot;style-loader&quot;, &quot;css-loader&quot;],<br>      },<br>    ],<br>  },<br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: &quot;./public/index.html&quot;,<br>    }),<br>  ],<br>};</pre><h4>Host Specific Changes</h4><p>In host-app/webpack.config.js, update port: 3000 and add the following in plugins after new HtmlWebpackPlugin() :</p><pre>new ModuleFederationPlugin({<br>  name: &quot;host_app&quot;,<br>  remotes: {<br>    header_app: &quot;header_app@http://localhost:3001/remoteEntry.js&quot;,<br>  },<br>  shared: { react: { singleton: true }, &quot;react-dom&quot;: { singleton: true } },<br>})</pre><h4>Remote Specific Changes</h4><p>In header-app/webpack.config.js, update port: 3001 and add the following like the above :</p><pre>new ModuleFederationPlugin({<br>  name: &quot;header_app&quot;,<br>  filename: &quot;remoteEntry.js&quot;,<br>  exposes: {<br>    &quot;./Header&quot;: &quot;./src/components/Header&quot;,<br>  },<br>  shared: { react: { singleton: true }, &quot;react-dom&quot;: { singleton: true } },<br>})</pre><h4>4. Create Basic React App Structure</h4><p>In each app, add:</p><pre>/public<br>  index.html<br>/src<br>  index.js<br>  bootstrap.jsx<br>  App.jsx</pre><p>public/index.html:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;MFE App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>src/index.js:</p><pre>import(&quot;./bootstrap.jsx&quot;);</pre><p>src/bootstrap.jsx</p><pre>import React from &quot;react&quot;;<br>import { createRoot } from &quot;react-dom/client&quot;;<br>import App from &quot;./App&quot;;<br><br>const root = createRoot(document.getElementById(&quot;root&quot;));<br>root.render(&lt;App /&gt;);</pre><p>src/App.jsx (Host)</p><pre>import React, { Suspense, lazy } from &quot;react&quot;;<br>const Header = lazy(() =&gt; import(&quot;header_app/Header&quot;));<br><br>export default function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Host App&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;p&gt;Loading...&lt;/p&gt;}&gt;<br>        &lt;Header /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>src/components/Header.jsx (Remote)</p><pre>import React from &quot;react&quot;;<br><br>const Header = () =&gt; &lt;header style={{ padding: 20, background: &#39;#eee&#39; }}&gt;Hello from Header App&lt;/header&gt;;<br>export default Header;</pre><p>Create src/App.jsx in header-app to render the component if you want to test the remote standalone.</p><h4>5. Add Scripts</h4><p>In package.json of each app:</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;webpack serve --config webpack.config.js --open&quot;,<br>  &quot;build&quot;: &quot;webpack --config webpack.config.js&quot;<br>}</pre><h4>6. Use bootstrap Pattern</h4><p>We use bootstrap.jsx to ensure all shared modules are initialized before loading the app. This prevents errors like:</p><ul><li>Invalid hook call</li><li>Shared module not available for eager consumption</li></ul><p>Always:</p><ul><li>Keep index.js minimal</li><li>Load all logic in bootstrap.jsx</li></ul><h3>⚙️ Run and Test</h3><p>In separate terminals:</p><pre>cd host-app<br>npm install<br>npm start   # Runs on http://localhost:3000</pre><pre>cd header-app<br>npm install<br>npm start   # Runs on http://localhost:3001</pre><p>Visit http://localhost:3000 — you should see the <strong>Header</strong> remote rendered inside the <strong>Host</strong>.</p><h3>❓ Troubleshooting Tips</h3><ul><li><strong>Shared module errors</strong>: Check singleton: true for React.</li><li><strong>Remote not loading</strong>: Verify remoteEntry.js URL &amp; port.</li><li><strong>Blank screen</strong>: Check browser console for network errors.</li><li><strong>Invalid hook call</strong>: Avoid loading multiple React versions.</li></ul><h3>✨ Next Steps</h3><ul><li>Add more remotes (e.g., nav-app, footer-app)</li><li>Add shared state with Zustand or Redux</li><li>Convert to production builds with caching &amp; code splitting</li><li>Explore runtime module federation &amp; dynamic remotes</li></ul><h3>🧾 Closing Notes</h3><p>If you need a detailed explanation on configuring webpack, refer to my previous blog on <a href="https://medium.com/@skyshots/what-they-dont-teach-you-about-react-building-everything-from-the-ground-up-b6ee2d4883b0">React from ground up</a>.</p><p>This guide gives you full control and visibility into each part of the architecture, making it easier to scale, debug, and customize. As you move forward:</p><ul><li>Keep components loosely coupled</li><li>Share only what’s needed between modules</li><li>Always test remotes independently before federation</li><li>Consider SSR and lazy loading for advanced performance</li></ul><p>While this guide focuses on React, the same Micro Frontend architecture using Webpack Module Federation can be applied to other frameworks like Angular, Vue, Svelte, and even plain JavaScript apps — making it a powerful solution for polyglot frontends.</p><p>Feel free to enhance this setup with TypeScript, linting, testing frameworks, and CI/CD pipelines. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e03f321fabd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What They Don’t Teach You About React: Building Everything From the Ground Up]]></title>
            <link>https://medium.com/@skyshots/what-they-dont-teach-you-about-react-building-everything-from-the-ground-up-b6ee2d4883b0?source=rss-41bbacaeeb75------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6ee2d4883b0</guid>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[ash]]></dc:creator>
            <pubDate>Thu, 12 Jun 2025 11:13:29 GMT</pubDate>
            <atom:updated>2025-06-12T15:31:31.016Z</atom:updated>
            <content:encoded><![CDATA[<p>When building React applications, many developers prefer using tools like <strong>Create React App (CRA)</strong> or <strong>Vite</strong> for convenience. However, understanding how to set up everything from scratch gives you <strong>complete control</strong> and a much deeper understanding of the build process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adu3bQk_FkQqoXN8YdROtA.png" /></figure><p>In this blog, we’ll create a modern React setup using:</p><ul><li><strong>Webpack</strong> for bundling</li><li><strong>Babel</strong> for transpiling</li><li><strong>Tailwind CSS</strong> for utility-first styling</li><li><strong>Material UI (MUI)</strong> for ready-made React components</li></ul><p>Whether you’re on <strong>Windows</strong>, <strong>Mac</strong>, or <strong>Linux</strong>, this guide walks you through every step.</p><h3>Prerequisites</h3><p>Before you begin, make sure you have the following installed:</p><ul><li><strong>Node.js</strong> and <strong>npm</strong>: Download from<a href="https://nodejs.org/"> nodejs.org</a></li><li><strong>A code editor</strong>, preferably<a href="https://code.visualstudio.com/"> Visual Studio Code</a></li></ul><h3>1️⃣ Initialize the Project</h3><p>Create a new directory and initialize it with npm:</p><pre>mkdir my-react-app<br>cd my-react-app<br>npm init -y</pre><p>This creates a package.json file to track dependencies.</p><h3>2️⃣ Install Required Packages</h3><h4>💠React Packages:</h4><pre>npm install react react-dom</pre><ul><li>react : Building components, hooks, JSX (Logic &amp; UI creation)</li><li>react-dom: Rendering to browser DOM (Making your app appear)</li></ul><p>These are the core libraries to build and render React components.</p><h4>💠<strong>Webpack Packages:</strong></h4><pre>npm install --save-dev webpack webpack-cli webpack-dev-server html-webpack-plugin</pre><ul><li>webpack : handles bundling.</li><li>webpack-cli : the command line interface.</li><li>webpack-dev-server : spins up a local dev server.</li><li>html-webpack-plugin : injects the bundle into your HTML.</li></ul><p>The — save-dev flag tells npm to install a package as a <strong>development dependency</strong></p><h4>💠<strong>Babel Packages:</strong></h4><pre>npm install --save-dev @babel/core @babel/preset-env @babel/preset-react babel-loader</pre><ul><li>@babel/core: Core engine that does the transforming</li><li>@babel/preset-env: Transforms modern JS (ES6+) to older JS</li><li>@babel/preset-react: Transforms JSX into React.createElement()</li><li>babel-loader: Lets Webpack use Babel to process JS/JSX files</li></ul><p>In short Babel helps convert modern JavaScript (and JSX) into code browsers understand.</p><h4>💠<strong>Loaders for CSS and PostCSS:</strong></h4><pre>npm install --save-dev style-loader css-loader postcss postcss-loader autoprefixer</pre><ul><li>style-loader and css-loader load CSS into your project.</li><li>postcss, postcss-loader, and autoprefixer optimize and prefix your CSS.</li></ul><h4>💠<strong>Tailwind CSS:</strong></h4><pre>npm install --save-dev tailwindcss</pre><p>If you’re on <strong>Windows</strong> and face issues with .cmd files, just download the full Tailwind release or clone from their<a href="https://github.com/tailwindlabs/tailwindcss"> GitHub repo</a> and extract it into node_modules/tailwindcss.</p><h4>💠Material UI:</h4><pre>npm install @mui/material @emotion/react @emotion/styled</pre><p>Material UI depends on Emotion for styling, so we install those as well.</p><h3>3️⃣ Babel Configuration</h3><p>Create a .babelrc file in the root of your project:</p><pre>{<br>  &quot;presets&quot;: [&quot;@babel/preset-env&quot;, &quot;@babel/preset-react&quot;]<br>}</pre><p>This tells Babel to transform modern JS and JSX.</p><h3>4️⃣ Webpack Configuration</h3><p>Create webpack.config.js in your project root:</p><h4>💠 Importing Required Modules:</h4><pre>const path = require(&#39;path&#39;);<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);</pre><ul><li>path: A Node.js module to handle file and folder paths. We use this to avoid hardcoding platform-specific paths.</li><li>HtmlWebpackPlugin: A Webpack plugin that <strong>automatically creates an HTML file</strong> with your JavaScript bundle injected into it. This means you don’t have to manually add a &lt;script&gt; tag.</li></ul><h4>💠 Entry Point:</h4><pre>entry: &#39;./src/index.jsx&#39;,</pre><ul><li>This is the <strong>main file</strong> where Webpack starts building the dependency graph.</li><li>Here, index.jsx is your main React file that renders the app (usually imports App.jsx).</li></ul><h4>💠 Output Configuration:</h4><pre>output: {<br>  filename: &#39;bundle.js&#39;,<br>  path: path.resolve(__dirname, &#39;dist&#39;),<br>  clean: true,<br>},</pre><ul><li>filename: What the output bundle will be called.</li><li>path: Where to put the bundled files. path.resolve(__dirname, &#39;dist&#39;) creates an absolute path to a folder named dist.</li><li>clean: true: Deletes old files in dist before building — keeps things tidy.</li></ul><h4>💠 Resolve Extensions:</h4><pre>resolve: {<br>  extensions: [&#39;.js&#39;, &#39;.jsx&#39;],<br>},</pre><ul><li>This tells Webpack which file extensions to automatically resolve.</li><li>So, when you write import App from &#39;./App&#39;, Webpack looks for App.js or App.jsx.</li></ul><h4>💠 Module Rules (Loaders):</h4><pre>module: {<br>  rules: [<br>    {<br>      test: /\.(js|jsx)$/,<br>      exclude: /node_modules/,<br>      use: &#39;babel-loader&#39;,<br>    },<br>    {<br>      test: /\.css$/i,<br>      use: [&#39;style-loader&#39;, &#39;css-loader&#39;, &#39;postcss-loader&#39;],<br>    },<br>  ],<br>},</pre><h4>🔸 First Rule — JavaScript and JSX files</h4><pre>{<br>  test: /\.(js|jsx)$/,<br>  exclude: /node_modules/,<br>  use: &#39;babel-loader&#39;,<br>}</pre><ul><li>test: A regex that matches .js and .jsx files.</li><li>exclude: Tells Webpack to ignore node_modules (already pre-compiled).</li><li>use: Uses babel-loader to transpile JSX + modern JS into browser-compatible JavaScript.</li></ul><h4>🔸 Second Rule — CSS and Tailwind</h4><pre>{<br>  test: /\.css$/i,<br>  use: [&#39;style-loader&#39;, &#39;css-loader&#39;, &#39;postcss-loader&#39;],<br>}</pre><ul><li>test: Matches .css files.</li><li>use (executed from <strong>right to left</strong>):</li><li>postcss-loader: Processes Tailwind and autoprefixer.</li><li>css-loader: Resolves @import and url() in CSS.</li><li>style-loader: Injects the CSS into the DOM via &lt;style&gt; tags.</li></ul><h4>💠 Plugins:</h4><pre>plugins: [<br>  new HtmlWebpackPlugin({<br>    template: &#39;./public/index.html&#39;,<br>  }),<br>],</pre><p>HtmlWebpackPlugin:</p><ul><li>Takes your public/index.html as a base template.</li><li>Automatically adds a &lt;script src=&quot;bundle.js&quot;&gt; pointing to your output.</li><li>Result is written to dist/index.html.</li></ul><h4>💠 Dev Server:</h4><pre>devServer: {<br>  static: &#39;./dist&#39;,<br>  port: 3000,<br>  open: true,<br>},</pre><ul><li>static: Tells the dev server to serve files from ./dist.</li><li>port: The app will run on <a href="http://localhost:3000.">http://localhost:3000.</a></li><li>open: Opens your default browser automatically when the dev server starts.</li></ul><h4>💠 Mode:</h4><pre>mode: &#39;development&#39;,</pre><ul><li>development: Enables faster builds, source maps, and disables minification.</li><li>You can change it to &#39;production&#39; for optimized builds.</li></ul><h4>Summary:</h4><ul><li>entry: Entry point to your app (index.jsx)</li><li>output: Output settings for bundled file</li><li>resolve: File extensions to auto-resolve</li><li>module.rules: Loaders that process files (JSX, CSS, etc.)</li><li>plugins: Add extra behavior (e.g. HTML injection)</li><li>devServer: Configuration for local development server</li><li>mode: Development vs Production mode</li></ul><h4>Your final webpack.config.js should look like the following:</h4><pre>const path = require(&#39;path&#39;);<br>const HtmlWebpackPlugin = require(&#39;html-webpack-plugin&#39;);<br><br>module.exports = {<br>  entry: &#39;./src/index.jsx&#39;,<br>  output: {<br>    filename: &#39;bundle.js&#39;,<br>    path: path.resolve(__dirname, &#39;dist&#39;),<br>    clean: true,<br>  },<br>  resolve: {<br>    extensions: [&#39;.js&#39;, &#39;.jsx&#39;],<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.(js|jsx)$/,<br>        exclude: /node_modules/,<br>        use: &#39;babel-loader&#39;,<br>      },<br>      {<br>        test: /\.css$/i,<br>        use: [&#39;style-loader&#39;, &#39;css-loader&#39;, &#39;postcss-loader&#39;],<br>      },<br>    ],<br>  },<br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: &#39;./public/index.html&#39;,<br>    }),<br>  ],<br>  devServer: {<br>    static: &#39;./dist&#39;,<br>    port: 3000,<br>    open: true,<br>  },<br>  mode: &#39;development&#39;,<br>};</pre><p>This tells Webpack how to process files and serve your app locally on port 3000.</p><h3>5️⃣ Tailwind and PostCSS Configuration</h3><p>Create tailwind.config.js manually:</p><pre>module.exports = {<br>  content: [&#39;./src/**/*.{js,jsx}&#39;, &#39;./public/index.html&#39;],<br>  theme: {<br>    extend: {},<br>  },<br>  plugins: [],<br>};</pre><p>Or if the CLI works for you:</p><pre>npx tailwindcss init</pre><p>Create postcss.config.js:</p><pre>module.exports = {<br>  plugins: [<br>    require(&#39;@tailwindcss/postcss&#39;),<br>    require(&#39;autoprefixer&#39;),<br>  ],<br>};</pre><h3>6️⃣ Create Project Structure</h3><p>Create your folders and files:</p><pre>mkdir src public<br>touch src/index.jsx src/App.jsx src/index.css public/index.html</pre><h4>🔸<strong>public/index.html</strong></h4><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;UTF-8&quot; /&gt;<br>    &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot; /&gt;<br>    &lt;title&gt;React App&lt;/title&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><h4>🔸<strong>src/index.css</strong></h4><pre>@tailwind base;<br>@tailwind components;<br>@tailwind utilities;</pre><h4>🔸<strong>src/index.jsx</strong></h4><pre>import React from &#39;react&#39;;<br>import { createRoot } from &#39;react-dom/client&#39;;<br>import App from &#39;./App&#39;;<br>import &#39;./index.css&#39;;<br><br>const root = createRoot(document.getElementById(&#39;root&#39;));<br>root.render(&lt;App /&gt;);</pre><h4>🔸<strong>src/App.jsx</strong></h4><pre>import React from &#39;react&#39;;<br>import Button from &#39;@mui/material/Button&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;div className=&quot;h-screen flex items-center justify-center bg-gradient-to-r from-green-400 to-blue-500&quot;&gt;<br>      &lt;div className=&quot;text-center&quot;&gt;<br>        &lt;h1 className=&quot;text-4xl font-bold text-white mb-4&quot;&gt;<br>          Hello, React + Tailwind + MUI!<br>        &lt;/h1&gt;<br>        &lt;Button variant=&quot;contained&quot; color=&quot;primary&quot;&gt;<br>          MUI Button<br>        &lt;/Button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>This renders a beautiful center-aligned screen with Tailwind’s gradient background and a Material UI button.</p><h4>Your Final Project Structure should look similar to the following:</h4><pre>my-react-app/<br>├── 📁 node_modules/<br>├── 📁 public/<br>│   └── index.html<br>├── 📁 src/<br>│   ├── index.jsx<br>│   ├── App.jsx<br>│   └── index.css<br>├── .babelrc<br>├── tailwind.config.js<br>├── postcss.config.js<br>├── webpack.config.js<br>├── package.json<br>└── package-lock.json</pre><h3><strong>7️⃣ Add Scripts to package.json</strong></h3><p>Inside the scripts section of your package.json, add:</p><pre>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;webpack serve --mode development&quot;,<br>  &quot;build&quot;: &quot;webpack --mode production&quot;<br>}</pre><p>Now you can start the dev server with:</p><pre>npm start</pre><h3>Final Tips</h3><ul><li><strong>If Tailwind’s CLI fails on Windows</strong>, manually create tailwind.config.js and copy the config shown above.</li><li><strong>Don’t forget to include </strong><strong>.css files in your JS</strong> — Tailwind styles won’t apply otherwise.</li><li><strong>MUI + Tailwind combo</strong> is powerful: use MUI for complex components and Tailwind for layout and spacing.</li></ul><h3>You’re All Set!</h3><p>You now have a fully working, modern React setup — no boilerplates, no shortcuts — <strong>everything is built from scratch</strong>. This gives you a clear understanding of how Webpack, Babel, Tailwind CSS, and Material UI integrate together.</p><p>Feel free to experiment, build components, and tweak your configuration. You now have <strong>full control</strong> over your React development environment.</p><p>Happy Coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6ee2d4883b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>