<?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 Boopy on Medium]]></title>
        <description><![CDATA[Stories by Boopy on Medium]]></description>
        <link>https://medium.com/@aalbertini95_90842?source=rss-a4fdee6aeb66------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kGyVia1esJm5TXl6FgT5UQ.jpeg</url>
            <title>Stories by Boopy on Medium</title>
            <link>https://medium.com/@aalbertini95_90842?source=rss-a4fdee6aeb66------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:23:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aalbertini95_90842/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[SSG vs ISR vs SSR vs CSR in Next.js 16: When to Use Each (and Why It Matters)]]></title>
            <link>https://blog.stackademic.com/rendering-methods-in-next-js-16-ssg-vs-isr-vs-ssr-vs-csr-explained-1c6c36f7c235?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c6c36f7c235</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 16:16:04 GMT</pubDate>
            <atom:updated>2026-05-19T05:16:18.950Z</atom:updated>
            <content:encoded><![CDATA[<p>When building a modern web application with Next.js, choosing the right rendering strategy can have a major impact on performance and user experience. In this article, we explore four complementary approaches: <strong>SSG (Static Site Generation)</strong>, <strong>ISR (Incremental Static Regeneration)</strong>, <strong>SSR (Server-Side Rendering)</strong>, and <strong>CSR (Client-Side Rendering)</strong>, including how they work, when to use them, and practical implementation examples.</p><h4>See Demos in Action</h4><p>Want to explore similar examples? Check out this <a href="https://github.com/kiki-le-singe/nextjs-perf-showcase">GitHub repo — nextjs-perf-showcase</a> with demo projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ynyjqUNYCsdAR3lFi3EjQ.gif" /></figure><h4>Versions Tested</h4><ul><li><strong>Next.js</strong>: <em>16.x (App Router + Cache Components (declarative </em>‘use cache’<em>))</em></li><li><strong>React</strong>: <em>19.x</em></li><li><strong>TanStack Query</strong>: <em>@tanstack/react-query v5.x</em></li></ul><h4>The 4 Rendering Methods at a Glance</h4><p>Before diving into SSG, ISR, SSR, and CSR, here’s a quick overview of the four main rendering methods available in Next.js:</p><pre>| <strong>Method</strong>  | <strong>When HTML is generated</strong>                            | <strong>Typical use case</strong>                                              |<br>| ------- | ------------------------------------------------- | ------------------------------------------------------------- |<br>| <strong><em>SSG</em></strong>     | Once at build time                                | Rarely changing content (blogs, documentation, legal pages)   |<br>| <strong><em>ISR</em></strong>     | At build time + automatic regeneration            | Content that changes regularly (e-commerce, news)             |<br>| <strong><em>SSR</em></strong>     | On every request                                  | Personalized or real-time content (dashboards, user profiles) |<br>| <strong><em>CSR</em></strong>     | Server-rendered shell, data fetched on the client | Rich interactions (dashboards, filters, advanced forms)       |</pre><p>In this article, we break down <strong>SSG</strong>, <strong>ISR</strong>, <strong>SSR</strong>, and <strong>CSR</strong>. In practice, these strategies are often combined within the same app depending on each section’s needs.</p><h4><strong>Build Output Summary</strong></h4><p>Here is an example of build output after running <strong>npm run build</strong>, Next.js displays a summary of all routes and their rendering strategies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xn2mUFJVdZwenlRtG1MEvA.png" /></figure><ul><li><strong>SSG</strong> (<strong>`○`</strong> without Revalidate/Expire): <strong>/rendering-methods/ssg</strong> — fully static, no revalidation</li><li><strong>ISR</strong> (<strong>`○`</strong> with Revalidate/Expire): <strong>/rendering-methods/isr</strong> <em>(2m/1h)</em>, <strong>/rendering-methods/isr-page</strong> <em>(15m/1y)</em> — static with automatic revalidation</li><li><strong>SSR with Partial Prerender</strong> (<strong>`◐`</strong>): <strong>/rendering-methods/ssr</strong> — static shell with dynamic server-streamed content</li><li><strong>CSR</strong> (<strong>`○`</strong>): <strong>/rendering-methods/csr</strong> — static shell, data fetched client-side</li></ul><h4>Global Prerequisite</h4><p>For ISR sections based on Cache Components, enable this option once:</p><pre>// next.config.ts<br>import type { NextConfig } from &#39;next&#39;<br><br>const nextConfig: NextConfig = {<br>  cacheComponents: true,<br>}<br><br>export default nextConfig</pre><p>Without this option, the <strong>’use cache’</strong> directive will not work.</p><h3>SSG — Static Site Generation</h3><blockquote><strong>Terminology</strong><em>: in Next.js, </em><strong>SSG</strong><em> refers to fully static pages with no revalidation. As soon as revalidation is active (default, max, or custom), it becomes </em><strong>ISR</strong><em>.</em></blockquote><h4><strong>The Principle</strong></h4><p>SSG (Static Site Generation) generates HTML <strong>at build time</strong>, then serves that HTML as-is on every request.</p><p><strong>How it works:</strong></p><ol><li>During build <strong>(npm run build)</strong>, Next.js generates full HTML for each page</li><li>Generated HTML is stored on disk in the build directory <strong>.next</strong> (by default)</li><li>On each request, this pre-generated HTML is served instantly</li><li>Content changes only after the next build/deploy</li></ol><h4><strong>SSG Example</strong></h4><pre>// SSG: no &#39;use cache&#39;, no runtime fetch, no dynamic signal.<br>export default function LegalPage() {<br>  return (<br>    &lt;main&gt;<br>      &lt;h1&gt;Legal Notice&lt;/h1&gt;<br>      &lt;p&gt;Static content generated at build time.&lt;/p&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><h4><strong>SSG with Dynamic Routes (generateStaticParams)</strong></h4><p>To pre-generate dynamic pages at build time (e.g. <strong>/blog/[slug]</strong>), use <strong>generateStaticParams</strong>:</p><pre>// Return a list of `params` to populate the [slug] dynamic segment<br>export async function generateStaticParams() {<br>  const posts = await getAllPostSlugs()<br><br>  return posts.map(post =&gt; ({<br>    slug: post.slug,<br>  }))<br>}<br><br>// Multiple versions of this page will be statically generated<br>// using the `params` returned by `generateStaticParams`<br>export default async function Page({ params }: { params: Promise&lt;{ slug: string }&gt; }) {<br>  const { slug } = await params<br>  return &lt;article&gt;...&lt;/article&gt;<br>}</pre><p>Next.js will generate one static HTML page per returned <strong>slug</strong>. Without <strong>’use cache’</strong> and without dynamic signals, each page stays <strong>`○`</strong> (static) in the build output.</p><h4><strong>Where Is SSG HTML Stored?</strong></h4><p>After <strong>npm run build</strong>, static output can be observed in <strong>.next/server/app/</strong>.</p><blockquote><em>See the </em><strong><em>Comparison Table</em></strong><em> and the </em><strong><em>How To Choose?</em></strong><em> for when to use SSG vs ISR/SSR/CSR.</em></blockquote><h3><strong>ISR — Incremental Static Regeneration</strong></h3><h4><strong>The Principle</strong></h4><p>ISR combines the best of both worlds: <strong>the speed of static sites</strong> with <strong>the freshness of dynamic content</strong>. Here’s how it works:</p><ol><li>The page is generated statically (like SSG)</li><li>It is served instantly from cache</li><li>After a configured delay, the next request triggers background regeneration</li><li>Following visitors receive the updated version</li></ol><h4><strong>Prerequisite: Configuration</strong></h4><p>See <strong>Global Prerequisite</strong> above.</p><h4><strong>Cache Components (Recommended Modern Approach)</strong></h4><p>Best practice is to use <strong>component-level caching</strong> rather than page-level caching. This provides better flexibility and performance. Here’s a concrete example based on a real implementation:</p><pre>import { Suspense } from &#39;react&#39;<br>import { cacheLife, cacheTag } from &#39;next/cache&#39;<br><br>// Page - Layout only (no cache here)<br>export default function ProductsPage() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Product Catalog&lt;/h1&gt;<br>      {/* Suspense for progressive loading */}<br>      &lt;Suspense fallback={&lt;ProductsSkeleton /&gt;}&gt;<br>        &lt;ProductsSection /&gt; {/* Component with ISR cache */}<br>      &lt;/Suspense&gt;<br>      &lt;Footer /&gt; {/* Static content */}<br>    &lt;/div&gt;<br>  )<br>}<br><br>// Component with ISR cache - This is where the magic happens<br>async function ProductsSection() {<br>  &#39;use cache&#39; // Component-level cache (modern)<br><br>  cacheLife({<br>    stale: 60, // Content becomes &quot;stale&quot; after 60 seconds<br>    revalidate: 120, // Background regeneration after 2 minutes<br>    expire: 3600, // Full expiration after 1 hour<br>  })<br><br>  cacheTag(&#39;products&#39;) // Tag for manual revalidation<br><br>  const productsData = await fetchProductsData()<br>  const dataVersion = productsData[0]?.lastUpdated || new Date().toISOString()<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;cache-info&quot;&gt;<br>        &lt;p&gt;Last updated: {new Date(dataVersion).toLocaleTimeString()}&lt;/p&gt;<br>        &lt;RevalidateButton /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div className=&quot;grid&quot;&gt;<br>        {productsData.map(product =&gt; (<br>          &lt;ProductCard key={product.id} product={product} /&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>// Skeleton displayed while loading<br>function ProductsSkeleton() {<br>  return (<br>    &lt;div className=&quot;animate-pulse&quot;&gt;<br>      &lt;div className=&quot;h-8 bg-gray-200 rounded w-48 mb-4&quot;&gt;&lt;/div&gt;<br>      &lt;div className=&quot;grid gap-6&quot;&gt;<br>        {[...Array(6)].map((_, i) =&gt; (<br>          &lt;div key={i} className=&quot;h-64 bg-gray-200 rounded&quot;&gt;&lt;/div&gt;<br>        ))}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><blockquote><em>For very simple pages with one data source, you can still use </em><strong><em>’use cache’</em></strong><em> at page level. For complex applications, component-level caching is recommended.</em> <strong>`<em>use cache’</em></strong><em> can also be placed at function level (not only in a component or page) to cache a fetch/calculation result independently.</em></blockquote><h4><strong>Understanding cacheLife: The 3 Periods</strong></h4><p><strong>cacheLife</strong> config defines how Next.js manages cache with 3 parameters:</p><pre>cacheLife({<br>  stale: 60, // After 60s, content becomes &quot;stale&quot; (but still served)<br>  revalidate: 120, // After 120s, regeneration is triggered by the next visitor<br>  expire: 3600, // After 1h, cache is fully removed<br>})</pre><p><strong>Quick definitions</strong></p><ul><li><strong>stale</strong> → <strong>Client (router) cache</strong> duration. During this period, the browser serves cache without contacting the server. Note: in PPR (Partial Prerendering), cache entries with <strong>stale &lt; 30s</strong> are treated as <strong>dynamic holes</strong> — excluded from the static prefetch shell and filled dynamically at navigation time. This is a classification rule, not a value clamp: your configured value is preserved, but the entry won’t participate in the static PPR shell.</li><li><strong>expire</strong> → Maximum duration before full server-cache removal. After this delay, the next request recomputes content <strong>synchronously</strong> (visitor waits).</li></ul><blockquote><strong>Two cache layers</strong><em>: stale controls </em><strong>client-side</strong><em> router cache, revalidate controls </em><strong>server-side</strong><em> cache. They are independent mechanisms that complement each other.</em></blockquote><p><strong>Scenario</strong>: First visit at <strong>12:00:00</strong>.</p><p><strong>#️⃣ Phase 1: Active client cache (0 to 60 seconds — <em>stale</em>)</strong></p><ul><li><strong>Duration</strong>: 12:00:00 → 12:01:00</li><li><strong>Layer</strong>: <strong>Client</strong> cache (router cache)</li><li><strong>Behavior</strong>:</li></ul><p>— ✅ Client-side navigations serve cache instantly, <strong>without contacting the server</strong></p><p>— ❌ No network request to server</p><ul><li><strong>Performance</strong>: ⚡ Ultra-fast (no network round-trip)</li></ul><p><strong>#️⃣ Phase 2: Client cache expired, server cache active (60 to 120 seconds)</strong></p><ul><li><strong>Duration</strong>: 12:01:00 → 12:02:00</li><li><strong>Layer</strong>: <strong>Server</strong> cache still valid</li><li><strong>Behavior</strong>:</li></ul><p>— 📡 Browser contacts server (client cache expired)</p><p>— ✅ Server serves Version A from cache (still in `revalidate` window)</p><p>— ❌ No background regeneration</p><ul><li><strong>Performance</strong>: ⚡ Fast (server request, but server-side cache hit)</li></ul><p><strong>#️⃣ Phase 3: REVALIDATE (after 120 seconds)</strong></p><ul><li><strong>Time</strong>: Starting at 12:02:00</li><li><strong>First visitor at 12:02:05</strong>:</li></ul><p>— 👤 Receives Version A immediately (old data from server cache)</p><p>— 🔄 Triggers background fetch (regeneration)</p><p>— ⏳ Regeneration takes a few seconds</p><ul><li><strong>Second visitor at 12:02:10</strong>:</li></ul><p>— ✅ Receives Version B if regeneration is done, otherwise still Version A</p><p>— ♻️ Cycle restarts</p><ul><li><strong>Pattern</strong>: “Stale-while-revalidate” — no one waits!</li></ul><p><strong>#️⃣ Phase 4: EXPIRE (after 3600 seconds / 1 hour)</strong></p><ul><li><strong>Time</strong>: After 13:00:00 (1 hour since cache creation)</li><li><strong>Behavior</strong>: Cache is <strong>fully removed</strong> (not a return to FRESH!)</li><li><strong>Why?</strong></li></ul><p>— 🗑️ Clean up memory/disk from very old cache entries</p><p>— 🛡️ Avoid serving extremely stale data</p><p>— 💾 Free resources</p><ul><li><strong>Scenario 1</strong>: If visitors came regularly (~every 2 min), cache has already been regenerated multiple times → <strong>expire</strong> mostly removes older versions</li><li><strong>Scenario 2</strong>: If <strong>no visitor</strong> after 120s → cache remains stale until 3600s, then is removed. Next visitor waits for a <strong>synchronous</strong> regeneration (like first-ever request)</li><li><strong>Important</strong>: <strong><em>expire</em></strong> is NOT automatic regeneration, it is <strong>cache removal</strong></li></ul><h4><strong>Built-in cacheLife Profiles</strong></h4><p>Next.js provides 7 predefined profiles. In the <strong>’use cache’</strong> context, without an explicit <strong>cacheLife</strong> call, the <strong>default</strong> profile is applied.</p><pre>| <strong>Profile</strong> | <strong>Use case</strong>                   | <strong>stale</strong>      | <strong>revalidate</strong>   | <strong>expire</strong>    |<br>| ------- | -------------------------- | ---------- | ------------ | --------- |<br>| <strong>default</strong> | Standard content           | 5 minutes  | 15 minutes   | ∞ (never) |<br>| <strong>seconds</strong> | Near real-time data        | 30 seconds | 1 second     | 1 minute  |<br>| <strong>minutes</strong> | Frequently updated content | 5 minutes  | 1 minute     | 1 hour    |<br>| <strong>hours</strong>   | Updated several times/day  | 5 minutes  | 1 hour       | 1 day     |<br>| <strong>days</strong>    | Daily updates              | 5 minutes  | 1 day        | 1 week    |<br>| <strong>weeks</strong>   | Weekly updates             | 5 minutes  | 1 week       | 30 days   |<br>| <strong>max</strong>     | Rarely changing content    | 5 minutes  | 30 days      | 1 year    |</pre><h4><strong>Page Cache vs Component Cache</strong></h4><p>The example above uses <strong>component-level</strong> cache (recommended). For simple pages with a single data source, you can also use <strong>’use cache’</strong> at <strong>page level</strong>:</p><pre>export default async function BlogPostPage() {<br>  &#39;use cache&#39; // ← Entire page is cached as one unit<br>  cacheLife(&#39;days&#39;)<br><br>  const post = await fetchBlogPost()<br><br>  return (<br>    &lt;div&gt;<br>      &lt;Header title={post.title} /&gt;<br>      &lt;ArticleContent content={post.content} /&gt;<br>      &lt;Footer /&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p><strong>How to choose?</strong></p><pre>| <strong>Criterion</strong>           | <strong>Page Cache</strong>                  | <strong>Component Cache</strong>                   |<br>| ------------------- | --------------------------- | --------------------------------- |<br>| Data sources        | One                         | Multiple with different freshness |<br>| Progressive loading | No                          | Yes (Suspense + skeletons)        |<br>| Complexity          | Simple                      | More initial code                 |<br>| Use case            | Blogs, simple product pages | E-commerce, complex applications  |</pre><h4><strong>Where Is ISR Cache Stored?</strong></h4><p>After <strong>npm run build</strong>, ISR output can be observed in <strong>.next/server/app/</strong>:</p><ul><li><strong>.next/server/app/rendering-methods/isr.html</strong> — Cached HTML</li><li><strong>.next/server/app/rendering-methods/isr.meta</strong> — Cache metadata (tags, stale time, headers)</li><li><strong>.next/server/app/rendering-methods/isr.segments/</strong> — RSC payload for client navigation</li></ul><h4><strong>On-Demand Revalidation</strong></h4><p>A powerful ISR feature is the ability to <strong>force a manual cache update</strong>. Here’s how to implement it:</p><pre>// Server action for manual revalidation<br>&#39;use server&#39;<br>import { revalidateTag } from &#39;next/cache&#39;<br><br>export async function revalidateProducts() {<br>  try {<br>    revalidateTag(&#39;products&#39;, &#39;max&#39;) // Recommended in Next.js 16.x (SWR)<br>    return { success: true, timestamp: new Date().toISOString() }<br>  } catch (error) {<br>    return { success: false, error: error instanceof Error ? error.message : String(error) }<br>  }<br>}</pre><p>In Next.js <strong>16.x</strong>, prefer <strong>revalidateTag(tag, ‘max’)</strong>.</p><p>The <strong>revalidateTag(tag)</strong> form (single arg) is legacy and deprecated.</p><p>And on the client, a button to trigger revalidation:</p><pre>&#39;use client&#39;<br>import { useTransition } from &#39;react&#39;<br><br>export function RevalidateButton() {<br>  const [isPending, startTransition] = useTransition()<br><br>  const handleRevalidate = () =&gt; {<br>    startTransition(async () =&gt; {<br>      await revalidateProducts()<br>      // Content will be updated automatically<br>    })<br>  }<br><br>  return (<br>    &lt;button onClick={handleRevalidate} disabled={isPending}&gt;<br>      {isPending ? &#39;Updating...&#39; : &#39;Revalidate Now&#39;}<br>    &lt;/button&gt;<br>  )<br>}</pre><h4><strong>updateTag and refresh() (immediate mutations)</strong></h4><p>For a mutation where the user must immediately see their own write (read-your-writes), use <strong>updateTag</strong> in a Server Action. If you need to force route client-cache refresh, use <strong>refresh()</strong>:</p><pre>&#39;use server&#39;<br>import { updateTag, refresh } from &#39;next/cache&#39;<br><br>export async function updateProductAction(input: UpdateProductInput) {<br>  await updateProductInDb(input)<br><br>  // Immediately expire the tag for future server reads.<br>  updateTag(&#39;products&#39;)<br><br>  // Refresh route client cache after the action.<br>  refresh()<br>}</pre><p><strong>revalidateTag(…, ‘max’)</strong> = SWR strategy (stale-while-revalidate).</p><p><strong>updateTag(…)</strong> = immediate expiration (Server Actions only).</p><blockquote><em>See the </em><strong><em>Comparison Table</em></strong><em> and the </em><strong><em>How To Choose?</em></strong><em> for when to use ISR vs SSG/SSR/CSR.</em></blockquote><h3><strong>SSR — Server-Side Rendering</strong></h3><h4><strong>The Principle</strong></h4><p>With SSR, HTML is <strong>generated on every request</strong> on the server. Unlike ISR, which caches, SSR generates <strong>always-fresh</strong> content at the cost of additional server processing.</p><h4><strong>Force Dynamic Behavior (optional)</strong></h4><p>A route becomes dynamic automatically as soon as it uses a dynamic signal: <strong>cookies()</strong>, <strong>headers()</strong>, <strong>searchParams</strong>, or a non-cached fetch. If you do not use any of these signals but still want to force dynamic behavior, use <strong>connection()</strong>:</p><pre>import { connection } from &#39;next/server&#39;<br><br>export default async function DashboardPage() {<br>  await connection()<br>  // ...<br>}</pre><p>In most cases, dynamic signals are enough and <strong>connection()</strong> is unnecessary.</p><h4><strong>SSR Configuration with Cache Components</strong></h4><p>With Cache Components, doing <strong>SSR</strong> (no cache) is very simple: <strong>just don’t use the ’use cache’ directive</strong>!</p><pre>// Server Component without &#39;use cache&#39;<br>export async function DashboardStats() {<br>  // No &#39;use cache&#39; = fresh data on every request<br>  const dashboardData = await getDashboardData()<br>  const currentTime = new Date().toISOString()<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Real-Time Statistics&lt;/h2&gt;<br>      &lt;p&gt;Last updated: {currentTime}&lt;/p&gt;<br><br>      &lt;div className=&quot;stats&quot;&gt;<br>        &lt;StatCard title=&quot;Total Orders&quot; value={dashboardData.totalOrders} /&gt;<br>        &lt;StatCard title=&quot;Revenue&quot; value={`${dashboardData.revenue}€`} /&gt;<br>        &lt;StatCard title=&quot;Support Tickets&quot; value={dashboardData.supportTickets} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>// In the main page, wrap with Suspense<br>export default function DashboardPage() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;StatsSkeleton /&gt;}&gt;<br>        &lt;DashboardStats /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4><strong>Suspense and SSR Streaming</strong></h4><p>Next.js allows you to use Suspense to <strong>stream</strong> SSR content progressively. Each async component wrapped in Suspense can have its own timing:</p><pre>import { Suspense } from &#39;react&#39;<br><br>export default function DashboardPage() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br><br>      {/* Fast stats */}<br>      &lt;Suspense fallback={&lt;StatsSkeleton /&gt;}&gt;<br>        &lt;QuickStats /&gt;<br>      &lt;/Suspense&gt;<br><br>      {/* Slower charts */}<br>      &lt;Suspense fallback={&lt;ChartsSkeleton /&gt;}&gt;<br>        &lt;ExpensiveCharts /&gt;<br>      &lt;/Suspense&gt;<br><br>      {/* Recent activity */}<br>      &lt;Suspense fallback={&lt;ActivitySkeleton /&gt;}&gt;<br>        &lt;RecentActivity /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p><strong>Advantage</strong>: The server sends HTML as early as possible, then streams slower parts progressively. The user sees the page build up over time.</p><h4><strong>SSR Storage</strong></h4><p>SSR <strong>does not cache data</strong> by default — business data is recomputed on every request. Next.js still generates a minimal shell in <strong>.next/server/app/</strong>. If you use <strong>’use cache’</strong> in a component within an SSR page, that component gets its own cache (similar to ISR), while the rest of the page remains dynamic.</p><blockquote><em>See the </em><strong><em>Comparison Table</em></strong><em> and the </em><strong><em>How To Choose?</em></strong><em> for when to use SSR vs SSG/ISR/CSR.</em></blockquote><h3><strong>CSR — Client-Side Rendering</strong></h3><h4><strong>The Principle</strong></h4><p>In App Router, all components — including <strong>’use client’</strong> ones — are pre-rendered on the server on initial load (unless explicitly opted out with <strong>dynamic(…, { ssr: false })</strong>). Client Components are then hydrated by React in the browser. What we call <strong>“CSR”</strong> here refers to the <strong>data fetching strategy</strong>: data is fetched client-side (via TanStack Query), not during server rendering.</p><h4><strong>Modern Implementation: Next.js + TanStack Query v5</strong></h4><p>A pragmatic pattern used in this demo (one of several valid approaches):</p><ol><li><strong>Provider scoped to CSR route</strong> (a global layout provider is also valid)</li><li><strong>useSuspenseQuery</strong> in client component (<strong>useQuery</strong> is also an option — it manages loading/error states manually without requiring a Suspense boundary)</li><li><strong>&lt;Suspense&gt;</strong> wrapping the data-dependent component (required by <strong>useSuspenseQuery</strong>)</li><li><strong>error.tsx</strong> for localized error handling</li></ol><p><strong>1) Query Client at CSR Route Level</strong></p><pre>// src/lib/query-client-provider.tsx<br>&#39;use client&#39;<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;<br>import { useState } from &#39;react&#39;<br><br>export const CSR_QUERY_DEFAULTS = {<br>  staleTime: 20_000,<br>  gcTime: 2 * 60_000,<br>  retry: 1,<br>  refetchOnWindowFocus: false, // demo choice: deterministic behavior<br>} as const<br><br>export function ClientQueryProvider({ children }: { children: React.ReactNode }) {<br>  const [queryClient] = useState(<br>    () =&gt;<br>      new QueryClient({<br>        defaultOptions: {<br>          queries: { ...CSR_QUERY_DEFAULTS },<br>        },<br>      })<br>  )<br><br>  return &lt;QueryClientProvider client={queryClient}&gt;{children}&lt;/QueryClientProvider&gt;<br>}</pre><p><strong>2) Query Defined Once and Reused</strong></p><pre>// src/components/rendering-methods/csr/dashboard.tsx<br>&#39;use client&#39;<br>import { queryOptions, useSuspenseQuery } from &#39;@tanstack/react-query&#39;<br><br>const csrQueryKeys = {<br>  dashboard: [&#39;csr&#39;, &#39;dashboard&#39;] as const,<br>}<br><br>const dashboardQueryOptions = queryOptions({<br>  queryKey: csrQueryKeys.dashboard,<br>  queryFn: ({ signal }) =&gt; fetchDashboardData({ signal }),<br>})<br><br>export function CSRDashboard() {<br>  const { data, isStale, isFetching } = useSuspenseQuery(dashboardQueryOptions)<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Status: {isFetching ? &#39;updating&#39; : isStale ? &#39;stale&#39; : &#39;fresh&#39;}&lt;/p&gt;<br>      &lt;pre&gt;{JSON.stringify(data, null, 2)}&lt;/pre&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p><strong>3) Suspense Boundary (Server Components)</strong></p><pre>// src/app/rendering-methods/csr/layout.tsx<br>// Provider scoped to this segment only — not in the global layout<br>import { ClientQueryProvider } from &#39;@/lib/query-client-provider&#39;<br><br>export default function CSRLayout({ children }: { children: React.ReactNode }) {<br>  return &lt;ClientQueryProvider&gt;{children}&lt;/ClientQueryProvider&gt;<br>}<br><br>// src/app/rendering-methods/csr/page.tsx<br>import { Suspense } from &#39;react&#39;<br><br>export default function CSRPage() {<br>  return (<br>    &lt;Suspense fallback={&lt;CSRDashboardSkeleton /&gt;}&gt;<br>      &lt;CSRDashboard /&gt;<br>    &lt;/Suspense&gt;<br>  )<br>}</pre><p><strong>4) Segment Error Boundary (App Router)</strong></p><pre>// src/app/rendering-methods/csr/error.tsx<br>&#39;use client&#39;<br><br>export default function CSRError({ error, reset }: { error: Error; reset: () =&gt; void }) {<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Failed to load CSR dashboard: {error.message}&lt;/p&gt;<br>      &lt;button onClick={reset}&gt;Retry&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><h4><strong>Client Cache in Practice</strong></h4><p>With <strong>staleTime: 20s</strong>, data is served from cache for 20 seconds. Once stale, a refetch is triggered on the next component mount, focus/reconnect (if enabled), or manual refetch — not automatically on a timer. Use the <strong>Network tab</strong> and <strong>React Query Devtools</strong> to observe this behavior.</p><blockquote><em>See the </em><strong><em>Comparison Table</em></strong><em> and the </em><strong><em>How To Choose?</em></strong><em> for when to use CSR vs SSG/ISR/SSR.</em></blockquote><h3><strong>Comparison Table: SSG, ISR, SSR, CSR</strong></h3><blockquote><em>This table compares the dominant strategy per page/segment. </em><strong>The ISR column reflects the Cache Components approach</strong><em> (</em><strong><em>&#39;use cache&#39; </em></strong><em>+ </em><strong><em>cacheLife</em></strong><em>). Hybrid compositions are covered in </em><strong><em>How To Choose?</em></strong></blockquote><pre>| <strong>Characteristic</strong>      | <strong>SSG</strong>                              | <strong>ISR</strong>                                                                                                                              | <strong>SSR</strong>                                  | <strong>CSR</strong>                                                 |<br>| ------------------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------ | --------------------------------------------------- |<br>| <strong>`use cache`</strong>         | ❌ No                            | ✅ Yes (implicit `default` profile or explicit `cacheLife`)                                                                      | ❌ No                                | ❌ N/A (client-side cache)                          |<br>| <strong>Performance</strong>         | ⚡ Maximum                        | ⚡ Excellent                                                                                                                     | 🟡 Good                              | 🟡 Variable                                         |<br>| <strong>Freshness</strong>           | 🔴 Fixed until next build        | 🟡 Depends on profile (`default` → `max`)                                                                                        | ✅ Always fresh                      | 🟡 Depends on `staleTime`/refetch                   |<br>| <strong>Revalidation</strong>        | ❌ None (rebuild required)       | 🔄 Auto (SWR) + on-demand (`revalidateTag`)                                                                                      | ❌ None (fresh on every request)     | 🔄 Client-side (focus, refetch, invalidate)         |<br>| <strong>SEO</strong>                 | ✅ Perfect                       | ✅ Excellent                                                                                                                     | ✅ Excellent                         | 🔴 Limited (data only) ¹                            |<br>| <strong>Server Load</strong>         | 🟢 Minimal                       | 🟢 Low (cache absorbs traffic)                                                                                                   | 🟡 Higher per request                | 🟢 Low (rendering server only — API load unchanged) |<br>| <strong>Personalization</strong>     | ❌ No                            | 🟡 Limited (parameterized via cache key; `cookies()`/`headers()` must be passed as args, not read directly inside `&#39;use cache&#39;`) | ✅ Yes                               | ✅ Yes                                              |<br>| <strong>JS Required</strong>         | ❌ No                            | ❌ No                                                                                                                            | ❌ No                                | ✅ Yes (data fetched client-side)                   |<br>| <strong>Cost</strong>                | 🟢 Minimal                       | 🟢 Low                                                                                                                           | 🟡 Higher per request                | 🟡 Variable ² (rendering: low; API cost unchanged)  |<br>| <strong>Best for</strong>            | Docs, legal pages, landing pages | E-commerce, blogs, news                                                                                                          | Dashboards, profiles, near real-time | Interactive apps, authenticated areas </pre><blockquote><em>ISR variants </em><strong><em>(</em>`<em>default</em>`<em>, </em>`<em>max</em>`<em>, custom)</em></strong><em> are detailed in </em><strong>Built-in cacheLife Profiles</strong><em>.</em></blockquote><blockquote><em>¹ </em><strong>CSR SEO</strong><em>: In App Router, every page produces a server-rendered HTML shell on initial load (including client-heavy pages). The </em><strong><em>🔴 Limited</em></strong><em> rating applies to the </em><strong>data</strong><em>: it is fetched client-side after hydration, so actual content is less reliably indexed by crawlers (some JS-capable crawlers do index it, but more slowly and inconsistently). Using </em><strong><em>dynamic(() =&gt; import(‘…’), { ssr: false })</em></strong><em> disables server prerendering for the </em><strong>targeted component</strong><em> (not the entire page shell).</em></blockquote><blockquote><em>² </em><strong>CSR Cost</strong><em>: The Next.js rendering server only serves a lightweight shell, keeping rendering costs low. However, your API server still receives one request per user data fetch — equivalent to SSR. Total infrastructure cost depends on your backend setup.</em></blockquote><h3><strong>How to Choose?</strong></h3><p>Here’s a simple decision tree:</p><h4><strong>0️⃣ Is the page mainly an interactive app-like interface?</strong></h4><p><strong>YES</strong> (dashboard, filters, rich interactions, low SEO priority) → <strong>Use CSR</strong></p><p><strong>NO</strong> → Go to question 1</p><h4><strong>1️⃣ Is the content identical for all users?</strong></h4><p><strong>YES</strong> → Go to question 2</p><p><strong>NO</strong> → <strong>Use SSR</strong> (personalized content)</p><h4><strong>2️⃣ Does the content change frequently?</strong></h4><p><strong>NO</strong> (manual updates) → <strong>Use SSG</strong> (blog, landing pages)</p><p><strong>YES</strong> (automatic updates) → Go to question 3</p><h4><strong>3️⃣ Do you need data fresh on every page load?</strong></h4><p><strong>YES</strong> (fresh on every page load) → <strong>Use SSR</strong> (monitoring, pricing, live inventory)</p><p><strong>NO</strong> (a few minutes is acceptable) → <strong>Use ISR</strong> (product catalog)</p><h4><strong>Hybrid Approach (Recommended)</strong></h4><p>In practice, most modern apps <strong>combine SSG, ISR, SSR, and CSR</strong> in the same app thanks to component-level cache and <strong>&lt;Suspense&gt;</strong>. Each section can have its own strategy: static header (SSG), 5-minute cached catalog <strong>(’use cache’ + cacheLife)</strong>, personalized recommendations (SSR without cache), interactive widget <strong>(’use client’ + TanStack Query)</strong>. Implementations are covered in earlier sections.</p><h3><strong>Conclusion</strong></h3><p>The <strong>comparison table</strong> and <strong>decision tree</strong> above summarize the choice between SSG, ISR, SSR, and CSR. In practice, most apps <strong>combine all four</strong> using component-level cache and Suspense.</p><p><strong>Three tips:</strong></p><ol><li>Start simple, then specialize strategy by section.</li><li>Keep server rendering for SEO and freshness; use CSR for rich interactivity.</li><li>Always measure in real conditions before optimizing.</li></ol><p><strong>Required configuration</strong>: see <strong>Global Prerequisite</strong> at the beginning of the article.</p><h3><strong>Useful Links</strong></h3><p>To go deeper, here are the official docs and related references:</p><h4><strong>Getting Started — Fundamentals</strong></h4><ul><li><a href="https://nextjs.org/docs/app/getting-started/server-and-client-components">Server and Client Components</a> — Understand the difference between server and client components</li><li><a href="https://nextjs.org/docs/app/getting-started/fetching-data">Fetching Data</a> — How to fetch data in Next.js</li><li><a href="https://nextjs.org/docs/app/getting-started/updating-data">Updating Data</a> — Mutations and Server Actions</li><li><a href="https://nextjs.org/docs/app/getting-started/cache-components">Cache Components</a> — Introduction to Cache Components</li><li><a href="https://nextjs.org/docs/app/getting-started/caching-and-revalidating">Caching and Revalidating</a> — Caching and revalidation guide</li></ul><h4><strong>Advanced Guides</strong></h4><ul><li><a href="https://nextjs.org/docs/app/guides/caching">Caching Guide</a> — Full caching guide</li><li><a href="https://nextjs.org/docs/app/guides/incremental-static-regeneration">Incremental Static Regeneration</a> — Detailed ISR guide</li><li><a href="https://nextjs.org/docs/app/guides/lazy-loading">Lazy Loading</a> — Code splitting and dynamic imports <strong>(`next/dynamic`)</strong></li></ul><h4><strong>API Reference — Cache Components</strong></h4><ul><li><a href="https://nextjs.org/docs/app/api-reference/directives/use-cache">use cache directive</a> — Official documentation for the <strong>`use cache`</strong> directive</li><li><a href="https://nextjs.org/docs/app/api-reference/functions/cacheLife">cacheLife function</a> — Official documentation for <strong>cacheLife</strong> and profiles</li><li><a href="https://nextjs.org/docs/app/api-reference/functions/cacheTag">cacheTag function</a> — Tag a cached function or component for targeted revalidation</li><li><a href="https://nextjs.org/docs/app/api-reference/functions/revalidateTag">revalidateTag function</a> — On-demand revalidation (SWR recommended with <strong>’max’</strong>)</li><li><a href="https://nextjs.org/docs/app/api-reference/functions/updateTag">updateTag function</a>) — Immediate expiration for read-your-writes (Server Actions)</li><li><a href="https://nextjs.org/docs/app/api-reference/functions/refresh">refresh function</a> — Route client-cache refresh after Server Action</li><li><a href="https://nextjs.org/docs/messages/revalidate-tag-single-arg">revalidateTag(tag) without profile (deprecated)</a> — Official migration note</li><li><a href="https://nextjs.org/docs/app/api-reference/next-config-js/cacheLife">next.config.js: cacheLife</a> — Configure custom <strong>cacheLife</strong> profiles in <strong>next.config.ts</strong></li></ul><h4><strong>API Reference — SSG &amp; SSR</strong></h4><ul><li><a href="https://nextjs.org/docs/app/api-reference/functions/generate-static-params">generateStaticParams</a> — Pre-generate dynamic routes at build time (SSG)</li><li><a href="https://nextjs.org/docs/app/api-reference/functions/connection">connection function</a> — Force dynamic rendering without a dynamic API signal (SSR)</li></ul><h4><strong>CSR — TanStack Query</strong></h4><ul><li><a href="https://tanstack.com/query/v5">TanStack Query v5 docs</a> — Full documentation for the client-side data fetching and caching library used in the CSR examples</li><li><a href="https://tanstack.com/query/v5/docs/framework/react/guides/suspense">TanStack Query — Suspense</a> — Using <strong>useSuspenseQuery</strong> with React Suspense</li><li><a href="https://nextjs.org/docs/app/guides/single-page-applications">Next.js — Single Page Applications</a> — Client-only rendering with <strong>ssr: false</strong></li></ul><p><strong>These resources will help you explore rendering strategies and caching in Next.js in depth.</strong></p><p><strong>💡 To dive deeper</strong>: Explore code examples in this <a href="https://github.com/kiki-le-singe/nextjs-perf-showcase">GitHub repo — nextjs-perf-showcase</a> and combine <strong>server cache</strong> <strong>(’use cache’)</strong> + <strong>client cache</strong> (TanStack Query) based on your use case.</p><blockquote><strong>⚠️ Just a note: </strong>This article doesn’t claim to be exhaustive or perfect — if something seems off or outdated, feel free to dig deeper or let me know. Happy to hear from you 🙂</blockquote><p>🙏 <strong>Thanks for reading!</strong></p><p>If you found this article useful, feel free to share it or leave a like. And of course, if you have feedback or questions, don’t hesitate to reach out. Always happy to learn and connect! 🚀</p><p>Find me on <a href="https://github.com/kiki-le-singe">https://github.com/kiki-le-singe</a> or <a href="https://x.com/kiki_le_singe">https://x.com/kiki_le_singe</a></p><h3>A message from our Founder</h3><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c6c36f7c235" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/rendering-methods-in-next-js-16-ssg-vs-isr-vs-ssr-vs-csr-explained-1c6c36f7c235">SSG vs ISR vs SSR vs CSR in Next.js 16: When to Use Each (and Why It Matters)</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Next.js Streaming Guide: loading.tsx, Suspense, and Performance]]></title>
            <link>https://javascript.plainenglish.io/a-complete-next-js-streaming-guide-loading-tsx-suspense-and-performance-c0979bc47896?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0979bc47896</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 17:05:14 GMT</pubDate>
            <atom:updated>2025-08-12T14:20:08.131Z</atom:updated>
            <content:encoded><![CDATA[<p>When building modern web apps, speed isn’t just about fast loading — it’s about feeling fast. Users expect immediate feedback, even when data takes time to load.</p><p>Next.js supports <strong>streaming</strong> out of the box with the App Router, helping you deliver pages progressively, piece by piece, instead of making users wait for everything.</p><p>In this article, I’ll explain what streaming means in practice, how it works in Next.js, and why <strong>loading.tsx</strong> makes it even easier to implement.</p><h4><strong>See Demos in Action</strong></h4><p>Want to explore similar examples? Check out this <a href="https://github.com/kiki-le-singe/nextjs-perf-showcase">GitHub repo — nextjs-perf-showcase</a> with demo projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opwMWzEyc3Li3OuvrQBP8g.gif" /></figure><h4><strong>What is Streaming?</strong></h4><p>Instead of waiting for the entire server-rendered page to be ready, <strong>streaming</strong> lets the server send chunks of HTML progressively as they become available. The browser can start rendering immediately, showing users content as soon as possible.</p><p>Think of it like watching a video online — you don’t wait for the entire file to download before playback starts. Same concept for web pages!</p><h4><strong>Why Does It Matter?</strong></h4><p>Without streaming, users stare at a blank screen while the server prepares the full response. This creates a poor experience, especially on slower connections.</p><p>With streaming:</p><ul><li>⚡ <strong>Faster perceived performance</strong> — Users see content immediately</li><li>🧩 <strong>Load critical content first</strong> — Navigation, headers appear instantly</li><li>⏳ <strong>Non-blocking data fetches</strong> — Slow API calls don’t freeze the entire page</li><li><strong>📱Better mobile experience</strong> — Progressive loading on slower networks</li></ul><h4><strong>How Streaming Works in Next.js</strong></h4><p>Next.js provides two complementary approaches for implementing streaming:</p><p><strong>### Page-Level Streaming with loading.tsx</strong></p><p>Use a <strong>loading.tsx</strong> file to handle loading states globally for an entire route. Next.js automatically wraps your page in a Suspense boundary, enabling the server to stream HTML progressively while showing your loading UI immediately.</p><p>Here’s how it works in practice:</p><pre>// app/dashboard/layout.tsx<br>export default function Layout({ children }) {<br>  return (<br>    &lt;div className=&quot;dashboard-layout&quot;&gt;<br>      &lt;Sidebar /&gt;<br>      &lt;div className=&quot;main-content&quot;&gt;<br>        &lt;Header /&gt;<br>        {children}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// app/dashboard/loading.tsx<br>export default function Loading() {<br>  return (<br>    &lt;div className=&quot;page-skeleton&quot;&gt;<br>      &lt;div className=&quot;skeleton-cards&quot; /&gt;<br>      &lt;div className=&quot;skeleton-chart&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// app/dashboard/page.tsx<br>export default async function Dashboard() {<br>  // This entire page can take time to load<br>  const data = await fetchDashboardData();<br><br>  return (<br>    &lt;div className=&quot;dashboard-content&quot;&gt;<br>      &lt;div className=&quot;metrics-cards&quot;&gt;<br>        &lt;MetricCard title=&quot;Revenue&quot; value={data.revenue} /&gt;<br>        &lt;MetricCard title=&quot;Users&quot; value={data.users} /&gt;<br>        &lt;MetricCard title=&quot;Orders&quot; value={data.orders} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;analytics-chart&quot;&gt;<br>        &lt;Chart data={data.chartData} /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Benefits of <strong>loading.tsx</strong>:</p><ul><li>Automatically applies to the route segment</li><li>No need to wrap components in Suspense</li><li>Works with nested routes</li><li>Keeps loading states organized</li></ul><p><strong>### Component-Level Streaming with &lt;Suspense&gt;</strong></p><p>For more granular control, use React’s <strong>&lt;Suspense&gt;</strong> component to stream specific parts of your UI independently.</p><p>Next.js enables streaming by default with the App Router. Every Server Component can stream its output when wrapped with <strong>Suspense</strong>:</p><pre>import { Suspense } from &quot;react&quot;;<br><br>// This component loads fast<br>function Header() {<br>  return &lt;h1&gt;Dashboard&lt;/h1&gt;;<br>}<br><br>// This component needs time to fetch data<br>async function Analytics() {<br>  const data = await fetchAnalytics(); // Slow API call<br>  return &lt;AnalyticsChart data={data} /&gt;;<br>}<br><br>export default function DashboardPage() {<br>  return (<br>    &lt;&gt;<br>      &lt;Header /&gt; {/* Shows immediately */}<br>      &lt;Suspense fallback={&lt;div&gt;Loading analytics...&lt;/div&gt;}&gt;<br>        &lt;Analytics /&gt; {/* Streams in when ready */}<br>      &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The page renders in this order:</p><ol><li>Header appears instantly</li><li>Loading fallback shows for Analytics</li><li>Analytics component streams in when data is ready</li></ol><h4><strong>Under the Hood: How Next.js Streaming Works</strong></h4><p>When you use streaming in Next.js, here’s what happens:</p><ol><li><strong>Server-Side</strong>: Next.js starts rendering your page and immediately sends the static structure (layout, headers, navigation)</li><li><strong>Suspense Detection</strong>: When React encounters a Suspense boundary with pending data, it pauses that component</li><li><strong>Progressive Rendering</strong>: The server continues rendering other parts of the page while data fetches happen in parallel</li><li><strong>Chunk Streaming</strong>: As data becomes available, Next.js streams HTML chunks to the browser</li><li><strong>Client Hydration</strong>: React hydrates components as they arrive, making them interactive</li></ol><p>This process uses HTTP streaming and React’s concurrent features to deliver content as fast as possible.</p><h4><strong>Real-World Example: E-commerce Dashboard</strong></h4><p>Let’s build a complex dashboard that demonstrates multiple streaming patterns:</p><pre>// app/dashboard/page.tsx<br>import { Suspense } from &quot;react&quot;;<br>import { ErrorBoundary } from &quot;react-error-boundary&quot;;<br><br>export default function Dashboard() {<br>  return (<br>    &lt;div className=&quot;dashboard&quot;&gt;<br>      {/* Critical content loads first */}<br>      &lt;Header /&gt;<br>      &lt;Navigation /&gt;<br><br>      {/* Stream multiple components in parallel */}<br>      &lt;div className=&quot;dashboard-grid&quot;&gt;<br>        &lt;ErrorBoundary fallback={&lt;ErrorCard /&gt;}&gt;<br>          &lt;Suspense fallback={&lt;MetricsSkeleton /&gt;}&gt;<br>            &lt;RealtimeMetrics /&gt;<br>          &lt;/Suspense&gt;<br>        &lt;/ErrorBoundary&gt;<br><br>        &lt;ErrorBoundary fallback={&lt;ErrorCard /&gt;}&gt;<br>          &lt;Suspense fallback={&lt;ChartSkeleton /&gt;}&gt;<br>            &lt;SalesChart /&gt;<br>          &lt;/Suspense&gt;<br>        &lt;/ErrorBoundary&gt;<br><br>        &lt;ErrorBoundary fallback={&lt;ErrorCard /&gt;}&gt;<br>          &lt;Suspense fallback={&lt;TableSkeleton /&gt;}&gt;<br>            &lt;RecentOrders /&gt;<br>          &lt;/Suspense&gt;<br>        &lt;/ErrorBoundary&gt;<br><br>        {/* Nested streaming for complex components */}<br>        &lt;div className=&quot;inventory-section&quot;&gt;<br>          &lt;h2&gt;Inventory&lt;/h2&gt;<br>          &lt;Suspense fallback={&lt;InventorySkeleton /&gt;}&gt;<br>            &lt;InventoryOverview /&gt;<br>          &lt;/Suspense&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Each component handles its own data fetching<br>async function RealtimeMetrics() {<br>  const metrics = await fetchMetrics(); // 500ms<br>  return &lt;MetricsCards data={metrics} /&gt;;<br>}<br><br>async function SalesChart() {<br>  const sales = await fetchSalesData(); // 1.2s<br>  return &lt;Chart data={sales} /&gt;;<br>}<br><br>async function RecentOrders() {<br>  const orders = await fetchRecentOrders(); // 800ms<br>  return &lt;OrdersTable orders={orders} /&gt;;<br>}<br><br>async function InventoryOverview() {<br>  // Parent component fetches its own data first<br>  const inventory = await fetchInventoryData(); // 600ms<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h3&gt;{inventory.title}&lt;/h3&gt;<br>      &lt;p&gt;Total Items: {inventory.totalItems}&lt;/p&gt;<br><br>      {/* Nested streaming within inventory */}<br>      &lt;Suspense fallback={&lt;div&gt;Loading stock levels...&lt;/div&gt;}&gt;<br>        &lt;StockLevels warehouseId={inventory.warehouseId} /&gt;<br>      &lt;/Suspense&gt;<br><br>      &lt;Suspense fallback={&lt;div&gt;Loading alerts...&lt;/div&gt;}&gt;<br>        &lt;LowStockAlerts threshold={inventory.alertThreshold} /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>async function StockLevels({ warehouseId }) {<br>  const levels = await fetchStockLevels(warehouseId); // 400ms<br>  return &lt;StockChart data={levels} /&gt;;<br>}<br><br>async function LowStockAlerts({ threshold }) {<br>  const alerts = await fetchLowStockAlerts(threshold); // 300ms<br>  return &lt;AlertsList alerts={alerts} /&gt;;<br>}</pre><p><strong>Loading sequence:</strong></p><ol><li>Header &amp; Navigation appear instantly</li><li>All skeleton states show simultaneously</li><li>RealtimeMetrics loads first (500ms)</li><li>InventoryOverview loads next (600ms) → shows inventory summary + child loading states</li><li>RecentOrders loads next (800ms)</li><li>SalesChart loads last (1.2s)</li><li>StockLevels and LowStockAlerts stream independently (300–400ms after inventory loads)</li></ol><h4><strong>Error Boundaries with Streaming</strong></h4><p>Combine error boundaries with Suspense when your components perform fallible operations (API calls, external dependencies):</p><pre>// app/dashboard/error.tsx (Next.js built-in approach)<br>&quot;use client&quot;;<br><br>export default function Error({ error, reset }) {<br>  return (<br>    &lt;div className=&quot;error-card&quot;&gt;<br>      &lt;h3&gt;Failed to load dashboard data&lt;/h3&gt;<br>      &lt;p&gt;{error.message}&lt;/p&gt;<br>      &lt;button onClick={reset}&gt;Retry&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>For granular error handling:</strong></p><pre>// components/SafeStreamingComponent.tsx<br>&quot;use client&quot;;<br><br>import { Suspense } from &quot;react&quot;;<br>import { ErrorBoundary } from &quot;react-error-boundary&quot;;<br><br>function DataErrorFallback({ error, resetErrorBoundary }) {<br>  return (<br>    &lt;div className=&quot;error-card&quot;&gt;<br>      &lt;h4&gt;Failed to load data&lt;/h4&gt;<br>      &lt;p&gt;{error.message}&lt;/p&gt;<br>      &lt;button onClick={resetErrorBoundary}&gt;Try again&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export function SafeStreamingComponent({ children, fallback }) {<br>  return (<br>    &lt;ErrorBoundary FallbackComponent={DataErrorFallback}&gt;<br>      &lt;Suspense fallback={fallback}&gt;{children}&lt;/Suspense&gt;<br>    &lt;/ErrorBoundary&gt;<br>  );<br>}</pre><p><strong>Usage:</strong></p><pre>// Example async component that could fail<br>async function UserProfile({ userId }) {<br>  const user = await fetchUser(userId); // Could throw an error<br>  return &lt;div&gt;Welcome, {user.name}!&lt;/div&gt;;<br>}<br><br>// Instead of writing this every time:<br>&lt;ErrorBoundary FallbackComponent={DataErrorFallback}&gt;<br>  &lt;Suspense fallback={&lt;div&gt;Loading user data...&lt;/div&gt;}&gt;<br>    &lt;UserProfile userId={123} /&gt;<br>  &lt;/Suspense&gt;<br>&lt;/ErrorBoundary&gt;<br><br>// You can just use:<br>&lt;SafeStreamingComponent fallback={&lt;div&gt;Loading user data...&lt;/div&gt;}&gt;<br>  &lt;UserProfile userId={123} /&gt;<br>&lt;/SafeStreamingComponent&gt;</pre><p><strong>When to use each approach:</strong></p><ul><li><strong>Next.js <em>error.tsx</em></strong>: Route-level errors (entire page fails)</li><li><strong>Custom ErrorBoundary</strong>: Component-level errors (specific parts fail)</li></ul><p><strong>Use error boundaries when components:</strong></p><ul><li>Fetch data from APIs</li><li>Use external libraries</li><li>Process user input</li><li>Could reasonably fail at runtime</li></ul><p><strong>Skip for simple code splitting:</strong></p><pre>// No error boundary needed - just lazy loading<br>&lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>  &lt;LazyModalComponent /&gt;<br>&lt;/Suspense&gt;</pre><h4><strong>Performance Monitoring</strong></h4><p>Track streaming performance using the browser’s built-in <strong>Web Performance API</strong>:</p><pre>// utils/performance.ts<br>export function measureStreamingPerformance() {<br>  const navigation = performance.getEntriesByType(&quot;navigation&quot;)[0];<br>  const paintEntries = performance.getEntriesByType(&quot;paint&quot;);<br><br>  if (!navigation || typeof window === &quot;undefined&quot;) return;<br><br>  // Measure Time to First Byte (TTFB)<br>  const ttfb = navigation.responseStart;<br><br>  // Measure First Contentful Paint<br>  const fcp = paintEntries.find(<br>    (entry) =&gt; entry.name === &quot;first-contentful-paint&quot;<br>  )?.startTime;<br><br>  console.log(&quot;TTFB:&quot;, Math.round(ttfb) + &quot;ms&quot;);<br>  console.log(&quot;FCP:&quot;, Math.round(fcp || 0) + &quot;ms&quot;);<br><br>  // LCP requires PerformanceObserver for accuracy<br>  if (&quot;PerformanceObserver&quot; in window) {<br>    new PerformanceObserver((list) =&gt; {<br>      const lcp = list.getEntries().at(-1)?.startTime;<br>      console.log(&quot;LCP:&quot;, Math.round(lcp || 0) + &quot;ms&quot;);<br>    }).observe({ type: &quot;largest-contentful-paint&quot;, buffered: true });<br>  }<br>}</pre><pre>// hooks/useStreamingPerformance.ts<br>&quot;use client&quot;;<br><br>import { useEffect } from &quot;react&quot;;<br>import { measureStreamingPerformance } from &quot;@/utils/performance&quot;;<br><br>export function useStreamingPerformance() {<br>  useEffect(() =&gt; {<br>    measureStreamingPerformance();<br>  }, []);<br>}</pre><p><strong>Usage in components:</strong></p><pre>// components/PerformanceTracker.tsx<br>&quot;use client&quot;;<br><br>import { useStreamingPerformance } from &quot;@/hooks/useStreamingPerformance&quot;;<br><br>export function PerformanceTracker() {<br>  useStreamingPerformance();<br>  return null; // This component only tracks performance<br>}<br><br>// pages/dashboard.tsx<br>import { PerformanceTracker } from &quot;@/components/PerformanceTracker&quot;;<br><br>export default function Dashboard() {<br>  return (<br>    &lt;div&gt;<br>      &lt;PerformanceTracker /&gt;<br>      &lt;Header /&gt;<br>      &lt;Suspense fallback={&lt;Loading /&gt;}&gt;<br>        &lt;StreamingContent /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>What these metrics mean:</strong></p><ul><li><strong>TTFB (Time to First Byte)</strong>: How fast your server responds — measures streaming start</li><li><strong>FCP (First Contentful Paint)</strong>: When users first see content — critical for perceived performance</li><li><strong>LCP (Largest Contentful Paint)</strong>: When main content loads — Core Web Vital for SEO</li></ul><p><strong>Good streaming targets:</strong></p><ul><li>TTFB &lt; 200ms (fast server response)</li><li>FCP — TTFB &lt; 300ms (content streams quickly after server response)</li><li>Progressive LCP improvements (content loads in chunks, not all at once)</li></ul><p><strong>Chrome DevTools tips:</strong></p><ol><li><strong>Network throttling</strong>: Click the “Network: No throttling” dropdown (visible in your screenshot) → Select “Slow 3G” to simulate slow connections and see streaming in action</li><li><strong>Performance tab</strong>: Record page load to see when HTML chunks arrive:</li></ol><ul><li>Click “Record and reload” button</li><li>Look for multiple “Parse HTML” entries showing streaming chunks</li></ul><p>3. <strong>Lighthouse</strong>: Run audit to measure streaming effectiveness:</p><ul><li>Go to Lighthouse tab → Click “Analyze page load”</li><li>Check metrics like First Contentful Paint and Time to Interactive</li></ul><h4><strong>When to Use Each Loading State</strong></h4><p><strong>### 🦴 Skeleton Screens</strong></p><p>Best for structured content like cards, tables, or lists (maintains layout and prevents content shift):</p><pre>&lt;div className=&quot;skeleton-card animate-pulse&quot;&gt;<br>  &lt;div className=&quot;h-4 bg-gray-200 rounded w-3/4&quot; /&gt;<br>  &lt;div className=&quot;h-4 bg-gray-200 rounded w-1/2 mt-2&quot; /&gt;<br>&lt;/div&gt;</pre><p><strong>### 🌀 Spinners</strong></p><p>Good for quick actions or unknown content structure (when you can’t predict the layout):</p><pre>&lt;div className=&quot;flex justify-center&quot;&gt;<br>  &lt;Spinner /&gt;<br>&lt;/div&gt;</pre><p><strong>### 📝 Content Placeholders</strong></p><p>Ideal for text-heavy areas (simple and lightweight for fast display):</p><pre>&lt;p className=&quot;text-gray-400&quot;&gt;Loading article content...&lt;/p&gt;</pre><h4><strong>Best Practices</strong></h4><p><strong>✅ DO:</strong></p><ul><li><strong>Stream critical content first</strong> — Headers, navigation, above-the-fold content</li><li><strong>Use skeleton screens</strong> — They maintain layout structure and prevent content shift</li><li><strong>Keep fallbacks lightweight</strong> — They should load instantly</li><li><strong>Test on slow connections</strong> — Use Chrome DevTools network throttling</li><li><strong>Progressive enhancement</strong> — Show basic content first, enhance with streaming</li><li><strong>Test with real data volumes</strong> — Large datasets affect streaming differently</li></ul><p><strong>❌ DON’T:</strong></p><ul><li><strong>Over-stream</strong> — Too many loading states can be jarring</li><li><strong>Block the entire page</strong> — Stream heavy components individually</li><li><strong>Forget error boundaries</strong> — Always wrap streamed components in error boundaries</li><li><strong>Skip performance monitoring</strong> — Measure streaming impact with real metrics</li><li><strong>Use generic spinners everywhere</strong> — Be specific with loading states</li></ul><h4><strong>Useful Links</strong></h4><ul><li><a href="https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming">Next.js Streaming Documentation</a></li><li><a href="https://nextjs.org/docs/app/getting-started/fetching-data#streaming">Fetching Data — Streaming</a></li><li><a href="https://react.dev/reference/react/Suspense">React Suspense Guide</a></li><li><a href="https://nextjs.org/docs/app/getting-started/error-handling">Error Handling</a></li></ul><h4><strong>Closing Thoughts</strong></h4><p>Streaming in Next.js isn’t just a performance optimization — it’s a UX philosophy. By showing users content progressively, you create experiences that feel instant and responsive.</p><p>Start simple with <strong>loading.tsx</strong> for route transitions, then add component-level streaming where it makes the most impact. Your users will notice the difference!</p><blockquote>💡 <strong>Quick tip</strong>: Use the React DevTools Profiler to identify which components take longest to render — those are perfect candidates for streaming!</blockquote><blockquote><strong>⚠️ Just a note: </strong>This article doesn’t claim to be exhaustive or perfect — if something seems off or outdated, feel free to dig deeper or let me know. Happy to hear from you 🙂</blockquote><p>🙏 <strong>Thanks for reading!</strong></p><p>If you found this article useful, feel free to share it or leave a like. And of course, if you have feedback or questions, don’t hesitate to reach out. Always happy to learn and connect! 🚀</p><p>Find me on <a href="https://github.com/kiki-le-singe">https://github.com/kiki-le-singe</a> or <a href="https://x.com/kiki_le_singe">https://x.com/kiki_le_singe</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0979bc47896" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/a-complete-next-js-streaming-guide-loading-tsx-suspense-and-performance-c0979bc47896">A Complete Next.js Streaming Guide: loading.tsx, Suspense, and Performance</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimize Next.js Performance with Smart Code Splitting: What to Load, When, and Why]]></title>
            <link>https://javascript.plainenglish.io/optimize-next-js-performance-with-smart-code-splitting-what-to-load-when-and-why-485dac08cd24?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/485dac08cd24</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Fri, 18 Jul 2025 19:30:47 GMT</pubDate>
            <atom:updated>2025-08-06T14:15:48.840Z</atom:updated>
            <content:encoded><![CDATA[<p>When building modern web applications, performance isn’t a luxury — it’s a necessity. Next.js comes with built-in code splitting to help you deliver faster, leaner apps by loading only what’s needed.</p><p>So how can you go beyond the defaults and take more control over what gets loaded — and when?</p><p>In this article, we’ll explore how to use <strong>dynamic imports</strong> effectively in Next.js to optimize performance — especially for components and libraries that aren’t required on initial load.</p><h4><strong>See Demos in Action</strong></h4><p>Want to explore similar examples? Check out this GitHub repo with demo projects: <a href="https://github.com/kiki-le-singe/nextjs-perf-showcase"><strong>nextjs-perf-showcase</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v_5GvG43_HCugE07U40Xjw.gif" /></figure><h4><strong>Why Code Splitting Matters</strong></h4><p>Code splitting allows you to break your application into smaller JavaScript bundles (or “chunks”) that can be loaded on demand. This leads to:</p><ul><li>⚡ Faster initial load times</li><li>📉 Reduced bundle sizes</li><li>📱 Better user experience — especially on slow or mobile networks</li></ul><p>Without code splitting, users must download the entire app upfront — even if they only interact with a small part of it.</p><h4><strong>Static vs Dynamic Imports</strong></h4><p><strong><em>With static imports:</em></strong></p><pre>import Component from &quot;./MyComponent&quot;;</pre><p>Everything is bundled and shipped during the initial load — even if the component isn’t used right away.</p><p><strong><em>With dynamic imports:</em></strong></p><pre>const Component = dynamic(() =&gt; import(&quot;./MyComponent&quot;));</pre><p>The component is loaded only when it’s needed. This leads to smaller initial bundles and improved startup performance.</p><h4>When Might You Use Dynamic Imports?</h4><p>Use <strong>next/dynamic</strong> when a component:</p><ul><li>Is <strong>heavy</strong> (e.g., charts, video players, maps)</li><li>Is <strong>conditionally visible or secondary U</strong>I (e.g., modals, tooltips, dropdowns, some carousels)</li><li>Is <strong>restricted or role-based UI</strong> (e.g., admin panels, private sections)</li></ul><p>In short: if a component isn’t needed upfront, you might consider loading it dynamically.</p><h4>Example: Dynamic Modal</h4><pre>&quot;use client&quot;;<br><br>import dynamic from &quot;next/dynamic&quot;;<br>import { useState } from &quot;react&quot;;<br><br>const Modal = dynamic(() =&gt; import(&quot;../components/Modal&quot;));<br><br>export default function ModalContainer() {<br>  const [isOpen, setIsOpen] = useState(false);<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; setIsOpen(true)}&gt;Open Modal&lt;/button&gt;<br>      {isOpen &amp;&amp; &lt;Modal onClose={() =&gt; setIsOpen(false)} /&gt;}<br>    &lt;/&gt;<br>  );<br>}</pre><p>In this example, the modal component is <strong>excluded from the initial bundle</strong> and only loaded when needed. This helps keep your main bundle lightweight.</p><h4><strong>Dynamic Tabs</strong></h4><p>Tabs are a great use case for dynamic imports — especially when the content of each tab is heavy (e.g., charts, maps, or long lists) and not immediately visible.</p><p>Let’s say you have a basic tab interface with four components: <strong>TabOverview</strong>, <strong>TabCharts</strong>, <strong>TabReports</strong>, and <strong>TabUsers</strong>.</p><pre>&quot;use client&quot;;<br><br>import dynamic from &quot;next/dynamic&quot;;<br>import { useState } from &quot;react&quot;;<br><br>const TabOverview = dynamic(() =&gt; import(&quot;./tabs/TabOverview&quot;));<br>const TabCharts = dynamic(() =&gt; import(&quot;./tabs/TabCharts&quot;));<br>const TabReports = dynamic(() =&gt; import(&quot;./tabs/TabReports&quot;));<br>const TabUsers = dynamic(() =&gt; import(&quot;./tabs/TabUsers&quot;));<br><br>const tabs = {<br>  tabOverview: TabOverview,<br>  tabCharts: TabCharts,<br>  tabReports: TabReports,<br>  tabUsers: TabUsers,<br>};<br><br>export default function Dashboard() {<br>  const [activeTab, setActiveTab] = useState(&quot;tabOverview&quot;);<br>  const ActiveTabContent = tabs[activeTab];<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setActiveTab(&quot;tabOverview&quot;)}&gt;Overview&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setActiveTab(&quot;tabCharts&quot;)}&gt;Charts&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setActiveTab(&quot;tabReports&quot;)}&gt;Reports&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setActiveTab(&quot;tabUsers&quot;)}&gt;Users&lt;/button&gt;<br><br>      &lt;div&gt;<br>        &lt;ActiveTabContent /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>Dynamically Load Heavy External Libraries</strong></h4><p>Heavy third-party libraries should also be imported dynamically. These libraries are often not needed on initial load, and can drastically increase your bundle size if included too early.</p><p>Let’s explore three practical examples.</p><h4><strong>🗺️ Example 1: Display a Map with <em>leaflet</em></strong></h4><pre>// src/app/contact/page.js (Server Component)<br><br>import MapSection from &quot;@/components/MapSection&quot;;<br><br>export default function ContactPage() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Contact Us&lt;/h1&gt;<br>      &lt;p&gt;Email: foo@bar.com&lt;/p&gt;<br>      &lt;p&gt;Phone: 0123456789&lt;/p&gt;<br><br>      {/* Client Component for interactive part */}<br>      &lt;MapSection /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>&quot;use client&quot;;<br><br>import { useState, useRef, useEffect } from &quot;react&quot;;<br><br>export default function MapSection() {<br>  const [showMap, setShowMap] = useState(false);<br>  const [isLoading, setIsLoading] = useState(false);<br>  const leafletRef = useRef(null);<br>  const mapContainerRef = useRef(null);<br>  const mapInstanceRef = useRef(null);<br><br>  // Preload Leaflet on hover<br>  async function preloadLeaflet() {<br>    if (!leafletRef.current) {<br>      leafletRef.current = await import(&quot;leaflet&quot;);<br>      await import(&quot;leaflet/dist/leaflet.css&quot;);<br>    }<br>  }<br><br>  async function loadMap() {<br>    setShowMap(true);<br>    setIsLoading(true);<br><br>    try {<br>      await preloadLeaflet();<br><br>      // Create map<br>      if (mapContainerRef.current &amp;&amp; !mapInstanceRef.current) {<br>        const L = leafletRef.current;<br><br>        // Fix Leaflet default icon issue in Next.js<br>        delete L.Icon.Default.prototype._getIconUrl;<br>        L.Icon.Default.mergeOptions({<br>          iconUrl:<br>            &quot;https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon.png&quot;,<br>          iconRetinaUrl:<br>            &quot;https://unpkg.com/leaflet@1.9.4/dist/images/marker-icon-2x.png&quot;,<br>          shadowUrl:<br>            &quot;https://unpkg.com/leaflet@1.9.4/dist/images/marker-shadow.png&quot;,<br>        });<br><br>        // Initialize map<br>        const map = L.map(mapContainerRef.current).setView([48.86, 2.35], 13);<br>        L.tileLayer(&quot;https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png&quot;, {<br>          attribution: &quot;© OpenStreetMap contributors&quot;,<br>        }).addTo(map);<br>        L.marker([48.86, 2.35]).addTo(map).bindPopup(&quot;Our office&quot;);<br><br>        mapInstanceRef.current = map;<br>      }<br>    } catch (error) {<br>      console.error(&quot;Error loading map:&quot;, error);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  }<br><br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      if (mapInstanceRef.current) {<br>        mapInstanceRef.current.remove();<br>        mapInstanceRef.current = null;<br>      }<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button<br>        onMouseEnter={preloadLeaflet}<br>        onClick={loadMap}<br>        style={{<br>          padding: &quot;10px 20px&quot;,<br>          fontSize: &quot;16px&quot;,<br>          cursor: &quot;pointer&quot;,<br>        }}<br>      &gt;<br>        Show map<br>      &lt;/button&gt;<br><br>      {showMap &amp;&amp; (<br>        &lt;div<br>          ref={mapContainerRef}<br>          style={{<br>            height: 400,<br>            marginTop: 20,<br>            position: &quot;relative&quot;,<br>            backgroundColor: isLoading ? &quot;#f0f0f0&quot; : &quot;transparent&quot;,<br>          }}<br>        &gt;<br>          {isLoading &amp;&amp; (<br>            &lt;div<br>              style={{<br>                position: &quot;absolute&quot;,<br>                top: &quot;50%&quot;,<br>                left: &quot;50%&quot;,<br>                transform: &quot;translate(-50%, -50%)&quot;,<br>                zIndex: 1000,<br>              }}<br>            &gt;<br>              &lt;p&gt;Loading map...&lt;/p&gt;<br>            &lt;/div&gt;<br>          )}<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>🎶 Example 2: Play an mp3 with <em>wavesurfer</em></strong></p><pre>// src/app/player/page.js (Server Component)<br><br>import AudioPlayer from &quot;@/components/AudioPlayer&quot;;<br><br>export default function AudioPlayerPage() {<br>  // Here you could fetch audio metadata from an API<br><br>  return (<br>    &lt;div&gt;<br>      {/* Client Component for interactive part */}<br>      &lt;AudioPlayer audioUrl=&quot;/file.mp3&quot; /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// src/components/AudioPlayer.js<br>&quot;use client&quot;;<br><br>import { useState, useRef, useEffect } from &quot;react&quot;;<br><br>export default function AudioPlayer({ audioUrl }) {<br>  const waveformRef = useRef(null);<br>  const wavesurferRef = useRef(null);<br>  const wavesurferLibRef = useRef(null);<br>  const [isPlaying, setIsPlaying] = useState(false);<br>  const [isLoading, setIsLoading] = useState(false);<br>  const [error, setError] = useState(null);<br><br>  // Preload WaveSurfer on hover<br>  async function preloadWaveSurfer() {<br>    if (!wavesurferLibRef.current) {<br>      wavesurferLibRef.current = await import(&quot;wavesurfer.js&quot;);<br>    }<br>  }<br><br>  async function handlePlayPause() {<br>    // If already loaded, just toggle play/pause<br>    if (wavesurferRef.current) {<br>      wavesurferRef.current.playPause();<br>      return;<br>    }<br><br>    // First time: load and play<br>    setIsLoading(true);<br>    setError(null);<br><br>    try {<br>      // Load library if not preloaded<br>      await preloadWaveSurfer();<br><br>      const WaveSurfer = wavesurferLibRef.current.default;<br><br>      wavesurferRef.current = WaveSurfer.create({<br>        container: waveformRef.current,<br>        waveColor: &quot;#4F4A85&quot;,<br>        progressColor: &quot;#383351&quot;,<br>        url: audioUrl,<br>        height: 80,<br>        barWidth: 2,<br>        barRadius: 3,<br>      });<br><br>      wavesurferRef.current.on(&quot;ready&quot;, () =&gt; {<br>        setIsLoading(false);<br>        // Auto-play after loading<br>        wavesurferRef.current.play();<br>      });<br><br>      wavesurferRef.current.on(&quot;play&quot;, () =&gt; setIsPlaying(true));<br>      wavesurferRef.current.on(&quot;pause&quot;, () =&gt; setIsPlaying(false));<br>      wavesurferRef.current.on(&quot;finish&quot;, () =&gt; setIsPlaying(false));<br><br>      wavesurferRef.current.on(&quot;error&quot;, (err) =&gt; {<br>        setError(err.message);<br>        setIsLoading(false);<br>      });<br>    } catch (err) {<br>      setError(&quot;Failed to load audio player&quot;);<br>      setIsLoading(false);<br>    }<br>  }<br><br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      if (wavesurferRef.current) {<br>        wavesurferRef.current.destroy();<br>        wavesurferRef.current = null;<br>      }<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div<br>        ref={waveformRef}<br>        style={{<br>          height: &quot;80px&quot;,<br>          backgroundColor: &quot;#f0f0f0&quot;,<br>          borderRadius: &quot;4px&quot;,<br>          marginBottom: &quot;10px&quot;,<br>        }}<br>      /&gt;<br><br>      {error &amp;&amp; &lt;p style={{ color: &quot;red&quot; }}&gt;Error: {error}&lt;/p&gt;}<br><br>      &lt;button<br>        onClick={handlePlayPause}<br>        onMouseEnter={preloadWaveSurfer}<br>        disabled={isLoading}<br>        style={{<br>          padding: &quot;10px 20px&quot;,<br>          fontSize: &quot;16px&quot;,<br>          cursor: isLoading ? &quot;not-allowed&quot; : &quot;pointer&quot;,<br>          opacity: isLoading ? 0.6 : 1,<br>        }}<br>      &gt;<br>        {isLoading ? &quot;Loading...&quot; : isPlaying ? &quot;⏸️ Pause&quot; : &quot;▶️ Play&quot;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>🗺️ Example 3: Display charts with <em>charts.js</em></strong></p><pre>// src/app/dashboard/page.js (Server Component)<br><br>import ChartSection from &quot;@/components/ChartSection&quot;;<br><br>export default function DashboardPage() {<br>  // Here you could fetch audio metadata from an API<br><br>  return (<br>    &lt;div&gt;<br>      {/* Client Component for interactive part */}<br>      &lt;ChartSection /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// src/components/ChartSection.tsx<br>&quot;use client&quot;;<br><br>import { useState, useRef, useEffect } from &quot;react&quot;;<br><br>export default function ChartSection() {<br>  const [showChart, setShowChart] = useState(false);<br>  const [isLoading, setIsLoading] = useState(false);<br>  const chartRef = useRef(null);<br>  const chartInstanceRef = useRef(null);<br>  const chartLibRef = useRef(null);<br><br>  // Create chart after canvas is rendered<br>  useEffect(() =&gt; {<br>    if (<br>      showChart &amp;&amp;<br>      chartRef.current &amp;&amp;<br>      !chartInstanceRef.current &amp;&amp;<br>      chartLibRef.current<br>    ) {<br>      createChart();<br>    }<br>  }, [showChart]);<br><br>  // Load Chart.js library<br>  async function loadChartLibrary() {<br>    if (chartLibRef.current) return chartLibRef.current;<br><br>    const chartModule = await import(&quot;chart.js&quot;);<br>    chartModule.Chart.register(...chartModule.registerables);<br>    chartLibRef.current = chartModule;<br>    return chartModule;<br>  }<br><br>  async function loadChart() {<br>    if (chartInstanceRef.current) return; // Already loaded<br><br>    setShowChart(true);<br>    setIsLoading(true);<br><br>    try {<br>      // ✨ Dynamic Import - The core technique<br>      await loadChartLibrary();<br><br>      // The actual chart creation will happen in the useEffect<br>      // after the canvas is rendered<br>    } catch (error) {<br>      console.error(&quot;Failed to load chart:&quot;, error);<br>    } finally {<br>      setIsLoading(false);<br>    }<br>  }<br><br>  // Create chart once canvas and library are ready<br>  function createChart() {<br>    if (!chartRef.current || !chartLibRef.current) return;<br><br>    try {<br>      // Create the chart<br>      chartInstanceRef.current = new chartLibRef.current.Chart(<br>        chartRef.current,<br>        {<br>          type: &quot;bar&quot;,<br>          data: {<br>            labels: [&quot;Jan&quot;, &quot;Feb&quot;, &quot;Mar&quot;, &quot;Apr&quot;, &quot;May&quot;],<br>            datasets: [<br>              {<br>                label: &quot;Sales (€)&quot;,<br>                data: [1200, 1900, 800, 1500, 2200],<br>                backgroundColor: &quot;rgba(54, 162, 235, 0.2)&quot;,<br>                borderColor: &quot;rgba(54, 162, 235, 1)&quot;,<br>                borderWidth: 2,<br>              },<br>            ],<br>          },<br>          options: {<br>            responsive: true,<br>            scales: {<br>              y: { beginAtZero: true },<br>            },<br>          },<br>        }<br>      );<br>    } catch (error) {<br>      console.error(&quot;Failed to create chart:&quot;, error);<br>    }<br>  }<br><br>  // Preload Chart.js on hover<br>  async function preloadChart() {<br>    try {<br>      await loadChartLibrary();<br>    } catch (error) {<br>      console.error(&quot;Failed to preload chart:&quot;, error);<br>    }<br>  }<br><br>  // Cleanup when component is destroyed<br>  useEffect(() =&gt; {<br>    return () =&gt; {<br>      if (chartInstanceRef.current) {<br>        chartInstanceRef.current.destroy();<br>      }<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div style={{ padding: &quot;20px&quot;, maxWidth: &quot;600px&quot; }}&gt;<br>      &lt;h2&gt;Sales Dashboard&lt;/h2&gt;<br><br>      &lt;button<br>        onClick={loadChart}<br>        onMouseEnter={preloadChart}<br>        disabled={isLoading}<br>        style={{<br>          padding: &quot;10px 20px&quot;,<br>          fontSize: &quot;16px&quot;,<br>          backgroundColor: &quot;#007bff&quot;,<br>          color: &quot;white&quot;,<br>          border: &quot;none&quot;,<br>          borderRadius: &quot;4px&quot;,<br>          cursor: isLoading ? &quot;not-allowed&quot; : &quot;pointer&quot;,<br>          opacity: isLoading ? 0.6 : 1,<br>        }}<br>      &gt;<br>        {isLoading ? &quot;Loading Chart...&quot; : &quot;📊 Load Chart&quot;}<br>      &lt;/button&gt;<br><br>      {showChart &amp;&amp; (<br>        &lt;div style={{ marginTop: &quot;20px&quot;, height: &quot;400px&quot; }}&gt;<br>          &lt;canvas ref={chartRef} /&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4><strong>🚀 Conclusion</strong></h4><p>Dynamic imports are a simple yet powerful way to improve performance in Next.js. By loading code only when it’s truly needed — and anticipating user intent — you can significantly reduce initial load times without compromising interactivity.</p><p>The bundle size savings can be substantial:</p><ul><li><strong>Chart.js</strong>: <em>~200KB+</em> (charts and visualizations)</li><li><strong>Leaflet</strong>: <em>~145KB+</em> (interactive maps)</li><li><strong>WaveSurfer</strong>: <em>~30KB+</em> (audio waveform rendering)</li></ul><p>By dynamically importing these libraries, you can reduce your initial bundle by <strong>375KB+</strong> — that’s faster load times, especially on mobile networks, and a better user experience for everyone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hn-S_BS9tr7xeEjX4bI1pw.gif" /><figcaption>Visual examples of dynamic imports in action</figcaption></figure><h4><strong>Does Next.js Split Code by Page Automatically?</strong></h4><p>Yes. Next.js <strong>automatically splits your app by route</strong> — each page gets its own bundle. This means:</p><ul><li>Visiting <strong>/about</strong> won’t load code for <strong>/dashboard</strong></li><li>Navigation becomes faster</li><li>You get automatic lazy-loading for each page</li></ul><p>You don’t need to configure this — it’s built into both the <strong>Pages Router </strong>and the <strong>App Router</strong>.</p><h4><strong>Disabling SSR with next/dynamic</strong></h4><p>In some cases, you may want to load a component <strong>only in the browser</strong>, and skip rendering it on the server. Next.js allows this by using <strong>dynamic()</strong> with <strong>ssr: false</strong>.</p><p>This is especially useful when the component relies on browser-only APIs, uses external libraries that only run client-side, or simply doesn’t need to be pre-rendered on the server.</p><p>Here’s a quick example:</p><pre>&quot;use client&quot;;<br><br>import dynamic from &quot;next/dynamic&quot;;<br><br>const TrueClientComponent = dynamic(<br>  () =&gt; import(&quot;../components/TrueClientComponent&quot;),<br>  { ssr: false }<br>);<br><br>export default function ClientComponent() {<br>  return (<br>    &lt;div&gt;<br>      &lt;TrueClientComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By setting <strong>ssr: false</strong>, the component is never rendered on the server — it’s fully skipped during SSR and only loaded on the client.</p><blockquote><em>💡 </em><strong>Note (App Router)</strong></blockquote><blockquote><em>In the App Router, components marked </em><strong><em>”use client”</em></strong><em> </em><strong>are still rendered on the server</strong><em> by default. Setting </em><strong>ssr: false</strong><em> ensures the component is </em><strong>only executed in the browser</strong><em>, giving you true client-only behavior.</em></blockquote><h4><strong>Key Points to Remember</strong></h4><ol><li>Use dynamic imports to load <strong><em>“non-critical”</em></strong> code only when needed — for example: tabs, modals, or UI rendered conditionally.</li><li>Disable SSR <strong>(ssr: false)</strong> when a component depends on browser-only APIs such as <strong>window</strong>, <strong>document</strong>, or <strong>localStorage</strong>.</li><li>Next.js automatically splits pages and components into chunks to improve performance and load times.</li><li>Dynamically import large external libraries to reduce the size of your initial JavaScript bundle.</li></ol><blockquote><strong>Start small. Test your impact. Split only what makes sense.</strong></blockquote><blockquote>Not everything needs to be lazy-loaded — but knowing when and how can make a real difference.</blockquote><h4><strong>Useful Links</strong></h4><ul><li><a href="https://nextjs.org/docs/app/guides/lazy-loading">Next.js Documentation — Lazy Loading</a></li><li><a href="https://github.com/vercel/next.js/tree/canary/examples/with-dynamic-import">Official Example: Dynamic Imports</a></li></ul><blockquote><strong>⚠️ Just a note</strong></blockquote><blockquote>This article doesn’t claim to be exhaustive or perfect — if something seems off or outdated, feel free to dig deeper or let me know. Happy to hear from you :)</blockquote><p>🙏 <strong>Thanks for reading!</strong></p><p>If you found this useful or have feedback, feel free to reach out. Always happy to learn, and glad if it helped. And if it did, don’t hesitate to clap or share – really, thanks!</p><p>Find me on <a href="https://github.com/kiki-le-singe">https://github.com/kiki-le-singe</a> or <a href="https://x.com/kiki_le_singe">https://x.com/kiki_le_singe</a></p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=485dac08cd24" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/optimize-next-js-performance-with-smart-code-splitting-what-to-load-when-and-why-485dac08cd24">Optimize Next.js Performance with Smart Code Splitting: What to Load, When, and Why</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I’m not a writer, but I have ideas — and now, an open source EPUB optimizer! ️]]></title>
            <link>https://blog.stackademic.com/im-not-a-writer-but-i-have-ideas-and-now-an-open-source-epub-optimizer-%EF%B8%8F-eb1ec12f1a01?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb1ec12f1a01</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[self-publishing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[writing]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 13:05:30 GMT</pubDate>
            <atom:updated>2026-05-19T05:16:38.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>I’m not a writer, but I have ideas — and now, an open source EPUB optimizer! 📚🛠️</h3><blockquote>I’ve always had stories in my head. Now, with a bit of AI, a bit of code — and a lot of curiosity — I’m finally turning them into something real. Here’s how.</blockquote><p>Ever since I was a kid, inspired by everything around me — video games, books, movies, comics — I used to write little stories, random bits of narrative that didn’t always make sense, or even try to create my own comics (usually just two or three panels, or a single page… 😅). Sometimes, I’d come up with wild scenarios while playing with my toys. Honestly, I would have loved to write movie scripts! But let’s be real: I’m not a writer, I don’t know how to write, or craft beautiful literary sentences… but I do have ideas! And today, thanks to artificial intelligence, I can finally put them into words, structure them, and give them a proper shape. AI has become a precious teammate, helping me turn my ideas into text, organize my thoughts, and explore new ways of telling stories. Even if I’m still just a noob in the storytelling game 🤪, I’ve started writing a sci-fi book in my spare time — and I fully intend to publish it 🚀💪.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*YLPHPWRaxG8yUCLXnni9sw.png" /><figcaption>EPUB Optimizer in action: compressing, minifying an EPUB file step by step.</figcaption></figure><h4><strong>The importance of technical mastery in self-publishing</strong></h4><p>Publishing an ebook isn’t just about writing. There’s everything else… and it can quickly become a pain! Especially when, like me, you don’t know much about it and you go the self-publishing route — which, to be fair, also makes publishing easier by removing a lot of constraints imposed by traditional publishers. But it also means you have to make sure your final file is accessible, meets certain standards, is pleasant to read, and… lightweight! From what I’ve learned, many self-publishing platforms set file size limits or even charge based on the size of the book downloaded by readers. So, as an independent author, every megabyte counts — especially if, like me, you want to include several illustrations in your story.</p><p>That’s why I developed <a href="https://github.com/kiki-le-singe/epub-optimizer"><strong>EPUB Optimizer</strong></a>, an open source tool that lets me keep full control over optimizing and tweaking my EPUB files. Rather than relying on other services (which didn’t really do what I wanted, or that I couldn’t figure out how to use properly…), I wanted to understand (I still don’t get everything, but you learn as you go!), test, and customize every step of the process to get a final result that works for me.</p><h4><strong>My workflow: from writing to optimization</strong></h4><ol><li><strong>Writing and layout:</strong> I write my texts and insert my images in Pages on Mac, making sure to add a table of contents and set up the cover.</li><li><strong>Export:</strong> I export my book in EPUB format, choosing options for reflowable text, embedded fonts, and using the first page as the cover.</li><li><strong>Optimization:</strong> Thanks to EPUB Optimizer, I compress the HTML, CSS, images, fonts, and repackage the archive. The result, for example: a file that goes from 24 MB to 7 MB, with no perceptible loss in quality, and fully compatible with mainstream e-readers. There’s also an <a href="https://www.w3.org/publishing/epubcheck/">epubcheck</a> validation after optimization.</li><li><strong>Validation:</strong> I manually test the optimized file on Apple Books, Kindle Previewer, and other platforms to ensure the best possible reading experience.</li></ol><h4><strong>Why this project?</strong></h4><p><a href="https://github.com/kiki-le-singe/epub-optimizer"><strong>EPUB Optimizer</strong></a> was born out of my need for flexibility and the ability to customize my final output while optimizing the file as much as possible. I wanted to be able to:</p><ul><li><strong>Customize every step</strong> (for example, choose whether or not to include the cover in the table of contents — while still making it the first page — , adjust image quality, or automatically fix unclosed tags like &lt;span&gt;, &lt;img&gt;, etc.)</li><li><strong>Understand what’s happening under the hood</strong>, to avoid nasty surprises at publication time.</li><li><strong>Share this tool with others</strong> (at least with other coders, I guess…) who, like me, want to keep control over their digital creations.</li></ul><blockquote>Of course, <strong>the tool isn’t perfect and there’s surely more work to be done, </strong>but it already works very well for my needs and, I hope, can help others too.</blockquote><h4><strong>Main features</strong></h4><ul><li>Minification of HTML/XHTML and CSS</li><li>Smart compression and conversion of images (JPEG, PNG, SVG, etc.)</li><li>Optional resizing of images that are too large</li><li>Adds lazy loading for images</li><li>Repackages the EPUB archive</li><li>Automatic EPUB compliance validation (<a href="https://www.w3.org/publishing/epubcheck/">epubcheck</a>)</li><li>Modular scripts (just comment, remove, or add steps) to customize the process — some steps are very personal, but can be disabled or adapted to fit your needs and workflow</li></ul><p><a href="https://github.com/kiki-le-singe/epub-optimizer"><strong>This project</strong></a> is open source and evolving. I plan to use it for my own needs and, if it can interest or help anyone, I invite you to try it, adapt it to your own uses, and contribute to its improvement. Writing today is more collaborative than ever — whether it’s with other humans or with AI.</p><p>And if this tool or approach doesn’t suit you, there are other optimization solutions out there: the important thing is to find what fits your workflow and your creative goals best!</p><p><a href="https://github.com/kiki-le-singe/epub-optimizer"><strong>Try it yourself</strong></a></p><p>🛠 If you’re working on your own tools for self-publishing or writing with AI, I’d love to hear about it — feel free to connect or drop a comment!</p><blockquote><em>I like exploring ideas through code — and when something useful comes out of it, I’m happy to share it.</em><br><em>A while ago, I even built a small mobile app that lets ChatGPT generate short stories from a few keywords, just for fun.</em><br> 👉 <em>You can check it out here: </em><a href="https://medium.com/@aalbertini95_90842/a-small-project-using-chatgpt-from-openai-and-react-native-7346d4a76ae2">A small project using ChatGPT and React Native</a><br> 💻 <em>GitHub:</em> <a href="https://github.com/kiki-le-singe/tell-me-a-story-ai">github.com/kiki-le-singe/tell-me-a-story-ai</a></blockquote><h3>A message from our Founder</h3><p>Hey, <a href="https://linkedin.com/in/sunilsandhu">Sunil</a> here. I wanted to take a moment to thank you for reading until the end and for being a part of this community. Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? We don’t receive any funding, we do this to support the community.</p><p>If you want to show some love, please take a moment to follow me on <a href="https://linkedin.com/in/sunilsandhu">LinkedIn</a>, <a href="https://tiktok.com/@messyfounder">TikTok</a>, <a href="https://instagram.com/sunilsandhu">Instagram</a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/">weekly newsletter</a>. And before you go, don’t forget to clap and follow the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb1ec12f1a01" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/im-not-a-writer-but-i-have-ideas-and-now-an-open-source-epub-optimizer-%EF%B8%8F-eb1ec12f1a01">I’m not a writer, but I have ideas — and now, an open source EPUB optimizer! 📚🛠️</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use the Context API in React 18 vs. React 19]]></title>
            <link>https://javascript.plainenglish.io/a-comparative-look-at-how-to-use-the-context-api-in-react-18-vs-react-19-898cb2a367ff?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/898cb2a367ff</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Thu, 05 Sep 2024 15:02:54 GMT</pubDate>
            <atom:updated>2025-08-05T15:00:52.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>React 19 vs React 18 — What’s New in the Context API (with Practical Code Examples)</h3><p>In this article, we’ll compare how context is used in React 18 and React 19, focusing on these key improvements with examples.</p><h3>Recap: The Context API in React 18</h3><p>In React 18, the Context API is widely used for managing shared state across deeply nested components without the need for prop drilling. It follows a simple process:</p><ol><li>Create a context using createContext.</li><li>Wrap the component tree with the Provider of the context.</li><li>Access the context values inside child components using useContext.</li></ol><p>Here’s a more complex example in React 18 with a theme context that allows toggling between light and dark modes:</p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>// Create a ThemeContext<br>const ThemeContext = createContext();<br><br>// ThemeProvider component<br>const ThemeProvider = ({ children }) =&gt; {<br>  const [theme, setTheme] = useState({<br>    mode: &#39;light&#39;,<br>    colors: {<br>      background: &#39;#fff&#39;,<br>      text: &#39;#000&#39;,<br>    },<br>  });<br><br>  const toggleTheme = () =&gt; {<br>    setTheme((prevTheme) =&gt; {<br>      return prevTheme.mode === &#39;light&#39;<br>        ? {<br>            mode: &#39;dark&#39;,<br>            colors: {<br>              background: &#39;#333&#39;,<br>              text: &#39;#fff&#39;,<br>            },<br>          }<br>        : {<br>            mode: &#39;light&#39;,<br>            colors: {<br>              background: &#39;#fff&#39;,<br>              text: &#39;#000&#39;,<br>            },<br>          };<br>    });<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};<br><br>// Component consuming context<br>const ThemedComponent = () =&gt; {<br>  const { theme, toggleTheme } = useContext(ThemeContext);<br>  <br>  return (<br>    &lt;div style={{ background: theme.colors.background, color: theme.colors.text }}&gt;<br>      &lt;p&gt;Current Theme: {theme.mode}&lt;/p&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default function App() {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;ThemedComponent /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>}</pre><h3>React 19: Theme Context Example</h3><p>Here’s how you can refactor the previous theme context example using the new context provider shorthand in React 19:</p><pre>import React, { createContext, useState, use } from &#39;react&#39;;<br><br>// Create a ThemeContext<br>const ThemeContext = createContext();<br><br>// ThemeProvider component using &lt;ThemeContext&gt; directly as a provider<br>const ThemeProvider = ({ children }) =&gt; {<br>  const [theme, setTheme] = useState({<br>    mode: &#39;light&#39;,<br>    colors: {<br>      background: &#39;#fff&#39;,<br>      text: &#39;#000&#39;,<br>    },<br>  });<br><br>  const toggleTheme = () =&gt; {<br>    setTheme((prevTheme) =&gt; {<br>      return prevTheme.mode === &#39;light&#39;<br>        ? {<br>            mode: &#39;dark&#39;,<br>            colors: {<br>              background: &#39;#333&#39;,<br>              text: &#39;#fff&#39;,<br>            },<br>          }<br>        : {<br>            mode: &#39;light&#39;,<br>            colors: {<br>              background: &#39;#fff&#39;,<br>              text: &#39;#000&#39;,<br>            },<br>          };<br>    });<br>  };<br><br>  return (<br>    &lt;ThemeContext value={{ theme, toggleTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext&gt;<br>  );<br>};<br><br>// Consuming context using the `use` hook in React 19<br>const ThemedComponent = () =&gt; {<br>  const { theme, toggleTheme } = use(ThemeContext);<br>  <br>  return (<br>    &lt;div style={{ background: theme.colors.background, color: theme.colors.text }}&gt;<br>      &lt;p&gt;Current Theme: {theme.mode}&lt;/p&gt;<br>      &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default function App() {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;ThemedComponent /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>}</pre><h3>Key Improvements in React 19:</h3><ol><li><strong>Simpler Context Provider Syntax</strong>: Instead of wrapping components with &lt;ThemeContext.Provider&gt;, you can directly render &lt;ThemeContext&gt; as a provider.</li><li><strong>use Hook</strong>: The use hook can replace useContext and allows consuming context more flexibly. It also works well with asynchronous data, which wasn’t as easy to handle in React 18.</li></ol><h3>User Status Example in React 19</h3><p>Now, let’s look at another example where a user status context is used to manage login state.</p><pre>import React, { createContext, useState, use } from &#39;react&#39;;<br><br>// Create a UserContext<br>const UserContext = createContext();<br><br>// UserProvider component using &lt;UserContext&gt; directly as a provider<br>const UserProvider = ({ children }) =&gt; {<br>  const [user, setUser] = useState({<br>    name: &#39;Jane Doe&#39;,<br>    status: 1, // 1 -&gt; loggedIn, 0 -&gt; loggedOut<br>  });<br><br>  const logout = () =&gt; {<br>    setUser({ name: &#39;&#39;, status: 0 });<br>  };<br><br>  return (<br>    &lt;UserContext value={{ user, logout }}&gt;<br>      {children}<br>    &lt;/UserContext&gt;<br>  );<br>};<br><br>// UserStatus component consuming the UserContext<br>const UserStatus = ({show = true}) =&gt; {<br>  if (show) {<br>    const { user, logout } = use(UserContext);<br><br>    return (<br>      &lt;div&gt;<br>        {user.status === 1 ? (<br>          &lt;&gt;<br>            &lt;p&gt;Welcome, {user.name}!&lt;/p&gt;<br>            &lt;button onClick={logout}&gt;Logout&lt;/button&gt;<br>          &lt;/&gt;<br>        ) : (<br>          &lt;p&gt;You are logged out.&lt;/p&gt;<br>        )}<br>      &lt;/div&gt;<br>    );<br>  }<br><br>  return null;<br>};<br><br>// App component<br>export default function App() {<br>  return (<br>    &lt;UserProvider&gt;<br>      &lt;UserStatus /&gt;<br>    &lt;/UserProvider&gt;<br>  );<br>}</pre><p>You can see that <strong><em>use</em></strong> is called from inside a <strong><em>if</em></strong> statement, allowing you to conditionally read values from a Context.</p><h3>Bonus</h3><h4><a href="https://react.dev/reference/react/use">Use API:</a></h4><p>use(resource)</p><blockquote>use is a React API that lets you read the value of a resource like a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> or <a href="https://react.dev/learn/passing-data-deeply-with-context">context</a>.</blockquote><p>The following example shows a loading message while the user information is fetched.</p><pre>import { use } from &quot;react&quot;;<br><br>async function getUser() {<br>  const data = await fetchUser();<br>  return data.json();<br>}<br><br>function User() {<br>  const user = use(getUser);<br><br>  return (<br>    &lt;&gt;<br>      &lt;p&gt;{user.name}&lt;/p&gt;<br>      &lt;p&gt;{user.status}&lt;/p&gt;<br>    &lt;&gt;<br>  )<br>}<br><br>function Page() {<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;User /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><blockquote>If this helped you, feel free to leave a few claps or follow — always appreciated 🙂You can also check out my <a href="https://github.com/kiki-le-singe"><strong>GitHub</strong></a> to see what I’m up to.<br>Have a great day and happy coding! 🚀</blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=898cb2a367ff" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/a-comparative-look-at-how-to-use-the-context-api-in-react-18-vs-react-19-898cb2a367ff">How to Use the Context API in React 18 vs. React 19</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Refs: A Deep Dive into an Essential Tool for React Developers]]></title>
            <link>https://javascript.plainenglish.io/react-refs-a-deep-dive-into-an-essential-tool-for-react-developers-da25f7d010da?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/da25f7d010da</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Sun, 01 Sep 2024 18:48:34 GMT</pubDate>
            <atom:updated>2025-08-05T15:02:13.898Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Use useRef in React (And Why It’s More Useful Than You Think)</h3><p>Refs in React are a powerful feature that don’t always get the spotlight they deserve. We all know the famous hooks like <a href="https://react.dev/reference/react/useState"><strong><em>useState</em></strong></a> and <a href="https://react.dev/reference/react/useEffect"><strong><em>useEffect</em></strong></a> but <a href="https://react.dev/reference/react/useRef"><strong><em>useRef</em></strong></a><strong><em> </em></strong>is more reserved. In this article, we’ll explore what refs are, how they work, and when you might want to use them in your React applications. We’ll also cover some use cases where refs can be really useful.</p><p><strong>From the React documentation:</strong></p><blockquote>When you want a component to “remember” some information, but you don’t want that information to trigger new renders, you can use a ref.</blockquote><blockquote><strong>useRef </strong>is a React Hook that lets you reference a value that’s not needed for rendering.</blockquote><h4><strong>What Exactly is a Ref in React?</strong></h4><p>In simple terms, a ref (short for reference) is a way to access and interact with DOM elements or React components directly. When a ref is attached to a React element, it provides a way to reference that element in the real DOM. This can be particularly useful when you need to perform imperative operations, such as managing focus, text selection, or triggering animations.</p><p>Refs are created using the <strong>useRef</strong> hook. Once created, you can attach a ref to an element via the <strong>ref</strong> attribute, and React will populate the ref object with the DOM element whenever the component mounts.</p><h4>Creating and Using Refs in Function Components</h4><p>Let’s start with an example of how to create and use a ref in a function component. We’ll build a simple form where the input field is automatically focused when the component mounts.</p><pre>import React, { useRef, useEffect } from &#39;react&#39;;<br><br>function AutoFocusInput() {<br>  const inputRef = useRef(null);<br><br>  useEffect(() =&gt; {<br>    if (inputRef.current) {<br>      inputRef.current.focus();<br>    }<br>  }, []);<br><br>  return &lt;input ref={inputRef} type=&quot;text&quot; placeholder=&quot;Focus on me!&quot; /&gt;;<br>}<br><br>export default AutoFocusInput;</pre><h3>Breakdown of the Code:</h3><ul><li><strong>useRef</strong>: We use the useRef hook to create a ref. It returns a mutable object with a .current property, which we can assign to our input element.</li><li><strong>useEffect</strong>: Once the component mounts, useEffect triggers, ensuring the input element is focused. We add a safety check to ensure the element exists before trying to focus it.</li></ul><h3>Advanced Use Cases for Refs:</h3><h3>1. Storing Previous Values with a Custom Hook</h3><p>Refs can be incredibly useful for storing the previous state or prop values without triggering a re-render. This can be particularly useful for implementing custom hooks or for comparing previous and current values in a component.</p><pre>import { useRef, useEffect } from &#39;react&#39;;<br><br>function usePrevious(value) {<br>  const ref = useRef();<br><br>  useEffect(() =&gt; {<br>    ref.current = value;<br>  }, [value]);<br><br>  return ref.current;<br>}<br><br>function MyComponent({ count }) {<br>  const prevCount = usePrevious(count);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Current Count: {count}&lt;/p&gt;<br>      &lt;p&gt;Previous Count: {prevCount}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MyComponent;</pre><h3>Breakdown of the Code:</h3><ul><li>Custom Hook (<strong>usePrevious</strong>): This hook encapsulates the logic of storing the previous value of a prop or state, enhancing code reuse and readability.</li></ul><h3>2. Controlling Child Component Instances with useImperativeHandle</h3><p>Refs can also be used to control and interact with child component instances, particularly when those components expose certain methods that need to be triggered by the parent. Using <strong>useImperativeHandle</strong> in conjunction with <strong>React.forwardRef</strong> gives you fine-grained control over what gets exposed to the parent.</p><pre>import React, { useRef, useImperativeHandle, forwardRef } from &#39;react&#39;;<br><br>const ChildComponent = forwardRef((props, ref) =&gt; {<br>  useImperativeHandle(ref, () =&gt; ({<br>    alertMessage() {<br>      alert(&#39;Hello from the Child Component!&#39;);<br>    }<br>  }));<br><br>  return &lt;button onClick={() =&gt; alert(&#39;Hello from the Child Component!&#39;)}&gt;Click me or call me from Parent&lt;/button&gt;;<br>});<br><br>function ParentComponent() {<br>  const childRef = useRef();<br><br>  const handleClick = () =&gt; {<br>    if (childRef.current) {<br>      childRef.current.alertMessage();<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ChildComponent ref={childRef} /&gt;<br>      &lt;button onClick={handleClick}&gt;Call Child Method&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ParentComponent;</pre><h3>Breakdown of the Code:</h3><ul><li><strong>React.forwardRef</strong>: Used to pass refs to a functional component.</li><li><strong>useImperativeHandle</strong>: Controls what is exposed to the parent when the ref is used, improving encapsulation and reducing the risk of exposing too much internal detail.</li></ul><h4>Note:</h4><blockquote>In <strong>React 19</strong>, new function components will no longer need forwardRef, and we will be publishing a codemod to automatically update your components to use the new ref prop. In future versions we will deprecate and remove forwardRef.</blockquote><p><a href="https://fr.react.dev/blog/2024/04/25/react-19#ref-as-a-prop"><strong>ref as a prop:</strong></a></p><p><em>(The revisited example above)</em></p><pre>import React, { useRef, useImperativeHandle} from &#39;react&#39;;<br><br>const ChildComponent = (props, ref) =&gt; {<br>  useImperativeHandle(ref, () =&gt; ({<br>    alertMessage() {<br>      alert(&#39;Hello from the Child Component!&#39;);<br>    }<br>  });<br><br>  return &lt;button onClick={() =&gt; alert(&#39;Hello from the Child Component!&#39;)}&gt;Click me or call me from Parent&lt;/button&gt;;<br>});<br><br>function ParentComponent() {<br>  const childRef = useRef();<br><br>  const handleClick = () =&gt; {<br>    if (childRef.current) {<br>      childRef.current.alertMessage();<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;ChildComponent ref={childRef} /&gt;<br>      &lt;button onClick={handleClick}&gt;Call Child Method&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ParentComponent;</pre><p><em>(This is a simple example)</em></p><pre>function CustomInput({ placeholder, ref }) {<br>  return &lt;input placeholder={placeholder} ref={ref} /&gt;;<br>}<br><br>// ...<br><br>&lt;CustomInput ref={ref} /&gt;;</pre><p><a href="https://fr.react.dev/blog/2024/04/25/react-19#cleanup-functions-for-refs"><strong>cleanup functions for refs:</strong></a></p><pre>&lt;input<br>  ref={(ref) =&gt; {<br>    // ref created<br><br>    // NEW: return a cleanup function to reset<br>    // the ref when element is removed from DOM.<br>    return () =&gt; {<br>      // ref cleanup<br>    };<br>  }}<br>/&gt;</pre><h3>3. Measuring DOM Elements with Safety Checks</h3><p>Another common use case for refs is to manipulate or measure DOM elements directly. This can be useful in scenarios where you need to work with third-party libraries that require direct DOM access.</p><pre>import React, { useRef, useEffect } from &#39;react&#39;;<br><br>function MeasureElement() {<br>  const divRef = useRef();<br><br>  useEffect(() =&gt; {<br>    const divElement = divRef.current;<br>    if (divElement) {<br>      console.log(&#39;Element width:&#39;, divElement.offsetWidth);<br>      console.log(&#39;Element height:&#39;, divElement.offsetHeight);<br>    }<br>  }, []);<br><br>  return &lt;div ref={divRef} style={{ width: &#39;100px&#39;, height: &#39;100px&#39;, backgroundColor: &#39;lightblue&#39; }}&gt;Measure me!&lt;/div&gt;;<br>}<br><br>export default MeasureElement;</pre><h3>Breakdown of the Code:</h3><ul><li><strong>Measuring DOM elements</strong>: We attach a ref to a div element and use the offsetWidth and offsetHeight properties to measure the element’s dimensions after the component mounts, with added checks to ensure safety.</li></ul><h3>4. Persisting Mutable Values in a Timer Example</h3><p>Refs can be used to store mutable values that persist across renders but don’t trigger a re-render when updated. This is useful for keeping track of variables that may change, such as timers, counters, or other external states.</p><pre>import React, { useRef } from &#39;react&#39;;<br><br>function TimerComponent() {<br>  const timerIdRef = useRef();<br><br>  const startTimer = () =&gt; {<br>    if (!timerIdRef.current) {<br>      timerIdRef.current = setInterval(() =&gt; {<br>        console.log(&#39;Timer running...&#39;);<br>      }, 1000);<br>    }<br>  };<br><br>  const stopTimer = () =&gt; {<br>    if (timerIdRef.current) {<br>      clearInterval(timerIdRef.current);<br>      timerIdRef.current = null;<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={startTimer}&gt;Start Timer&lt;/button&gt;<br>      &lt;button onClick={stopTimer}&gt;Stop Timer&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default TimerComponent;</pre><h3>Breakdown of the Code:</h3><ul><li><strong>Persisting timers:</strong> We store a timer ID in a ref, allowing us to start and stop the timer without affecting the component’s rendering cycle.</li></ul><h3>Wrapping Up</h3><p>Refs are a powerful and sometimes underappreciated feature in React. They allow you to step outside the declarative nature of React when necessary, providing you with a direct line to the DOM and component instances. However, with great power comes great responsibility. Always consider whether you could solve your problem with props, state, or context before reaching for refs.</p><p>Whether you’re managing focus, storing previous values, or triggering child component methods, refs offer a flexible and efficient way to interact with your React components. The examples above demonstrate how to use refs in a way that aligns with modern React practices, ensuring your code remains clean, maintainable, and performant.</p><p>For a more in-depth understanding, consider reviewing the official React documentation on <a href="https://react.dev/reference/react/useRef"><strong>useRef</strong></a> , the <a href="https://react.dev/learn/referencing-values-with-refs#differences-between-refs-and-state"><strong>differences between refs and state</strong></a><strong>, </strong><a href="https://react.dev/learn/referencing-values-with-refs"><strong>Referencing Values with Refs</strong></a><strong> and </strong><a href="https://react.dev/learn/manipulating-the-dom-with-refs"><strong>Manipulating the DOM with Refs</strong></a><strong>. These </strong>resources provide additional insights and examples to help you use refs more effectively in your applications.</p><blockquote>If this helped you, feel free to leave a few claps or follow — always appreciated 🙂You can also check out my <a href="https://github.com/kiki-le-singe"><strong>GitHub</strong></a> to see what I’m up to.<br>Have a great day and happy coding! 🚀</blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da25f7d010da" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-refs-a-deep-dive-into-an-essential-tool-for-react-developers-da25f7d010da">React Refs: A Deep Dive into an Essential Tool for React Developers</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next.js, TailwindCSS, NestJS, Turborepo…Modern Web Development]]></title>
            <link>https://javascript.plainenglish.io/exploring-modern-web-development-an-nft-marketplace-with-turborepo-next-js-3676e1f6fe29?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/3676e1f6fe29</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Wed, 22 May 2024 16:26:00 GMT</pubDate>
            <atom:updated>2025-08-05T15:01:11.957Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Fullstack Monorepo with Turborepo, Next.js, NestJS &amp; TailwindCSS</h3><p>GitHub Project: <a href="https://github.com/kiki-le-singe/nft-marketplace"><strong><em>NFT Marketplace</em></strong></a></p><p>I started this project mainly for fun. So it’s not perfect! 😅 I wanted to learn and experiment with a few modern tools: <a href="https://turbo.build/repo"><strong><em>Turborepo</em></strong></a><strong><em> for monorepo structure</em></strong>, <a href="https://nextjs.org/"><strong><em>Next.js</em></strong></a><strong><em> </em></strong>for the frontend, <a href="https://nestjs.com/"><strong><em>NestJS</em></strong></a><strong><em> for the backend</em></strong>, <a href="https://www.prisma.io/"><strong><em>Prisma</em></strong></a><strong><em> for the database layer</em></strong>, <a href="https://tailwindcss.com/"><strong><em>tailwindcss</em></strong></a><strong><em> for styling</em></strong>... Everything is written in TypeScript, with shared types, a common ESLint config, and reusable UI components across apps and packages.</p><p>I created a simple, fake, responsive application using this <a href="https://www.figma.com/community/file/1173962104946517060/nft-marketplace-template-create-an-nft-website-in-minutes"><strong><em>NFT Marketplace</em></strong></a> template from <a href="https://www.figma.com/@anima"><strong><em>Anima</em></strong></a>. For the images I used <strong><em>DALL.E</em></strong>.</p><p>It’s not a real product, but the code is deployable and structured, with a few best practices baked in.</p><p>Hopefully it helps others get started faster – or sparks some curiosity.</p><p>Enjoy it! And let me know :)</p><p>Here is what the application looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*SBUkonMR9RFSDLCzTSy_Ew.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ei6or4U7NlzyCYpdu-AB5Q.gif" /></figure><p><strong>## Requirements</strong></p><p>- <a href="http://nodejs.org/"><strong><em>nodejs</em></strong></a><br>- <a href="https://pnpm.io/"><strong><em>pnpm</em></strong></a> (you can use another package manager, but <strong><em>pnpm</em></strong> is recommended. Personally, I use it for this project)<br>- <a href="https://yarnpkg.com/"><strong><em>Yarn</em></strong></a><br>- <a href="https://www.npmjs.com/"><strong><em>npm</em></strong></a></p><p>This is my configuration at the time of writing this README:</p><p>- Node <strong><em>22.1.0</em></strong><br>- pnpm <strong><em>9.0.6</em></strong><br>- yarn <strong><em>1.22.22</em></strong><br>- npm <strong><em>10.7.0</em></strong></p><p>If you don’t know some tools used in this project, you can check the following links:</p><ul><li><a href="https://turbo.build/repo/docs"><strong><em>Turborepo Quickstart</em></strong></a><br>- <a href="https://nextjs.org/docs"><strong><em>Next.js</em></strong></a><br>- <a href="https://tailwindcss.com/"><strong><em>tailwindcss</em></strong></a><br>- <a href="https://www.framer.com/motion/"><strong><em>Framer Motion</em></strong></a><br>- <a href="https://docs.nestjs.com/"><strong><em>NestJS</em></strong></a><br>- <a href="https://www.prisma.io/"><strong><em>Prisma</em></strong></a></li></ul><p><strong>## Package Manager</strong></p><p><a href="https://turbo.build/repo/docs/getting-started/create-new#which-package-manager-do-you-want-to-use"><strong><em>Which package manager do you want to use?</em></strong></a></p><p>Turborepo doesn’t handle installing packages, so you’ll need to choose one of:</p><p>- <a href="https://pnpm.io/"><strong><em>pnpm</em></strong></a> (<strong><em>Turborepo</em></strong> recommends <strong><em>pnpm</em></strong>)<br>- <a href="https://yarnpkg.com/"><strong><em>Yarn</em></strong></a><br>- <a href="https://www.npmjs.com/"><strong><em>npm</em></strong></a></p><p><strong>## Installation</strong></p><pre>$ git clone https://github.com/kiki-le-singe/nft-marketplace.git &lt;name&gt;<br>$ cd &lt;name&gt;</pre><p><strong><em>Warning</em></strong> If you use <strong><em>yarn</em></strong> or <strong><em>npm</em></strong>, you need to update the <strong><em>package.json</em></strong> file in the root of the project and use your version of <strong><em>yarn</em></strong> or <strong><em>npm</em></strong>:</p><pre>{<br> &quot;packageManager&quot;: &quot;yarn@1.22.22&quot;,<br> &quot;workspaces&quot;: [&quot;apps/*&quot;, &quot;packages/*&quot;]<br>}</pre><p>or</p><pre>{<br> &quot;packageManager&quot;: &quot;npm@10.7.0&quot;,<br> &quot;workspaces&quot;: [&quot;apps/*&quot;, &quot;packages/*&quot;]<br>}</pre><p>You must to replace all <strong><em>“workspace:*”</em></strong> by <strong><em>“*”</em></strong> inside the <strong><em>package.json</em></strong> files in the <strong><em>apps</em></strong>, <strong><em>packages</em></strong> and the root of the project. Indeed, only <strong><em>pnpm</em></strong> uses the <strong><em>workspace</em></strong> keyword.</p><p>When your package manager is set, you can go to the <strong><em>apps/api</em></strong> and add a <strong><em>.env</em></strong> file with the following content: <strong><em>DATABASE_URL=”file:./dev.db”</em></strong></p><p>Go to the root of the project and run the following command:</p><pre>$ pnpm|yarn|npm install</pre><p><strong>## Run</strong></p><pre>$ pnpm|yarn|npm dev (to run all the apps)</pre><p>If you want to run the apps separately:</p><pre>$ pnpm|yarn|npm dev - filter api (port 3002)<br>$ pnpm|yarn|npm dev - filter web (port 3000)<br>$ pnpm|yarn|npm dev - filter docs (port 3001)</pre><p>Inside <strong><em>apps/api</em></strong> to see the database in the browser <strong><em>(port 5555)</em></strong>:</p><pre>$ npx prisma studio</pre><p>For production:</p><pre>$ pnpm|yarn|npm build</pre><p>Then go to the root of <strong><em>apps/[api|docs|web]</em></strong> and run:</p><pre>$ pnpm|yarn|npm start</pre><p>Then open <a href="http://localhost:3002/"><strong><em>localhost:3002</em></strong></a> for the api, <a href="http://localhost:3000/"><strong><em>localhost:3000</em></strong></a> for the web and <a href="http://localhost:3001/"><strong><em>localhost:3001</em></strong></a> for the docs if the web app is already running.</p><p><strong><em>Be careful</em></strong><br>If you have run this script <strong><em>pnpm|yarn|npm dev</em></strong>, the docs app could be running before the web app. In this case, the docs app will be on <a href="http://localhost:3000/"><strong><em>localhost:3000</em></strong></a> and the web app on <a href="http://localhost:3001/"><strong><em>localhost:3001</em></strong></a></p><p><strong>## API</strong></p><p>For the api, there are some routes available:</p><p>- <a href="http://localhost:3002/"><strong><em>localhost:3002</em></strong></a> list some images served by the api.<br>- <a href="http://localhost:3002/api"><strong><em>localhost:3002/api</em></strong></a> the starting point of the api.<br>- <a href="http://localhost:3002/api/creations/1"><strong><em>localhost:3002/api/creations/:id</em></strong></a> return the creation with the id <strong><em>1</em></strong>.<br>- <a href="http://localhost:3002/api/creations/explore"><strong><em>localhost:3002/api/creations/explore</em></strong></a> return the creations to explore.<br>- <a href="http://localhost:3002/api/categories"><strong><em>localhost:3002/api/categories</em></strong></a> return all the categories.<br>- <a href="http://localhost:3002/api/categories/trending"><strong><em>localhost:3002/api/categories/trending</em></strong></a> return the trending categories.<br>- <a href="http://localhost:3002/api/users"><strong><em>localhost:3002/api/users</em></strong></a> return all the users.</p><p><strong>## Features</strong></p><ul><li><strong>Monorepo with Turborepo</strong></li><li><strong>Next.js for the web and docs apps</strong>:</li><li><em>App Router (Features available in /app)</em></li><li><em>SSR</em></li><li><em>Data Fetching on the server side using </em><a href="https://nextjs.org/docs/app/building-your-application/data-fetching/patterns#streaming"><strong><em>streaming</em></strong></a><em> and </em><a href="https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming"><strong><em>Loading UI and Streaming</em></strong></a></li><li><em>Dynamic imports </em><a href="https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading"><strong><em>Lazy Loading</em></strong></a></li><li><strong>tailwindcss</strong></li><li><strong>Responsive Design</strong></li><li><strong>animations (hover, click, etc.)</strong></li><li><strong>skeleton loading </strong><a href="https://nextjs.org/learn/dashboard-app/streaming#adding-loading-skeletons"><strong><em>Adding loading skeletons</em></strong></a></li><li><strong>Modal with Parallel and Intercepting Routes</strong>:</li><li><a href="https://nextjs.org/docs/app/building-your-application/routing/parallel-routes#modals"><em>Parallel Routes: Modals</em></a></li><li><a href="https://nextjs.org/docs/app/building-your-application/routing/intercepting-routes#modals"><em>Intercepting Routes: Modals</em></a></li><li><strong>NestJS for the api app</strong></li><li><strong>Prisma for the database</strong></li></ul><p><strong>## [WIP] Features to come (maybe…)</strong></p><p>-authentification<br>- improve the API<br>- Dark/Light mode<br>- SEO (metadata, etc.)<br>- i18n<br>- a11y<br>- tests (unit and e2e)<br>- performance optimization (images, etc.)</p><p><strong># Turborepo starter</strong></p><p>This is an official starter Turborepo.</p><p><strong>## Using this example</strong></p><p>Run the following command:</p><pre>npx create-turbo@latest</pre><p><strong>## What’s inside?</strong></p><p>This Turborepo includes the following packages/apps:</p><p><strong>### Apps and Packages</strong></p><p>- <strong><em>api</em></strong>: a <a href="https://nestjs.com/"><strong><em>NestJS</em></strong></a> app<br>- <strong><em>docs</em></strong>: a <a href="https://nextjs.org/"><strong><em>Next.js</em></strong></a> app<br>- <strong><em>web</em></strong>: another <a href="https://nextjs.org/"><strong><em>Next.js</em></strong></a> app<br>- <strong><em>ui</em></strong>: a stub React component library shared by both <strong><em>web</em></strong> and <strong><em>docs</em></strong> applications<br>- <strong><em>eslint-config-custom</em></strong>: <strong><em>eslint</em></strong> configurations (includes <strong><em>eslint-config-next</em></strong> and <strong><em>eslint-config-prettier</em></strong>)<br>- <strong><em>tsconfig</em></strong>: <strong><em>tsconfig.json</em></strong>`s used throughout the monorepo</p><p>Each package/app is 100% <a href="https://www.typescriptlang.org/"><strong><em>TypeScript</em></strong></a>.</p><p><strong>### Utilities</strong></p><p>This Turborepo has some additional tools already setup for you:</p><p>- <a href="https://www.typescriptlang.org/"><strong><em>TypeScript</em></strong></a> for static type checking<br>- <a href="https://eslint.org/"><strong><em>ESLint</em></strong></a> for code linting<br>- <a href="https://prettier.io/"><strong><em>Prettier</em></strong></a> for code formatting</p><p><strong>### Build</strong></p><p>To build all apps and packages, run the following command:</p><pre>cd my-turborepo<br>pnpm build</pre><p><strong>### Develop</strong></p><p>To develop all apps and packages, run the following command:</p><pre>cd my-turborepo<br>pnpm dev</pre><p><strong>### Remote Caching</strong></p><p>Turborepo can use a technique known as <a href="https://turbo.build/repo/docs/core-concepts/remote-caching"><strong><em>Remote Caching</em></strong></a> to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.</p><p>By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don’t have an account you can <a href="https://vercel.com/signup"><strong><em>create one</em></strong></a>, then enter the following commands:</p><pre>cd my-turborepo<br>npx turbo login</pre><p>This will authenticate the Turborepo CLI with your <a href="https://vercel.com/docs/concepts/personal-accounts/overview"><strong><em>Vercel account</em></strong></a>.</p><p>Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:</p><pre>npx turbo link</pre><p><strong>## Useful Links</strong></p><p>Learn more about the power of Turborepo:</p><p>- <a href="https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks"><strong><em>Tasks</em></strong></a><br>- <a href="https://turbo.build/repo/docs/core-concepts/caching"><strong><em>Caching</em></strong></a><br>- <a href="https://turbo.build/repo/docs/core-concepts/remote-caching"><strong><em>Remote Caching</em></strong></a><br>- <a href="https://turbo.build/repo/docs/core-concepts/monorepos/filtering"><strong><em>Filtering</em></strong></a><br>- <a href="https://turbo.build/repo/docs/reference/configuration"><strong><em>Configuration Options</em></strong></a><br>- <a href="https://turbo.build/repo/docs/reference/command-line-reference"><strong><em>CLI Usage</em></strong></a><br>- <a href="https://turbo.build/repo/docs/handbook/package-installation"><strong><em>Package Installation</em></strong></a><br>- <a href="https://turbo.build/repo/docs/handbook/workspaces"><strong><em>Workspaces</em></strong></a><br>- <a href="https://www.prisma.io/nestjs"><strong><em>Prisma and NestJS</em></strong></a><br>- <a href="https://docs.nestjs.com/recipes/prisma"><strong><em>NestJS Recipes Prisma</em></strong></a><br>- <a href="https://docs.nestjs.com/recipes/prisma#install-and-generate-prisma-client"><strong><em>NestJS/Prisma — Install and generate Prisma Client</em></strong></a></p><blockquote>If this helped you, feel free to leave a few claps or follow — always appreciated 🙂You can also check out my <a href="https://github.com/kiki-le-singe"><strong>GitHub</strong></a> to see what I’m up to.<br>Have a great day and happy coding! 🚀</blockquote><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 200k supporters? <strong>We do not get paid by Medium</strong>!</p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a><strong> and </strong><a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3676e1f6fe29" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/exploring-modern-web-development-an-nft-marketplace-with-turborepo-next-js-3676e1f6fe29">Next.js, TailwindCSS, NestJS, Turborepo…Modern Web Development</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A small project using ChatGPT from OpenAI and React Native]]></title>
            <link>https://medium.com/@aalbertini95_90842/a-small-project-using-chatgpt-from-openai-and-react-native-7346d4a76ae2?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/7346d4a76ae2</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 16:21:50 GMT</pubDate>
            <atom:updated>2024-08-31T14:09:27.660Z</atom:updated>
            <content:encoded><![CDATA[<h3>Tell me a story… With ChatGPT from OpenAI and React Native</h3><p><strong># Introduction</strong></p><blockquote>I started this <a href="https://github.com/kiki-le-singe/tell-me-a-story-ai"><strong>project</strong></a> mainly to play with <a href="https://chat.openai.com/"><strong>ChatGPT</strong></a> from <a href="https://openai.com/"><strong>OpenAI</strong></a>. It’s a small app that allows you to write a story using the <a href="https://platform.openai.com/docs/api-reference"><strong>OpenAI API</strong></a>. There are some predefined stories to help your inspiration, and you can also write your own story.</blockquote><p><a href="https://github.com/kiki-le-singe/tell-me-a-story-ai">GitHub - kiki-le-singe/tell-me-a-story-ai</a></p><p>This app uses these following API:</p><ul><li><a href="https://platform.openai.com/docs/api-reference/images/create"><strong>Create image</strong></a></li><li><a href="https://platform.openai.com/docs/api-reference/completions/create"><strong>Create completion</strong></a></li><li><a href="https://platform.openai.com/docs/api-reference/audio/create">Create transcription</a></li></ul><p>Enjoy it! :)</p><p>This app has four screens:</p><ul><li>A tutorial interface that introduces the app.</li><li>A simple screen that displays the users who have created pictures and illustrations.</li><li>The screen that allows you to write a predefined story.</li><li>The screen that allows you to write your own story.</li></ul><figure><img alt="Tell Me A Story App" src="https://cdn-images-1.medium.com/max/444/1*fugbK6ARWwboFVVAG1Knjg.gif" /></figure><figure><img alt="How to write your own story" src="https://cdn-images-1.medium.com/max/444/1*ArXxOt-_EOt2Fe6r1_wzqg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*5aeU83g7F1iNsTORtauWqQ.gif" /></figure><p><em>&gt; You can use an audio file, from your device, to write a story. Before you have to record an audio (Tell me a story about an alien who loves to swim and eat chocolate very much.), and then the app will transcribe it. After that, you can use the transcription to write a story.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*pfkn4v9udrhNhQqjN0Dimw.gif" /></figure><p><strong># Requirements</strong></p><p>In order to use the API of ChatGPT, you have to create an account <a href="https://platform.openai.com/overview"><strong>Explore the OpenAI API</strong></a>. After that, just create a new secret key <a href="https://platform.openai.com/account/api-keys"><strong>API keys</strong></a>.</p><p><strong># Installation</strong></p><pre>git clone https://github.com/kiki-le-singe/tell-me-a-story-ai.git &lt;name&gt;<br>cd &lt;name&gt;<br>yarn | npm install<br>npx pod-install</pre><blockquote>Create a .env file at the root of the project and set this env variable <strong><em>OPENAI_API_KEY=&lt;YOUR_SECRET_KEY&gt;</em></strong></blockquote><pre>npm run ios</pre><p><strong># Resources</strong></p><p>All the images are taken from <a href="http://www.freepik.com/"><strong>Freepik</strong></a>. Those I have chosen have a free license. I just use them to illustrate this app.</p><p>They are designed by these authors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*prBZABvZG2bVQ-6gnysctA.gif" /></figure><ul><li><a href="https://www.freepik.com/author/freepik"><strong>freepik</strong></a></li><li><a href="https://www.freepik.com/author/ddraw"><strong>ddraw</strong></a></li><li><a href="https://www.freepik.com/author/vectorjuice"><strong>vectorjuice</strong></a></li><li><a href="https://www.freepik.com/author/pikisuperstar"><strong>pikisuperstar</strong></a></li><li><a href="https://www.freepik.com/author/pch-vector"><strong>pch.vector</strong></a></li><li><a href="https://www.freepik.com/author/catalyststuff"><strong>catalyststuff</strong></a></li><li><a href="https://www.freepik.com/author/rawpixel-com"><strong>rawpixel-com</strong></a></li><li><a href="https://www.freepik.com/author/upklyak"><strong>upklyak</strong></a></li><li><a href="https://www.freepik.com/author/brgfx"><strong>brgfx</strong></a></li><li><a href="https://www.freepik.com/author/stories"><strong>storyset</strong></a></li></ul><p>All the icons are taken from <a href="https://undraw.co/"><strong>unDraw</strong></a>.</p><p>A <strong>big thanks</strong> to them for their awesome work!</p><blockquote><strong>If you appreciate this project, do not hesitate to share it, like it, and give me feedback if you have any questions. Enjoy it ;)</strong></blockquote><blockquote><strong>Have a good day :)</strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7346d4a76ae2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mobile UI testing with React Native and Maestro]]></title>
            <link>https://medium.com/@aalbertini95_90842/mobile-ui-testing-with-react-native-and-maestro-af7fa34df2fd?source=rss-a4fdee6aeb66------2</link>
            <guid isPermaLink="false">https://medium.com/p/af7fa34df2fd</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Boopy]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 13:10:58 GMT</pubDate>
            <atom:updated>2024-08-31T14:08:21.193Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<blockquote>Hello!</blockquote><blockquote>I would like to introduce you a small personal project I mainly created for fun and to develop my mobile UI testing skills. I would like to share it with you, if you are interested in it. This project shows how to make UI testing with <strong>React Native</strong> (A framework to create native apps for Android and iOS) and <strong>Maestro</strong> (A mobile UI testing framework).</blockquote><blockquote>This is the complete project: <a href="https://github.com/kiki-le-singe/react-native-maestro"><strong>https://github.com/kiki-le-singe/react-native-maestro</strong></a></blockquote><h4>Introduction</h4><blockquote>I started this project mainly for fun and to develop my mobile UI testing skills. After reading the Documentation for Maestro (<a href="https://maestro.mobile.dev/">https://maestro.mobile.dev/</a> and <a href="https://maestro.mobile.dev/platform-support/react-native">https://maestro.mobile.dev/platform-support/react-native</a>), I found it seemed easy to implement, simple and effective. So… Let’s go! :D<br>I created a React Native app built with Expo to simply this part. The aim of this project is <strong>Maestro</strong>.<br>Enjoy it! :)</blockquote><p>This app has three screens:</p><p>- A sign in interface with two fields, email and password. After clicking the sign in button, if the form is valid `(a valid email and password)` we’ll see the next screen.<br>- A simple screen with greetings and email user, a link to another screen and a sign out button.<br>- A scrollview screen with some texts and images. It’s also possible to go back to the previous screen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*xKOZwos_0GfVuh5TTtvc8w.gif" /></figure><h4>Installation</h4><p># React Native Maestro App</p><pre>git clone https://github.com/kiki-le-singe/react-native-maestro.git &lt;name&gt;<br>cd &lt;name&gt;<br>npm install</pre><p># Maestro</p><pre>curl -Ls &quot;https://get.maestro.mobile.dev&quot; | bash<br>maestro -v</pre><p>&gt; Only for iOS: <strong><em>Connecting to Your Device</em> </strong><a href="https://maestro.mobile.dev/getting-started/installing-maestro#connecting-to-your-device">https://maestro.mobile.dev/getting-started/installing-maestro#connecting-to-your-device</a></p><pre>brew tap facebook/fb<br>brew install facebook/fb/idb-companion</pre><p>See the official documentation: <strong><em>Installing Maestro</em> </strong><a href="https://maestro.mobile.dev/getting-started/installing-maestro">https://maestro.mobile.dev/getting-started/installing-maestro</a></p><h4>Run</h4><pre>npm start<br>npm run ios or android</pre><h4>Maestro tests</h4><p>The tests are in the <strong><em>maestro</em></strong> directory. You can run them locally in your iOS simulator or Android emulator. At the moment, Maestro does not support real iOS devices. See <strong><em>Installing Maestro</em></strong> <a href="https://maestro.mobile.dev/getting-started/installing-maestro">https://maestro.mobile.dev/getting-started/installing-maestro</a> and <strong><em>Connecting to Your Device </em></strong><a href="https://maestro.mobile.dev/getting-started/installing-maestro#connecting-to-your-device">https://maestro.mobile.dev/getting-started/installing-maestro#connecting-to-your-device</a></p><p>You can run the tests in CI with <strong><em>Maestro Cloud</em></strong>. See <strong><em>Running Flows on CI </em></strong><a href="https://maestro.mobile.dev/getting-started/running-flows-on-ci">https://maestro.mobile.dev/getting-started/running-flows-on-ci</a></p><h4>Running tests</h4><pre># run single test<br>maestro test maestro/[fileName].yaml</pre><pre>maestro test maestro/simple-flow.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*_jg3FxEkfIR2pGgv9RuQxQ.gif" /></figure><pre>maestro test maestro/signin/signin-errors-flow.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qG9KMXJOtyi7dg8jmzZJMg.gif" /></figure><pre>maestro test maestro/signin/signin-success-flow.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Krpg3ucQgqTfJ9yHPWb_fg.gif" /></figure><pre>maestro test maestro/home/home-flow.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*byvYpxiDBea82OKGgDmVHQ.gif" /></figure><pre>maestro test maestro/details/details-flow.yaml</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PXWQhjWjqBedB62MnuvZPA.gif" /></figure><blockquote>Sometimes you could see this error: <strong><em>Failed to reach out XCUITest Server </em></strong><a href="https://github.com/mobile-dev-inc/maestro/issues/880">https://github.com/mobile-dev-inc/maestro/issues/880</a></blockquote><blockquote>Maybe your component is not reachable, so you probably check your code. Sometimes the CLI just seems a little capricious… So just wait a few secondes… And it perfectly works! :D</blockquote><blockquote>Voilà! That’s it!</blockquote><blockquote>Don’t hesitate if you have any questions</blockquote><blockquote>I hope it would be helpful for someone :)</blockquote><blockquote>Have a good day!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af7fa34df2fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>