<?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 Valentyn Yakymenko on Medium]]></title>
        <description><![CDATA[Stories by Valentyn Yakymenko on Medium]]></description>
        <link>https://medium.com/@vyakymenko?source=rss-480104d31c3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TsdqVy2a-e-SwPHRzRQ-og@2x.jpeg</url>
            <title>Stories by Valentyn Yakymenko on Medium</title>
            <link>https://medium.com/@vyakymenko?source=rss-480104d31c3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 02:43:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vyakymenko/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[Enterprise Next.js Application Architecture (with Nx & Vitest)]]></title>
            <link>https://medium.com/hackernoon/enterprise-next-js-application-architecture-with-nx-vitest-c453dbd94f0a?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c453dbd94f0a</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 08:32:05 GMT</pubDate>
            <atom:updated>2025-10-17T08:32:34.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>🏢 Enterprise Next.js Application Architecture (with Nx &amp; Vitest)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MAz3Q3rh58c_T1eGlpgdQ.png" /></figure><p>This article describes the architecture, design principles, and folder structure for our enterprise-grade <strong>Next.js</strong> application powered by <strong>Nx</strong> and <strong>Vitest</strong>.<br>The goal is to ensure <strong>scalability, maintainability, and performance</strong> across multiple teams, domains, and shared libraries.</p><h4><a href="https://github.com/vyakymenko/nextjs-enterprise-architecture">GitHub Document Link</a></h4><h3>⚙️ Core Principles</h3><ul><li><strong>Monorepo First:</strong> Nx for workspace orchestration and dependency graphing.</li><li><strong>Modularity:</strong> Clear domain separation via apps/ and libs/ boundaries.</li><li><strong>Scalability:</strong> Built for multiple teams, environments, and applications.</li><li><strong>Type Safety:</strong> Full TypeScript coverage across client and server.</li><li><strong>Performance:</strong> SSR with Server Components, edge caching, and ISR.</li><li><strong>Testing Excellence:</strong> Fast and isolated testing using Vitest.</li><li><strong>Security:</strong> Encapsulated APIs and middleware for auth and validation.</li><li><strong>Observability:</strong> Centralized logging, metrics, and error tracking.</li></ul><h3>🧱 Architectural Overview</h3><pre>Presentation Layer (UI)<br>  ├── Pages / Routes / Layouts<br>  ├── Components, UI primitives<br>  └── Client-side state / hooks<br><br>Application / Domain Layer (Business Logic)<br>  ├── Use cases, services, orchestration<br>  ├── Domain entities, validation, and rules<br>  └── Application interfaces (ports)<br><br>Infrastructure Layer (Adapters)<br>  ├── Repositories, data access (DB / APIs)<br>  ├── Integrations (HTTP, GraphQL, storage)<br>  └── Logging, caching, monitoring<br><br>Interface Layer (Boundaries)<br>  ├── Next.js API routes / Route handlers<br>  ├── Middleware (auth, validation)<br>  └── Controllers invoking the Application Layer<br><br>Cross-cutting Concerns<br>  ├── Config / Environment handling<br>  ├── Error handling / Observability<br>  ├── Shared utilities / helpers<br>  └── Design system and UI components</pre><h3>🧰 Nx Monorepo Setup</h3><p><strong>Nx</strong> manages our monorepo with multiple apps and libraries:</p><pre>apps/<br>  web/             → Main Next.js app<br>  admin/           → Admin dashboard app<br><br>libs/<br>  ui/              → Shared design system components<br>  domain/          → Business logic and types<br>  utils/           → Shared utilities<br>  config/          → Environment and feature flags</pre><h4>Benefits</h4><ul><li><strong>Dependency Graph Visualization</strong> (npx nx graph)</li><li><strong>Smart Task Orchestration</strong> (npx nx affected:build)</li><li><strong>Incremental &amp; Cached Builds</strong> (Nx Cloud)</li><li><strong>Reusable Generators &amp; Executors</strong></li><li><strong>Clear Ownership Across Teams</strong></li></ul><h4>Common Commands</h4><pre>npx nx graph<br>npx nx affected:test<br>npx nx run web:serve<br>npx nx run admin:build</pre><h3>🧪 Testing with Vitest</h3><p><strong>Vitest</strong> provides ultra-fast and modern testing for Next.js apps.</p><h4>Features</h4><ul><li>⚡ Blazing fast runs with Vite under the hood</li><li>🧩 TypeScript support out of the box</li><li>🧠 Jest-compatible API (describe, it, expect)</li><li>🧪 Integration with React Testing Library</li><li>🧱 Works seamlessly with Nx targets</li></ul><h4>Example vitest.config.ts</h4><pre>import { defineConfig } from &#39;vitest/config&#39;;<br>import { defineConfig } from &#39;vitest/config&#39;;<br><br>export default defineConfig({<br>  test: {<br>    globals: true,<br>    environment: &#39;jsdom&#39;,<br>    setupFiles: &#39;./tests/setup.ts&#39;,<br>    coverage: {<br>      reporter: [&#39;text&#39;, &#39;html&#39;],<br>    },<br>  },<br>});</pre><h4>Example Command</h4><pre>npx nx run web:test</pre><h3>📂 Folder Structure</h3><pre>apps/<br>  web/<br>    src/<br>      app/<br>        api/<br>          auth/<br>            route.ts<br>          users/<br>            route.ts<br>        dashboard/<br>          page.tsx<br>          layout.tsx<br>        layout.tsx<br>        page.tsx<br>      components/<br>        ui/<br>          Button/<br>            index.tsx<br>            Button.test.tsx<br>        layout/<br>          Header.tsx<br>          Footer.tsx<br>      hooks/<br>        useUser.ts<br>        useFetch.ts<br>      services/<br>        authService.ts<br>        userService.ts<br>      config/<br>        env.ts<br>        featureFlags.ts<br>      middleware/<br>        authMiddleware.ts<br>        errorMiddleware.ts<br><br>libs/<br>  ui/<br>    Button.tsx<br>    Modal.tsx<br>  domain/<br>    user/<br>      User.ts<br>      validators.ts<br>  utils/<br>    format.ts<br>    date.ts<br>  config/<br>    env.ts<br>    featureFlags.ts<br><br>tests/<br>  unit/<br>  integration/<br>  e2e/<br><br>nx.json<br>package.json<br>tsconfig.base.json<br>vite.config.ts</pre><h3>💻 Example Code</h3><p>src/usecases/loginUser.ts</p><pre>import { authRepo } from &quot;@org/domain/authRepo&quot;;<br>import { validateCredentials } from &quot;@org/domain/auth/validators&quot;;<br><br>export async function loginUser(email: string, password: string) {<br>  validateCredentials(email, password);<br>  const user = await authRepo.login(email, password);<br>  if (!user) throw new Error(&quot;Invalid credentials&quot;);<br>  return user;<br>}</pre><p>apps/web/src/app/api/auth/route.ts</p><pre>import { NextRequest, NextResponse } from &quot;next/server&quot;;<br>import { loginUser } from &quot;@org/domain/usecases/loginUser&quot;;<br><br>export async function POST(req: NextRequest) {<br>  const { email, password } = await req.json();<br>  try {<br>    const user = await loginUser(email, password);<br>    return NextResponse.json({ user });<br>  } catch (err: any) {<br>    return NextResponse.json({ error: err.message }, { status: 400 });<br>  }<br>}</pre><h3>🚀 Deployment &amp; Scaling</h3><ul><li><strong>Incremental Builds:</strong> Nx Cloud caching and remote execution.</li><li><strong>Environment Config:</strong> Strict validation via libs/config/env.ts.</li><li><strong>Feature Flags:</strong> Controlled rollout in libs/config/featureFlags.ts.</li><li><strong>Monitoring:</strong> Sentry / OpenTelemetry for metrics and tracing.</li><li><strong>CI/CD:</strong> Nx + GitHub Actions for affected pipelines only.</li><li><strong>Microfrontends:</strong> Independent apps/ deploys via Nx projects.</li><li><strong>Monorepo Governance:</strong> Shared linting, formatting, and type rules.</li></ul><h3>🧠 Tech Stack</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*D2z38Bh9rv2DMiIltiOShg.png" /></figure><blockquote><em>“Architecture is not about frameworks, it’s about boundaries.”</em> — Uncle Bob Martin</blockquote><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c453dbd94f0a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/enterprise-next-js-application-architecture-with-nx-vitest-c453dbd94f0a">Enterprise Next.js Application Architecture (with Nx &amp; Vitest)</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Color contrast with OKLCH; prefers-reduced-motion and motion design ethics]]></title>
            <link>https://medium.com/@vyakymenko/color-contrast-with-oklch-prefers-reduced-motion-and-motion-design-ethics-089c0c8897d0?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/089c0c8897d0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[accessibility]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 12:04:16 GMT</pubDate>
            <atom:updated>2025-10-12T12:04:16.302Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*mVfs1noLg5dEttP7NLafmA.jpeg" /></figure><p>Front-end for everyone and today we going discuss color contrasts with OKLCH, how to use it. You will understand prefers-reduced-motion and motion design ethics.</p><ul><li>Use OKLCH as your primary design-system color space. It tracks perceived lightness (L) and chroma (C) more linearly than HSL/HSV and sRGB, making contrast‑safe scaling and theming predictable.</li><li>Build a contrast‑safe palette by locking L for text and adjusting C and h to meet WCAG 2.2 (4.5:1 body text, 3:1 large text/UI). Add an APCA/optional contrast target for future‑proofing.</li><li>Progressive enhance: ship solid sRGB fallbacks first; layer OKLCH via @supports and color‑mix in oklch.</li><li>Motion is a product ethic. Default to motion that communicates, not decorates. Respect prefers-reduced-motion at the component level, not just globally. Provide non‑motion alternatives for essential feedback.</li><li>Create a “motion budget” and an a11y test plan. Keep heavy motion off critical paths. Verify with real users and tooling (Lighthouse, Web Vitals, reduced‑motion audits).</li></ul><h4>1) Why OKLCH now</h4><p>HSL and HSV are convenient but not perceptually uniform: equal steps in “lightness” don’t loo</p><p>k equal. sRGB is a device‑dependent encoding, not a design space. OKLCH (Oklab in polar form: Lightness L [0–1], Chroma C [0–~0.37], Hue h [0–360]) gives you visually even steps and predictable tints/shades across hues.</p><h4>What this unlocks</h4><ul><li>Contrast-consistent scales: Hold L for text roles; vary C and h for branding without breaking legibility.</li><li>Safer theming: Adjust a small set of tokens by L and C to switch light/dark/high‑contrast modes without re‑authoring palettes.</li><li>More color gamut: On wide‑gamut displays, OKLCH maps well while remaining backwards compatible.</li></ul><h4>Quick primer</h4><ul><li>L (lightness): perceived brightness. Biggest lever for contrast.</li><li>C (chroma): colorfulness/saturation. High C can reduce contrast at the same L against some backgrounds.</li><li>h (hue): angle around the color wheel.</li></ul><h4>Diagram (conceptual)</h4><pre>   OKLCH (cylindrical)<br>        ↑ L<br>        │<br>        │       (higher chroma →)<br>        ●───◯───◯───◯  h rotates around<br>       /      <br>      /   C<br>     ⟳ h</pre><h4>2) Contrast fundamentals that matter in production</h4><ul><li>WCAG 2.2 requires 4.5:1 for body text &lt; 18pt (or &lt; 24px) and 3:1 for large text/UI icons/graphics. Non‑text elements also need sufficient contrast when conveying meaning.</li><li>APCA (WCAG 3.0 candidate) uses a perceptual model better aligned with human vision, especially for low‑contrast UIs on modern displays. It’s not a normative requirement yet. I recommend: satisfy WCAG 2.2; track APCA deltas in CI for future readiness.</li><li>Don’t chase a single “ratio” blindly. Real context matters: weight, font rendering, size, background noise, and motion.</li></ul><h4>3) Practical OKLCH palette building for contrast Approach</h4><ul><li>Decide roles first: text/foreground (primary, secondary, disabled), backgrounds (surface, elevated), borders, states (info, success, warn, danger), and accent.</li><li>Lock foreground L targets by role and vary C slightly to keep brand feel.</li><li>Derive backgrounds by stepping L up/down; keep chroma low for surfaces to avoid color cast banding.</li></ul><p>Example tokens (progressive enhancement)</p><p>CSS with safe sRGB fallback, upgraded to OKLCH when supported.</p><pre>:root {<br>  /* sRGB fallbacks (closest approximations) */<br>  --fg-strong: #0b0b0c;        /* ≈ oklch(0.15 0.02 260) */<br>  --fg: #222326;               /* ≈ oklch(0.30 0.03 260) */<br>  --fg-muted: #5a5d65;         /* ≈ oklch(0.55 0.02 260) */<br>  --bg: #ffffff;               /* ≈ oklch(0.97 0 0) */<br>  --bg-soft: #f6f7f9;          /* ≈ oklch(0.96 0.01 260) */<br>  --accent: #005fcc;           /* ≈ oklch(0.60 0.14 255) */<br>  --accent-contrast: #ffffff;  /* ≈ oklch(0.98 0 0) */<br>}<br><br>@supports (color: oklch(0.5 0.1 0)) {<br>  :root {<br>    /* OKLCH first-class tokens */<br>    --fg-strong: oklch(0.15 0.02 260);<br>    --fg: oklch(0.30 0.03 260);<br>    --fg-muted: oklch(0.55 0.02 260);<br>    --bg: oklch(0.97 0 0);<br>    --bg-soft: oklch(0.96 0.01 260);<br>    --accent: oklch(0.60 0.14 255);<br>    --accent-contrast: oklch(0.98 0 0);<br>  }<br><br>  .button {<br>    color: var(--accent-contrast);<br>    background: var(--accent);<br>    /* derive hover by mixing accent toward fg for better perceived contrast */<br>    background: color-mix(in oklch, var(--accent) 88%, var(--fg-strong));<br>  }<br>}</pre><p>Contrast‑safe text heuristic</p><ul><li>For light backgrounds (~L ≥ 0.94), keep body text L ≤ 0.30 and chroma low (C ≤ 0.05) to reduce edge fringing on LCD subpixels.</li><li>For dark mode (bg L ≤ 0.15), push text L ≥ 0.85; avoid neon C that glows on OLED.</li></ul><h4>4) Computing/validating contrast in pipelines</h4><p>Browser‑native contrast functions like <strong>color-contrast()</strong> are still experimental. Today, measure contrast in CI using a library. Two options:</p><p>Node (culori) example</p><pre>// tooling/contrast.ts<br>// npm i culori<br>import { converter } from &#39;culori&#39;;<br>import { wcagContrast } from &#39;culori/contrast&#39;;<br><br>const toRgb = converter(&#39;rgb&#39;);<br>function contrast(a: string, b: string) {<br>  const A = toRgb(a);<br>  const B = toRgb(b);<br>  return wcagContrast(A, B); // returns ratio<br>}<br>const pairs = [<br>  [&#39;oklch(0.30 0.03 260)&#39;, &#39;oklch(0.97 0 0)&#39;],<br>  [&#39;oklch(0.98 0 0)&#39;, &#39;oklch(0.60 0.14 255)&#39;],<br>];<br>for (const [fg, bg] of pairs) {<br>  console.log(fg, &#39;on&#39;, bg, &#39;→&#39;, contrast(fg, bg).toFixed(2), &#39;:1&#39;);<br>}</pre><p>CI guardrail (pseudo)</p><ul><li>Parse CSS for tokens.</li><li>Compute contrast for role‑based pairs.</li><li>Fail PR if body text &lt; 4.5:1 or large text &lt; 3:1.</li><li>Log APCA as info for future migration.</li></ul><h4>5) Theming with OKLCH without regressions</h4><p>Light/dark + high‑contrast modes</p><pre>:root { /* light */<br>  --bg: oklch(0.98 0 0);<br>  --fg: oklch(0.30 0.03 260);<br>}<br><br>@media (prefers-color-scheme: dark) {<br>  :root {<br>    --bg: oklch(0.12 0 0);<br>    --fg: oklch(0.86 0.02 260);<br>  }<br>}<br><br>/* User‑requested high contrast variant (via class) */<br>:root.hc {<br>  --fg: oklch(0.08 0.02 260);<br>  --bg: oklch(0.99 0 0);<br>}</pre><p><em>Tip: Separate perceptual knobs</em></p><ul><li>L toggles readability.</li><li>C carries brand feel, raise it in accents, lower it in text.</li><li>h differentiates categories (e.g., success vs danger) while preserving contrast via L.</li></ul><h4>6) prefers-reduced-motion: from checkbox to engineering standard</h4><p>Motion can communicate hierarchy, causality, and feedback. It can also make people sick or distracted. As a principle: motion must always increase clarity and never gate core tasks.</p><p>The baseline</p><ul><li>Respect prefers-reduced-motion globally and locally.</li><li>Provide a motion budget per surface (e.g., onboarding: 200ms small fades; dashboard: zero ambient parallax).</li><li>Avoid autoplaying motion on entry where possible. Delay non‑essential motion until user intent.</li></ul><h4>Global opt‑down guardrail</h4><pre>/* Keep CSS transitions but swap to opacity/transform with reduced amplitude */<br>@media (prefers-reduced-motion: reduce) {<br>  * {<br>    animation: none !important;<br>    scroll-behavior: auto !important;<br>    transition-duration: 0.01ms !important; /* effectively none */<br>    transition-delay: 0s !important;<br>  }<br>}</pre><h4>Component-level ethical defaults</h4><pre>/* Base */<br>.toast {<br>  transform: translateY(8px);<br>  opacity: 0;<br>  transition: transform 180ms ease-out, opacity 120ms linear;<br>}<br>.toast[open] { transform: translateY(0); opacity: 1; }<br><br>/**** Respect reduced motion without removing feedback ****/<br>@media (prefers-reduced-motion: reduce) {<br>  .toast {<br>    /* Skip spatial motion, keep clarity via cross‑fade */<br>    transform: none;<br>    transition: opacity 80ms linear;<br>  }<br>}</pre><h4>React 18+ example (Framer Motion)</h4><pre>import { useReducedMotion, motion } from &#39;framer-motion&#39;;<br><br>export function Button({ children }) {<br>  const shouldReduce = useReducedMotion();<br>  const variants = shouldReduce<br>    ? { initial: { opacity: 0 }, animate: { opacity: 1 } }<br>    : { initial: { y: 8, opacity: 0 }, animate: { y: 0, opacity: 1 } };<br>  return (<br>    &lt;motion.button initial=&quot;initial&quot; animate=&quot;animate&quot; variants={variants}&gt;<br>      {children}<br>    &lt;/motion.button&gt;<br>  );<br>}</pre><h4>Angular example (Angular animations)</h4><pre>import { Component } from &#39;@angular/core&#39;;<br>import { trigger, transition, style, animate } from &#39;@angular/animations&#39;;<br><br>@Component({<br>  selector: &#39;app-toast&#39;,<br>  standalone: true,<br>  template: `&lt;div [@appear] class=&quot;toast&quot;&gt;&lt;ng-content /&gt;&lt;/div&gt;`,<br>  animations: [<br>    trigger(&#39;appear&#39;, [<br>      transition(&#39;:enter&#39;, [<br>        style({ opacity: 0, transform: &#39;translateY(8px)&#39; }),<br>        animate(&#39;180ms ease-out&#39;, style({ opacity: 1, transform: &#39;none&#39; }))<br>      ])<br>    ])<br>  ]<br>})<br>export class ToastComponent {}</pre><p>Respect user preference in Angular globally by swapping to NoopAnimationsModule for a reduced-motion build or read the media query in a service and vary animation metadata accordingly.</p><p>JS utility to read the user preference</p><pre>export const prefersReducedMotion = () =&gt;<br>  typeof window !== &#39;undefined&#39;<br>    ? window.matchMedia(&#39;(prefers-reduced-motion: reduce)&#39;).matches<br>    : false;</pre><h4>7) Motion ethics: what not to do (and why)</h4><ul><li>Don’t use parallax/zoom on scroll for primary content. Vestibular issues are real; sudden z‑axis motion can trigger nausea.</li><li>Don’t gate trust behind motion. Loading skeletons are fine; fake progress or distracting shimmer loops are not.</li><li>Don’t couple motion and color extremes. High‑chroma flicker plus motion is a migraine recipe.</li><li>Don’t surprise. Any motion exceeding ~200ms or &gt; 12px travel should be intent‑driven with visible affordances.</li></ul><h4>Do instead</h4><ul><li>Use subtle opacity/scale under 1.04, distances under 8–12px, duration 120–200ms for UI feedback.</li><li>Prefer cross‑fade over translate/rotate for reduced motion contexts.</li><li>Annotate animations with purpose (enter, exit, emphasis, spatial continuity) and measure their value.</li></ul><h4>8) Performance and Web Vitals</h4><ul><li>Stick to compositor‑only properties (opacity, transform). Avoid layout‑thrashing properties in transitions (top/left, width/height) unless measured and isolated.</li><li>Avoid heavy animated SVG filters and large GIF/WebM loops; they can tank CPU and battery.</li><li>Audit CLS: sudden content shifts from lazy images/ads are a form of harmful motion.</li><li>Test both normal and reduced‑motion modes in Lighthouse and WebPageTest. Treat regressions as bugs.</li></ul><h4>9) Real‑world rollout plan (what I do with teams)</h4><ul><li>Inventory colors. Convert existing tokens to OKLCH (one‑time script with culori). Store both representations; OKLCH is authoritative.</li><li>Define target L ranges by role. Example: body text L≈0.25–0.32 (light mode), L≈0.85–0.92 (dark mode). Accents keep brand hue but adjust C per background.</li><li>Implement fallbacks and @supports upgrade. Ship color-mix(in oklch, …) only in supporting browsers.</li><li>Add CI contrast checks (WCAG now, APCA info). Break builds on regressions.</li><li>Create a motion policy. Include: prefers‑reduced‑motion handling, motion budget, banned patterns (parallax), and required alt patterns.</li><li>Refactor animation utilities/components to consult reduced‑motion at runtime.</li><li>Run an accessibility review with users. Watch for motion discomfort reports; adjust defaults.</li></ul><h4>10) Common pitfalls and fixes</h4><ul><li>“My brand blue looks dull in dark mode.” Fix: Raise C slightly but increase L contrast; don’t push neon C on dark backgrounds.</li><li>“Text on accent buttons fails contrast.” Fix: Nudge button L downward and enforce white text; alternatively desaturate accent slightly at the same L.</li><li>“Animations feel sluggish on low‑end devices.” Fix: Shorten duration, prefer opacity, drop blur/backdrop filters, reduce simultaneous animated elements.</li><li>“We ‘support’ reduced motion but skeletons still shimmer.” Fix: Provide a static placeholder path when reduced motion is on.</li></ul><h4>Appendix A: Relative color syntax + color-mix examples</h4><pre>/* Derive a subtle border from foreground in OKLCH */<br>@supports (color: oklch(0.5 0.1 0)) {<br>  .card {<br>    --border: color-mix(in oklch, var(--fg) 15%, var(--bg));<br>    border: 1px solid var(--border);<br>  }<br>}<br><br>/* Tone an accent for hover/focus */<br>.button:hover {<br>  background: color-mix(in oklch, var(--accent) 82%, var(--fg-strong));<br>}</pre><h4>Appendix B: ASCII palette visualizer (L vs C)</h4><pre>L: 0.98 bg  ────────────────────────────────●<br>L: 0.86 text-dark  ────────────────────●<br>L: 0.60 accent  ─────────────● (C↑)<br>L: 0.30 text  ─────● (C low)<br>L: 0.12 bg-dark  ●</pre><h4>Final checklist</h4><ul><li>OKLCH tokens with sRGB fallbacks</li><li><strong>@supports</strong> upgrade path + color-mix in oklch</li><li>WCAG 2.2 contrast CI guards; APCA logged informationally</li><li>Reduced-motion respected globally and per component with non‑motion alternatives</li><li>Motion budget documented; banned patterns enforced</li><li>Performance profiled for both normal and reduced-motion modes</li></ul><h4>Further reading/tools</h4><ul><li>OKLCH guide: <a href="https://oklch.com/">https://oklch.com/</a></li><li>Culori: <a href="https://culorijs.org/">https://culorijs.org/</a></li><li>APCA: <a href="https://www.myndex.com/APCA/">https://www.myndex.com/APCA/</a></li><li>Web Vitals: <a href="https://web.dev/vitals/">https://web.dev/vitals/</a></li><li>WCAG 2.2: <a href="https://www.w3.org/TR/WCAG22/">https://www.w3.org/TR/WCAG22/</a></li></ul><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=089c0c8897d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js, Bun and Deno in Front End Workflows]]></title>
            <link>https://medium.com/@vyakymenko/node-js-bun-and-deno-in-front-end-workflows-6c7dc08820aa?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c7dc08820aa</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 09:43:42 GMT</pubDate>
            <atom:updated>2025-10-07T09:43:42.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tcTiwIpWzo_r7h2a0HrWQ.png" /></figure><p>Front-end workflows are evolving fast. Three JavaScript runtimes meaningfully shape day-to-day DX: Node.js, Bun, and Deno. Node is modernizing with a built-in test runner, first-class ESM, and user-land loaders; Bun and Deno ship batteries-included developer ergonomics like fast dev servers, native TypeScript, and integrated test tooling.</p><p>This is a practical guide: when to pick which, how to compose them in monorepos, and concrete code you can paste into real projects.</p><p>What you’ll learn:</p><ul><li>How Bun and Deno improve FE workflows (dev server, test runner, bundling, TypeScript, npm interop)</li><li>What’s new in Node (node:test, ESM-by-default patterns, loaders/hooks)</li><li>Side-by-side code examples for Node, Bun, and Deno</li><li>Migration and coexistence tips in polyglot repos</li></ul><h4>TL; DR Choosing quickly (cheat sheet)</h4><ul><li>Need pure speed for local dev/tests in an npm repo? Try Bun for dev/test; deploy with Node.</li><li>Need out-of-the-box TS, strict permissions, and web-standard APIs? Use Deno end-to-end.</li><li>Need maximum ecosystem compatibility and enterprise stability? Node remains the default.</li><li>Building a UI library to run everywhere? Target Web APIs; run tests in all three.</li></ul><h3>1) Quick positioning: when each runtime shines</h3><h4>Node.js</h4><ul><li>Strengths: ecosystem gravity (npm), long-term stability, mature production story, wide platform support.</li><li>Today’s upgrades: built-in node:test, stable ESM patterns, loaders for transformation/resolution.</li><li>Use when: serverful apps, CLI tools, broad library compatibility, enterprise infra.</li></ul><h4>Bun</h4><ul><li>Strengths: very fast startup and test runs, built-in bundler/transformer, sensible web APIs, good npm compatibility, file watching.</li><li>Use when: fast FE dev server, tests on large React/Vue codebases, single-binary DX for local tooling.</li></ul><h4>Deno</h4><ul><li>Strengths: native TypeScript, secure-by-default permissions, URL/JSR imports, web-standard APIs, excellent test tooling and built-in linter/formatter.</li><li>Use when: standards-first code, TS-heavy repos, edge-ready APIs, strong security controls.</li></ul><h4>Rule of thumb</h4><ul><li>If your repo is npm-centric and must match existing Node production: use Node, optionally Bun for local dev/test speed.</li><li>If you want TypeScript without build steps and a batteries-included toolchain: Deno is ergonomic.</li><li>Polyglot is normal: you can run FE dev with Bun or Deno and still ship Node to prod.</li></ul><h3>2) Project setup patterns</h3><h4>Node (ESM project)</h4><p>package.json:</p><pre>{<br>  &quot;name&quot;: &quot;fe-app&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;node --watch ./dev-server.js&quot;,<br>    &quot;test&quot;: &quot;node --test&quot;,<br>    &quot;build&quot;: &quot;node ./scripts/build.mjs&quot;<br>  },<br>  &quot;devDependencies&quot;: {<br>    &quot;vite&quot;: &quot;^5.4.0&quot;<br>  }<br>}</pre><h4>Bun</h4><pre>bun init<br>bun add -d vite<br>bun dev         # runs vite if defined in package.json scripts<br>bun test        # runs bun&#39;s test runner</pre><p>Example package.json for Bun dev:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;vite&quot;,<br>    &quot;test&quot;: &quot;bun test&quot;,<br>    &quot;build&quot;: &quot;vite build&quot;<br>  }<br>}</pre><h4>Deno</h4><p>No package.json required. Use deno.json for tasks and permissions.</p><pre>{<br>  &quot;tasks&quot;: {<br>    &quot;dev&quot;: &quot;deno run --watch --allow-net --allow-read dev_server.ts&quot;,<br>    &quot;test&quot;: &quot;deno test&quot;,<br>    &quot;build&quot;: &quot;deno run -A scripts/build.ts&quot;<br>  },<br>  &quot;lint&quot;: { &quot;rules&quot;: { &quot;tags&quot;: [&quot;recommended&quot;] } },<br>  &quot;fmt&quot;: { &quot;useTabs&quot;: false, &quot;indentWidth&quot;: 2 }<br>}</pre><p>Run tasks:</p><pre>deno task dev<br>deno task test</pre><h3>3) Testing: node:test vs bun:test vs deno test</h3><h4>Node’s built-in test runner</h4><ul><li>Node 20+ ships node:test. No external framework required.</li><li>Supports subtests, TAP output, parallelization, watch mode via — test — watch.</li></ul><p>Example (ESM):</p><pre>// math.test.mjs<br>import test from &#39;node:test&#39;;<br>import assert from &#39;node:assert/strict&#39;;<br><br>function add(a, b) { return a + b; }<br><br>test(&#39;add adds numbers&#39;, () =&gt; {<br>  assert.equal(add(2, 2), 4);<br>});<br><br>test(&#39;async example&#39;, async (t) =&gt; {<br>  await t.test(&#39;nested subtest&#39;, () =&gt; {<br>    assert.ok(true);<br>  });<br>});</pre><p>Run:</p><pre>node --test<br>node --test --watch  # great for local TDD</pre><h4>Bun’s test runner</h4><p>Jest-like API with fast start, snapshots, and built-in mocking.</p><pre>// math.test.ts<br>import { describe, it, expect } from &#39;bun:test&#39;;<br><br>function add(a: number, b: number) { return a + b; }<br><br>describe(&#39;math&#39;, () =&gt; {<br>  it(&#39;adds&#39;, () =&gt; {<br>    expect(add(1, 2)).toBe(3);<br>  });<br>});</pre><p>Run:</p><pre>bun test<br>bun test --watch</pre><h4>Deno test</h4><ul><li>Batteries-included; uses standard assertions and permissions model.</li></ul><pre>// math_test.ts<br>import { assertEquals } from &quot;jsr:@std/assert&quot;;<br><br>function add(a: number, b: number) { return a + b; }<br><br>Deno.test(&quot;adds&quot;, () =&gt; {<br>  assertEquals(add(2, 3), 5);<br>});</pre><p>Run:</p><pre>deno test<br>deno test --watch</pre><h4>Snapshot testing</h4><ul><li>Bun: built-in snapshots with expect(…).toMatchSnapshot().</li><li>Deno: snapshot libraries exist on JSR; use permissions with care.</li><li>Node: use third-party snapshot libs or tap via reporters.</li></ul><h3>4) TypeScript and module resolution</h3><h4>Node</h4><ul><li>ESM preferred for modern tooling. Use “type”: “module” or .mjs extensions.</li><li>TS needs a transpile step or a loader (tsx, swc). Examples below.</li></ul><h4>Bun</h4><ul><li>TS/TSX supported out of the box; no ts-node needed. Good JSX support for React/Vue.</li></ul><h4>Deno</h4><ul><li>Native TypeScript with zero config. Imports can be bare (via npm:) or URL/JSR.</li></ul><h4>Examples</h4><p><strong>Node with tsx for dev</strong></p><pre>{<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;devDependencies&quot;: { &quot;tsx&quot;: &quot;^4.19.0&quot; },<br>  &quot;scripts&quot;: { &quot;dev&quot;: &quot;tsx watch src/index.ts&quot; }<br>}</pre><p><strong>Node ESM + custom loader to import TS</strong></p><pre>// ts-loader.mjs (minimal demo – use in dev only)<br>import { transformSync } from &#39;esbuild&#39;;<br><br>export async function load(url, context, defaultLoad) {<br>  if (url.endsWith(&#39;.ts&#39;)) {<br>    const { source } = await defaultLoad(url, { ...context, format: &#39;module&#39; });<br>    const { code } = transformSync(source.toString(), { loader: &#39;ts&#39;, format: &#39;esm&#39; });<br>    return { format: &#39;module&#39;, source: code };<br>  }<br>  return defaultLoad(url, context, defaultLoad);<br>}</pre><p>Run with Node loaders:</p><pre>node --loader ./ts-loader.mjs src/index.ts</pre><p><strong>Deno bare TS ESM</strong></p><pre>// src/mod.ts<br>export const greet = (name: string) =&gt; `Hello, ${name}`;</pre><p>Run:</p><pre>deno run src/mod.ts</pre><p><strong>Bun TS</strong></p><pre>// src/index.ts<br>export const greet = (name: string) =&gt; `Hello, ${name}`;</pre><p>Run:</p><pre>bun run src/index.ts</pre><h3>5) Loaders, hooks, and import maps</h3><p><strong>Node ESM loaders (resolution/transform hooks)</strong></p><ul><li>Use — loader to intercept resolution and transform sources (e.g., TS, CSS modules for SSR, SVG-to-URL).</li><li>Newer Node also supports — import to preload modules before user code.</li></ul><p>Resolution example (alias @/* -&gt; ./src/*):</p><pre>// alias-loader.mjs<br>export async function resolve(specifier, context, next) {<br>  if (specifier.startsWith(&#39;@/&#39;)) {<br>    const url = new URL(specifier.replace(&#39;@/&#39;, &#39;./src/&#39;), import.meta.url);<br>    return { url: url.href, shortCircuit: false }; // defer to next for format<br>  }<br>  return next(specifier, context, next);<br>}</pre><p>Run:</p><pre>node --loader ./alias-loader.mjs app.mjs</pre><p>Preload example:</p><pre>node --import=dotenv/config --test   # preload dotenv for tests</pre><p><strong>Deno import maps</strong></p><ul><li>Configure path aliases and external URLs in deno.json.</li></ul><pre>{<br>  &quot;imports&quot;: {<br>    &quot;@/&quot;: &quot;./src/&quot;,<br>    &quot;lodash&quot;: &quot;npm:lodash@^4&quot;<br>  }<br>}</pre><p>Usage:</p><pre>import { debounce } from &quot;lodash&quot;;<br>import { foo } from &quot;@/utils/foo.ts&quot;;</pre><p><strong>Bun aliasing</strong></p><ul><li>Bun respects tsconfig paths and supports import maps via bunfig.toml.</li></ul><pre># bunfig.toml<br>[install]<br>peer = true</pre><pre>[alias]<br>&quot;@/&quot; = &quot;./src/&quot;</pre><h3>6) Dev servers and bundling for FE apps</h3><ul><li>Node: pair with Vite, Webpack, or Rspack. Start via node or tsx and defer to the bundler.</li><li>Bun: ships a fast bundler/transformer and can run Vite or its own Bun.serve() for simple apps.</li><li>Deno: use deno serve for static + SSR, or integrate with Vite via plugins; Fresh (Deno’s framework) is zero-build for islands.</li></ul><p>Minimal HTTP dev servers</p><p><strong>Node (ESM + undici)</strong></p><pre>// dev-server.mjs<br>import { createServer } from &#39;node:http&#39;;</pre><pre>createServer((req, res) =&gt; {<br>  res.setHeader(&#39;content-type&#39;, &#39;text/plain&#39;);<br>  res.end(&#39;Hello from Node dev server&#39;);<br>}).listen(5173, () =&gt; console.log(&#39;http://localhost:5173&#39;));</pre><p><strong>Bun</strong></p><pre>// dev_server.ts<br>export default {<br>  port: 5173,<br>  fetch(_req: Request) {<br>    return new Response(&#39;Hello from Bun dev server&#39;, { headers: { &#39;content-type&#39;: &#39;text/plain&#39; } });<br>  }<br>};</pre><p>Run:</p><pre>bun run dev_server.ts</pre><p><strong>Deno</strong></p><pre>// dev_server.ts<br>Deno.serve((_req) =&gt; new Response(&#39;Hello from Deno dev server&#39;, { headers: { &#39;content-type&#39;: &#39;text/plain&#39; } }));</pre><p>Run:</p><pre>deno run --allow-net dev_server.ts</pre><h3>7) npm, JSR, and compatibility</h3><ul><li>Node: native npm. ESM-first packages are common; prefer import semantics in new code.</li><li>Bun: excellent npm compatibility; uses the same package.json and node_modules. Often faster installs.</li><li>Deno: can import npm: specifiers without node_modules. For example:</li></ul><pre>import express from &quot;npm:express@^4&quot;; // yes, for quick adaptation; prefer standard fetch/Request in Deno</pre><ul><li>JSR: the JavaScript Registry for standards-based modules. Deno and Node can both consume JSR packages with tooling; prefer JSR for TS+ESM libraries.</li></ul><p><strong>Publishing libraries</strong></p><ul><li>If targeting all three runtimes, avoid Node-only globals. Stick to Web APIs (fetch, URL, TextEncoder) or provide conditional exports.</li><li>For Node, define exports with ESM/CJS conditions in package.json.</li></ul><pre>{<br>  &quot;name&quot;: &quot;lib&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;exports&quot;: {<br>    &quot;.&quot;: {<br>      &quot;types&quot;: &quot;./dist/index.d.ts&quot;,<br>      &quot;import&quot;: &quot;./dist/index.js&quot;,<br>      &quot;require&quot;: &quot;./dist/index.cjs&quot;<br>    }<br>  }<br>}</pre><h3>8) Security and permissions</h3><ul><li>Node: no permission sandbox; rely on process sandboxing and least-privilege at OS/container level.</li><li>Bun: similar to Node (no explicit permission flags), but fewer legacy attack surfaces.</li><li>Deno: permissioned by default. Grant only what you need per command:</li></ul><pre>deno run --allow-net=api.example.com --allow-read=./data app.ts</pre><h3>9) Mixing runtimes in monorepos</h3><ul><li>Use workspaces (pnpm/npm/yarn) for Node/Bun packages; keep Deno projects side-by-side with their own deno.json.</li><li>Provide universal scripts via make or justfile, or use task runners that shell out to each runtime.</li><li>Example layout:</li></ul><pre>repo/<br>  apps/<br>    web-node/        # Next.js (Node)<br>    web-bun/         # Vite + Bun dev<br>    web-deno/        # Fresh (Deno)<br>  packages/<br>    ui/              # ESM library, Web APIs only</pre><ul><li>Contract: packages/ui must avoid Node-only modules. Test in all runtimes:</li></ul><pre>node --test packages/ui/*.test.mjs<br>bun test packages/ui<br>deno test packages/ui</pre><h3>10) Node innovations in focus</h3><p><strong>node:test as a daily driver</strong></p><ul><li>Stable, fast, built-in. Pair with — experimental-test-coverage in newer Node when available, or use c8.</li></ul><p><strong>ESM done right</strong></p><ul><li>Prefer “type”: “module”. For CJS interop, use createRequire or dynamic import.</li></ul><pre>// cjs-interop.mjs<br>import { createRequire } from &#39;node:module&#39;;<br>const require = createRequire(import.meta.url);<br>const legacy = require(&#39;left-pad&#39;);</pre><p><strong>Loaders and preloading</strong></p><ul><li>— loader for custom resolution/transform; — import for preloading env and hooks.</li><li>Keep production loaders minimal; prefer build-time transforms. Use loaders for SSR glue (CSS modules, SVG, TS in dev).</li></ul><h3>11 ) Choosing quickly (cheat sheet)</h3><ul><li>Need pure speed for local dev/tests in an npm repo? Try Bun for dev/test; deploy with Node.</li><li>Need out-of-the-box TS, strict permissions, and web-standard APIs? Use Deno end-to-end.</li><li>Need maximum ecosystem compatibility and enterprise stability? Node remains the default.</li><li>Building a UI library to run everywhere? Target Web APIs; run tests in all three.</li></ul><h3>12) Migration tips and pitfalls</h3><ul><li>Avoid process, Buffer, and path-specific code in shared FE libraries; prefer URL, Blob, File, TextEncoder, crypto.subtle.</li><li>For fetch differences, polyfill Request/Response types consistently (most are aligned now across runtimes).</li><li>Node ESM gotchas: file URL to path conversion:</li></ul><pre>import { fileURLToPath } from &#39;node:url&#39;;<br>import { dirname } from &#39;node:path&#39;;<br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = dirname(__filename);</pre><ul><li>Bun and Deno ship fetch globally; Node 18+ does too, but older LTS needs undici.</li><li>Snapshots: Bun built-in; Deno via libs; Node via external libs.</li></ul><h3>Closing thoughts</h3><p>Bun and Deno push the envelope for developer experience — fast feedback loops, built-in TypeScript, and pragmatic defaults. Node keeps improving where it matters: standardized modules, first-party testing, and extensible loaders. In practice, you don’t have to pick a single winner. Use the best tool per task, keep shared code on Web APIs, and make testing across runtimes a habit.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c7dc08820aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Edge rendering vs. static vs. serverful trade‑offs]]></title>
            <link>https://medium.com/@vyakymenko/edge-rendering-vs-static-vs-serverful-trade-offs-8f720d69dc7b?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f720d69dc7b</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Thu, 02 Oct 2025 16:40:01 GMT</pubDate>
            <atom:updated>2025-10-02T16:40:01.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5_VEObqUPNBK9bqBLsWlNg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@eddyyyyyyyyyy?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Pengfei Liu</a> on <a href="https://unsplash.com/photos/a-blue-cube-sitting-on-top-of-a-pink-floor-3xZ6Ki1wEdM?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>If you’re building for the web, you’ve basically got three ways to get <strong><em>pixels to people</em></strong>: ship static HTML, run a tiny function at the edge, or run a fuller app in a region. Here’s a quick guide to when each one actually makes sense.</p><h4>What these terms actually mean</h4><ul><li><strong>Static</strong>: HTML is produced ahead of time at build (SSG) or periodically (ISR), optionally with Partial Prerendering (PPR) to stream dynamic islands later.</li><li><strong>Edge rendering</strong>: code runs in a distributed edge runtime (V8 isolates or WASM) close to users. Great for low‑latency logic; constrained by cold‑start budgets, CPU/memory limits, and platform APIs.</li><li><strong>Serverful SSR</strong>: traditional regional servers/functions. Full Node/Deno/Java runtimes, higher resource ceilings, and easy private networking. Latency is bound by geography and queueing.</li></ul><h4>Quick decisions</h4><ul><li>Do you need the same bytes for everyone for hours? Go static.</li><li>Do you need per‑request personalization or geo routing in &lt;50 ms compute? Go edge.</li><li>Do you need heavy libs (Puppeteer, headless PDF, ML), transactions, or VPC? Go serverful.</li><li>Can you split the page? Static outer shell + streamed dynamic islands is often the best of both worlds.</li></ul><h4>When static wins</h4><ul><li>Marketing, docs, blogs, product pages that change on schedule.</li><li>Search pages whose results are stable for minutes and can be revalidated on tag.</li><li>Predictable, cheap, resilient: CDN caches hide origin incidents.</li></ul><h4>If you go static</h4><ul><li>Prefer content APIs that can be pulled at build and tagged for ISR invalidation.</li><li>With PPR, pre‑render the shell and stream dynamic holes on demand to keep TTFB low while data stays fresh.</li></ul><h4>When edge wins</h4><ul><li>Geo‑aware pricing, inventory, and copy; country/state VAT; locale bootstrapping.</li><li>Logged‑out personalization (e.g., cart by cookie, AB variant) that doesn’t require sensitive data access.</li><li>Request shaping: quickly reject bots, rate‑limit, or rewrite without a regional hop.</li></ul><h4>Edge gotchas to keep in mind</h4><ul><li>Keep compute sub‑10–20 ms; <strong>avoid N+1 to distant origins</strong>.</li><li><strong>Avoid large native deps</strong> and Node‑only APIs; prefer Web standard APIs, fetch, and lightweight logic.</li><li><strong>Design for statelessness</strong>. If you need session data, use signed tokens or a fast edge KV/Cache layer.</li></ul><h4>When serverful wins</h4><ul><li>Authenticated dashboards with complex joins and transactional writes.</li><li><strong>Heavy tooling</strong>: image/video processing, headless browsers, AI inference beyond tiny models.</li><li><strong>Enterprise integrations inside private networks</strong> (databases over VPC, SAP/Oracle, internal APIs).</li></ul><h4>Serverful gotchas</h4><ul><li>Expect 100–400 ms extra round‑trip latency for global users; reduce by regionalizing where practical.</li><li>Invest in backpressure, pooling, and circuit breakers; failures are less forgiving than at the edge/CDN.</li></ul><h3>Performance, cost, and complexity at a glance</h3><h4>Static</h4><ul><li><strong>Perf:</strong> Best TTFB globally; zero server compute on hit.</li><li><strong>Cost:</strong> Lowest; bandwidth‑heavy, compute‑light.</li><li><strong>Complexity:</strong> Low; invalidation and build pipelines are the main moving parts.</li></ul><h4>Edge</h4><ul><li><strong>Perf:</strong> Excellent when logic is local and data is cached nearby; degrades if reaching regional databases.</li><li><strong>Cost:</strong> Pay per‑request compute; can be efficient for small functions, expensive for long CPU.</li><li><strong>Complexity:</strong> Medium; platform constraints + observability across many pops.</li></ul><h4>Serverful</h4><ul><li><strong>Perf:</strong> Consistent but bound by region; can be fast for users near the region.</li><li><strong>Cost:</strong> Higher baseline (instances) or bursty (functions) plus egress to CDN.</li><li><strong>Complexity:</strong> Highest; infra, security, scaling, and networking.</li></ul><h4>How to mix them in real life</h4><ul><li>Static shell + dynamic holes (PPR/streaming): Render nav/footer/above‑the‑fold statically; stream user‑specific data as it becomes available.</li><li>Edge gate, serverful backend: Do auth cookie verification and AB at the edge, forward to a regional app for heavy lifting.</li><li>Cache‑through on edge: Fetch regional data once, cache at the edge with short TTLs and tag‑based busting.</li></ul><h4>Anti‑patterns</h4><ul><li>Doing all SSR at the edge while your database lives in one region — you’ll pay the RTT tax on every request.</li><li>Making everything static and relying on client hydration to “fix” data freshness — you’ll ship too much JS and still show stale UI.</li><li>Pushing heavy Node‑only libraries to edge runtimes — you’ll hit platform limits and cold starts.</li></ul><h4>Rule of thumb</h4><ul><li>Start static where you can, go edge when you must, fall back to serverful when you need power.</li></ul><h4>A simple decision flow</h4><ol><li>Can it be the same for everyone for N minutes? Static/ISR.</li><li>If not, can logic run fast without private data? Edge.</li><li>If not, does it need heavy compute or private networks? Serverful.</li><li>Compose: static shell + streamed/edge islands + serverful APIs.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f720d69dc7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 21 is Coming]]></title>
            <link>https://medium.com/@vyakymenko/angular-21-is-coming-5bf438eb3c2c?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5bf438eb3c2c</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 14:41:00 GMT</pubDate>
            <atom:updated>2025-09-29T14:41:00.242Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAuteXWB3TI0ANxKzWHTNA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@bdv91?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Dmytro Bukhantsov</a> on <a href="https://unsplash.com/photos/a-tree-in-a-park-pOJz6pFwMxg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Angular Team released new Angular 21.next release. Many of us will be curious about the kind of features and bug fixes that we can see in this one.</p><p>Angular has been on a steady, predictable release cadence for years, with a focus on developer‑experience upgrades, performance and modern primitives like signals and the new control flow. With v20 out earlier in 2025, the next stop is Angular 21.</p><h3>A quick recap of where Angular is now</h3><ul><li>Standalone is the default. New projects and guides revolve around standalone APIs, route‑level providers, and feature modules via directory structure — not NgModules.</li><li>Signals and new control flow (<strong>@if</strong>, <strong>@for</strong>, <strong>@switch</strong>) are mainstream. Templates are cleaner, more predictable, and tree‑shakable.</li><li>SSR + hydration are first‑class. Streaming and island‑style hydration patterns are encouraged; build tooling is optimized accordingly.</li><li>Vite‑based builder and faster dev server workflows are the norm. DX continues to be a top priority.</li><li>Router is fully functional, with lazy, defer, and fine‑grained preloading patterns. Typed APIs and route data are widely used.</li></ul><p>If your app embraces the bullet points above, you’ve already done most of the work to make future upgrades smooth.</p><h3>What I’m watching for Angular 21</h3><p>These are areas that have seen active iteration across the last few releases and are likely to keep improving.</p><h4>Signals and zoneless change detection</h4><ul><li>Continued polish around signal ergonomics in templates and host bindings</li><li>Broader guidance for <strong>zoneless</strong> apps by default</li><li>Tooling and schematics that make the opt‑in story simpler for large apps</li></ul><h4>SSR, hydration, and streaming</h4><ul><li>More resilient hydration across complex component trees</li><li>Clearer, faster defaults for streaming in common setups</li><li>Better DX for debugging hydration mismatches</li></ul><h4>Router ergonomics and performance</h4><ul><li>Incremental data loading, smarter preloading strategies, and improved error/loading UI patterns</li><li>Typed redirects and cleaner route configuration ergonomics</li></ul><h4>Tooling and builder pipeline</h4><ul><li>Devserver/builder iterations focused on faster feedback loops</li><li>More consistent output chunking and better profiling hooks</li></ul><h4>CDK and Material (M3)</h4><ul><li>Accessibility and theming refinements</li><li>Better defaults for density, motion, and color systems aligned with Material 3</li></ul><h4>Typed forms, i18n, and testing</h4><ul><li>Continued improvements in typed forms ergonomics</li><li>I18n extraction/build stability for SSR</li><li>Test harnesses and faster component tests with the new test APIs</li></ul><h3>Durable patterns you can adopt now</h3><p>These are safe, forward‑compatible patterns you can put in production today to be ready for v21.</p><h4>Signals in components and templates</h4><pre>import { Component, signal, computed } from &#39;@angular/core&#39;;<br><br>@Component({<br>  selector: &#39;app-cart&#39;,<br>  standalone: true,<br>  template: `<br>    &lt;h2&gt;Cart ({{ count() }})&lt;/h2&gt;<br>    &lt;ul&gt;<br>      @for (item of items(); track item.id) {<br>        &lt;li&gt;<br>          {{ item.title }} — {{ item.price | currency }}<br>          &lt;button (click)=&quot;remove(item.id)&quot;&gt;Remove&lt;/button&gt;<br>        &lt;/li&gt;<br>      }<br>    &lt;/ul&gt;<br>    &lt;p&gt;Total: {{ total() | currency }}&lt;/p&gt;<br>  `,<br>})<br>export class CartComponent {<br>  readonly items = signal&lt;{ id: number; title: string; price: number }[]&gt;([]);<br>  readonly count = computed(() =&gt; this.items().length);<br>  readonly total = computed(() =&gt; this.items().reduce((s, i) =&gt; s + i.price, 0));<br><br>  add(item: { id: number; title: string; price: number }) {<br>    this.items.update(list =&gt; [...list, item]);<br>  }<br>  remove(id: number) {<br>    this.items.update(list =&gt; list.filter(i =&gt; i.id !== id));<br>  }<br>}</pre><h4>New control flow: @if, @for, @switch</h4><pre>&lt;!-- Cleaner and more powerful than *ngIf/*ngFor for complex UIs --&gt;<br>@if (user()) {<br>  &lt;h3&gt;Welcome, {{ user()!.name }}&lt;/h3&gt;<br>} @else {<br>  &lt;p&gt;Please sign in&lt;/p&gt;<br>}<br><br>@switch (status()) {<br>  @case (&#39;loading&#39;) { &lt;spinner/&gt; }<br>  @case (&#39;ready&#39;)   { &lt;dashboard/&gt; }<br>  @default          { &lt;p&gt;Error&lt;/p&gt; }<br>}</pre><h4>Defer non‑critical features</h4><pre>&lt;!-- Defer the heavy chart until it’s near viewport or idle --&gt;<br>@defer (on viewport; prefetch on idle) {<br>  &lt;app-heavy-chart /&gt;<br>} @placeholder {<br>  &lt;skeleton-chart /&gt;<br>} @loading {<br>  &lt;p&gt;Loading chart…&lt;/p&gt;<br>} @error {<br>  &lt;p&gt;Couldn’t load chart.&lt;/p&gt;<br>}</pre><h4>SSR + hydration defaults</h4><pre># Create a new app with SSR enabled<br>ng new my-app --ssr<br><br># Or add SSR to an existing project<br>ng add @angular/ssr</pre><h4>Functional router configuration with lazy boundaries</h4><pre>import { Routes } from &#39;@angular/router&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;&#39;,<br>    loadComponent: () =&gt; import(&#39;./home/home.component&#39;).then(m =&gt; m.HomeComponent),<br>  },<br>  {<br>    path: &#39;admin&#39;,<br>    loadChildren: () =&gt; import(&#39;./admin/routes&#39;).then(m =&gt; m.ADMIN_ROUTES),<br>    data: { preload: false },<br>  },<br>];</pre><h4>Route‑level providers and environment composition</h4><pre>import { provideHttpClient, withInterceptors } from &#39;@angular/common/http&#39;;<br><br>export const routes: Routes = [<br>  {<br>    path: &#39;feature&#39;,<br>    providers: [<br>      provideHttpClient(<br>        withInterceptors([<br>          (req, next) =&gt; next(req.clone({ setHeaders: { &#39;X-Feature&#39;: &#39;1&#39; } }))<br>        ])<br>      )<br>    ],<br>    loadComponent: () =&gt; import(&#39;./feature/feature.component&#39;).then(m =&gt; m.FeatureComponent)<br>  }<br>];</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5bf438eb3c2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS 2025 Container queries and style queries in real projects]]></title>
            <link>https://medium.com/@vyakymenko/css-2025-container-queries-and-style-queries-in-real-projects-c38af5a13aa2?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c38af5a13aa2</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 10:52:07 GMT</pubDate>
            <atom:updated>2025-09-29T10:52:07.435Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJXwkiMIExYirf79FEA3FQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@marcus_ganahl?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Marcus Ganahl</a> on <a href="https://unsplash.com/photos/text-W5qgKZj-qnk?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>If you’re like me, you’ve probably wrestled with components that look perfect in one column and fall apart in another. The first time I flipped a layout with just a container width — no media queries — I felt like I’d been cheating the system all these years. Container queries finally let our components listen to the space they actually get.</p><p>When container queries graduated from “<strong>someday</strong>” to “<strong>widely shipping</strong>” responsive CSS changed for good. In 2025, you can design and ship components that adapt to their parent, not the viewport, and you can conditionally style components based on the styling of their container too. This post is a field guide to using size queries, style queries, and container units in real projects — including patterns, migration strategies, and pitfalls to avoid.</p><h4>What you’ll learn:</h4><ul><li>When to use container queries vs. traditional media queries</li><li>How to set up containment correctly (and safely) in production</li><li>Practical size queries for cards, navigation, data tables, and complex layouts</li><li>Real‑world style queries for theme variants and density modes</li><li>Container units (<strong>cqw</strong>/<strong>cqh</strong>/<strong>cqi</strong>/<strong>cqmin</strong>/<strong>cqmax</strong>) and when they’re better than <strong>vw</strong>/<strong>vh</strong></li><li>Progressive enhancement and fallbacks so nothing breaks in older browsers</li><li>Performance, testing, and debugging tips</li></ul><h4>1) The problem container queries solve</h4><p>Viewport media queries are <strong>coarse</strong>. If a card moves from a wide main column to a tight sidebar, its rules shouldn’t depend on the device width. Component size and style should drive behavior. Container queries make components portable and truly reusable.</p><ul><li>Size queries: Style a component based on the container’s inline/block size.</li><li>Style queries: Style a component based on certain styles of its container (e.g., theme or density via custom properties, or other queryable discrete properties where supported).</li></ul><h4>2) Enabling container queries safely</h4><p>To query a container, you must designate an ancestor as a “container.” Do this on the component’s immediate wrapper or on a meaningful ancestor that defines available space.</p><p>Basic setup:</p><pre>/* 1) Make a container by type (the safest default is inline-size) */<br>.card-grid {<br>  container-type: inline-size; /* enables @container width queries for descendants */<br>  container-name: cards;       /* optional but helpful for named queries */<br>}<br><br>/* 2) Now descendants can use @container */<br>@container cards (width &gt; 42rem) { /* or (inline-size &gt; 42rem) */<br>  .card { grid-template-columns: 2fr 3fr; }<br>}</pre><p><strong>Rules of thumb:</strong></p><ul><li>Prefer container-type: inline-size on layout wrappers. It avoids unintended fragmentation and is compatible with most patterns. Reserve container-type: size for very specific cases where block-size also matters.</li><li>Name containers you’ll query from multiple places: container-name: sidebar; Then use @container sidebar (…).</li><li>Don’t over‑nest container contexts unnecessarily. Each container establishes a new query context; keep it predictable.</li></ul><h4>3) Real‑world size query patterns</h4><p>A. Responsive card that reflows media and content</p><pre>&lt;section class=&quot;card-grid&quot;&gt;<br>  &lt;article class=&quot;card&quot;&gt;<br>    &lt;img class=&quot;card__media&quot; src=&quot;cover.jpg&quot; alt=&quot;&quot; /&gt;<br>    &lt;div class=&quot;card__body&quot;&gt;<br>      &lt;h3&gt;Title&lt;/h3&gt;<br>      &lt;p&gt;Supporting copy…&lt;/p&gt;<br>      &lt;a class=&quot;button&quot; href=&quot;#&quot;&gt;Read more&lt;/a&gt;<br>    &lt;/div&gt;<br>  &lt;/article&gt;<br>  &lt;!-- repeat cards --&gt;<br>&lt;/section&gt;</pre><pre>.card-grid {<br>  display: grid;<br>  gap: 1rem;<br>  grid-template-columns: repeat(auto-fill, minmax(18rem, 1fr));<br>  container-type: inline-size;<br>  container-name: cards;<br>}<br><br>.card {<br>  display: grid;<br>  grid-template: &quot;media&quot; auto &quot;body&quot; 1fr / 1fr;<br>  background: #fff;<br>  border-radius: .75rem;<br>  overflow: clip; /* hide media overflow on rounded corners */<br>}<br><br>/* At wider container widths, switch to a side-by-side layout */<br>@container cards (width &gt;= 30rem) {<br>  .card { grid-template: &quot;media body&quot; auto / 2fr 3fr; }<br>  .card__media { block-size: 100%; object-fit: cover; }<br>}<br><br>/* Add a larger layout tier when the grid itself gets roomy */<br>@container cards (width &gt;= 60rem) {<br>  .card { grid-template-columns: 1.5fr 2fr; }<br>}</pre><p>B. Sidebar navigation that upgrades from icons to labeled items</p><pre>&lt;aside class=&quot;app-sidebar&quot;&gt;<br>  &lt;nav class=&quot;nav&quot;&gt;<br>    &lt;a class=&quot;nav__item&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;i-home&quot;&gt;&lt;/i&gt;&lt;span&gt;Home&lt;/span&gt;&lt;/a&gt;<br>    &lt;a class=&quot;nav__item&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;i-analytics&quot;&gt;&lt;/i&gt;&lt;span&gt;Analytics&lt;/span&gt;&lt;/a&gt;<br>    &lt;a class=&quot;nav__item&quot; href=&quot;#&quot;&gt;&lt;i class=&quot;i-settings&quot;&gt;&lt;/i&gt;&lt;span&gt;Settings&lt;/span&gt;&lt;/a&gt;<br>  &lt;/nav&gt;<br>&lt;/aside&gt;</pre><pre>.app-sidebar {<br>  inline-size: 3.5rem; /* collapsed by default (just icons) */<br>  container-type: inline-size;<br>  container-name: sidebar;<br>}<br><br>.nav__item { display: grid; grid-auto-flow: column; gap: .75rem; align-items: center; }<br>.nav__item span { display: none; }<br><br>@container sidebar (width &gt;= 10rem) {<br>  .nav__item span { display: inline; }<br>}</pre><p>C. Data table that progressively reveals columns</p><pre>.table-wrap { container-type: inline-size; }<br>.table { display: grid; grid-template-columns: 1fr 2fr; }<br><br>@container (width &gt;= 30rem) { /* no name → nearest container by default */<br>  .table { grid-template-columns: 1fr 2fr 1fr; }<br>}<br>@container (width &gt;= 50rem) {<br>  .table { grid-template-columns: 2fr 2fr 1fr 1fr; }<br>}</pre><h4>4) Style queries: component variants without extra classes</h4><p>Style queries let you write rules that respond to the styles of the container. In practice today, the most reliable approach is to query custom properties that you set on the container. This keeps the API explicit and works across composition boundaries.</p><p><strong>Example:</strong> card density and theme driven by container style</p><pre>&lt;section class=&quot;card-grid&quot; style=&quot;--density: compact; --theme: surface&quot;&gt;<br>  ...<br>&lt;/section&gt;</pre><pre>.card-grid { container-type: inline-size; }<br><br>/* Opt into a denser layout when the container declares it */<br>@container style(--density: compact) {<br>  .card { padding: .75rem; gap: .5rem; }<br>  .card h3 { font-size: 1rem; }<br>}<br><br>/* Theme variant controlled by container */<br>@container style(--theme: surface) {<br>  .card { background: #fff; color: #111; }<br>}<br>@container style(--theme: elevated) {<br>  .card { background: #fff; box-shadow: 0 2px 8px rgba(0,0,0,.1); }<br>}</pre><h4>Notes on style queries in 2025</h4><ul><li>Custom properties are the most portable way to express container state (theme, density, contrast mode, etc.).</li><li>Some engines support style queries for a subset of discrete properties (e.g., <strong>overflow: auto</strong>). Verify current support before relying on non‑custom‑property queries; keep a class or attribute‑based fallback if needed.</li><li>Keep queries readable and minimal. One or two style gates per component is usually enough.</li></ul><h4>5) Container units: cqw, cqh, cqi, cqmin, cqmax</h4><p>Container query units scale measurements to the query container instead of the viewport.</p><ul><li><strong>1cqw = 1%</strong> of the container’s inline size</li><li><strong>1cqh = 1%</strong> of the container’s block size</li><li><strong>1cqi = 1%</strong> of the smaller of the container’s inline/block size (in logical flow)</li><li><strong>cqmin/cqmax</strong> = <strong>min/max</strong> of the two axes</li></ul><p>Practical uses:</p><pre>.hero { container-type: inline-size; }<br>.hero__title { font-size: clamp(1.25rem, 3cqw + .75rem, 3rem); }<br>.card { padding: clamp(.75rem, 2cqw, 2rem); }</pre><p>Choose container units when the component should scale inside different columns or sidebars regardless of viewport. Prefer viewport units for page‑level hero sections that truly depend on viewport.</p><h4>6) Progressive enhancement and fallbacks</h4><p>You can ship container queries today with guard rails.</p><ul><li>Feature queries: Wrap advanced rules in @supports to avoid parse errors on very old engines.</li><li>Fallbacks first: Write a solid baseline without queries; then layer enhancements.</li><li>Don’t hide content that depends on a query. Degradation should be cosmetic, not functional.</li></ul><p>Example scaffold:</p><pre>/* Baseline (works everywhere) */<br>.card { display: grid; gap: 1rem; }<br><br>/* Enhance with container queries when supported */<br>@supports (container-type: inline-size) {<br>  .card-grid { container-type: inline-size; container-name: cards; }<br>  @container cards (width &gt;= 30rem) { .card { grid-template-columns: 2fr 3fr; } }<br>}</pre><h4>7) Architecture: where to place containers and queries</h4><ul><li>Layout wrappers define containers; components consume them.</li></ul><p>- Good: .sidebar, .content, .card-grid wrappers with container-type set.</p><p>- Avoid putting container-type on deeply nested nodes that don’t control space.</p><ul><li>Co-locate rules: Keep a component’s <strong>@container</strong> blocks near the base component styles for maintainability.</li><li>Name important containers you reference from multiple components.</li><li><strong>Limit tiers</strong>: Two or three size breakpoints per component is often enough. Too many tiers complicate testing.</li></ul><h4>8) Migration: from media queries to container queries</h4><p>Common refactor pattern for a section component:</p><p><strong>Before (viewport media query):</strong></p><pre>.section__content { display: grid; grid-template-columns: 1fr; }<br>@media (min-width: 900px) {<br>  .section__content { grid-template-columns: 1fr 2fr; }<br>}</pre><p><strong>After (container query):</strong></p><pre>.section { container-type: inline-size; }<br>.section__content { display: grid; grid-template-columns: 1fr; }<br>@container (width &gt;= 40rem) {<br>  .section__content { grid-template-columns: 1fr 2fr; }<br>}</pre><p><strong>Refactor tips:</strong></p><ul><li>Convert breakpoint px to rem tied to your root font-size so components scale with user preferences.</li><li>Choose container breakpoints that reflect component needs (e.g., when labels wrap) rather than viewport sizes.</li><li>Keep some page‑level media queries for global layout shifts (e.g., turning the whole app from single‑ to two‑column at xl).</li></ul><h4>9) Accessibility and UX considerations</h4><ul><li>Respect user font-size: use rem in thresholds to preserve behavior when users zoom.</li><li>Hit targets: at smaller container widths, increase vertical spacing or switch to stacked layouts to preserve touch targets.</li><li>Color contrast: when using style queries for theme variants, ensure contrast stays compliant in all variants.</li><li>Motion: if you animate layout transitions across container widths, honor prefers-reduced-motion.\</li></ul><h4>10) Performance: cost and hygiene</h4><p>Container queries are designed to be efficient, but any conditional layout logic can cost if abused.</p><ul><li>Keep containers purposeful. Avoid attaching container-type to hundreds of tiny nodes.</li><li>Prefer inline-size over size when block size isn’t truly needed.</li><li>Avoid thrashing: Don’t toggle container-type dynamically in JS. Toggle classes or custom properties on the container instead.</li><li>Audit in DevTools: Chrome DevTools highlights container query evaluation; watch for excessive reflows.</li></ul><h4>11) Debugging and testing</h4><ul><li>Visualize containers: temporary outline helps find the active container context.</li></ul><pre>/* debug only */<br>*[container-type] { outline: 1px dashed color-mix(in srgb, rebeccapurple 40%, transparent); }</pre><ul><li>Unit test thresholds: If you use component tests (Playwright/Vitest), render components in controlled width wrappers and assert class/role/visibility outcomes.</li><li>Storybook: Add “container width” and style knobs to stories so designers can preview tiers.</li></ul><h4>12) Interop with modern CSS features</h4><ul><li><strong>Subgrid</strong>: Combine container queries with subgrid to keep columns aligned while letting components rearrange within their allocated tracks.</li><li><strong>:has()</strong>: Useful for stateful thresholds, e.g., cards that switch layout when they contain an image or a long label — combine with size queries for robust behavior.</li><li>View transitions: When tiers switch, wrap structural changes with polite transitions; avoid disorienting large jumps.</li></ul><h4>13) Browser support (early 2025 snapshot)</h4><ul><li>Size queries (<strong>@container </strong>width/inline-size, etc.): broadly supported in current Chrome, Edge, Safari, and Firefox stable.</li><li>Style queries (<strong>@container</strong> style(…)):</li></ul><p>- Supported in Chromium‑based browsers and recent Safari for custom property queries; broader property support varies.</p><p>- Firefox support is in progress/behind a flag in some versions. Verify before relying on non‑custom‑property queries.</p><ul><li>Container units (<strong>cqw</strong>, <strong>cqh</strong>, <strong>cqi</strong>, <strong>cqmin</strong>, <strong>cqmax</strong>): shipping in Chromium and Safari; Firefox support landing/behind a flag in some channels.</li></ul><p>Always verify with caniuse.com or MDN for the exact versions you target, and gate advanced bits with `<strong>@supports</strong>`.</p><h4>14) Patterns you’ll reuse</h4><ul><li>Card media flip: Stack → side‑by‑side at 30rem container width.</li><li>Menu labeling: Icons only → icons + labels at 10rem container width.</li><li>Dense mode: <strong>@container</strong> style( — density: compact) to tighten spacing.</li><li>Themed surfaces: <strong>@container</strong> style( — theme: elevated) for shadowed cards inside certain sections.</li><li>Scalable type: <strong>clamp()</strong> with cqw for headings that fit their column.</li></ul><h4>15) A small, shippable starter</h4><pre>&lt;section class=&quot;feature-list&quot;&gt;<br>  &lt;article class=&quot;feature&quot;&gt;<br>    &lt;h3&gt;Fast&lt;/h3&gt;<br>    &lt;p&gt;Blazing performance at scale.&lt;/p&gt;<br>  &lt;/article&gt;<br>  &lt;article class=&quot;feature&quot;&gt;<br>    &lt;h3&gt;Secure&lt;/h3&gt;<br>    &lt;p&gt;Privacy‑first by design.&lt;/p&gt;<br>  &lt;/article&gt;<br>  &lt;article class=&quot;feature&quot;&gt;<br>    &lt;h3&gt;Open&lt;/h3&gt;<br>    &lt;p&gt;Built on web standards.&lt;/p&gt;<br>  &lt;/article&gt;<br>&lt;/section&gt;</pre><pre>.feature-list {<br>  display: grid;<br>  gap: 1rem;<br>  grid-template-columns: repeat(auto-fill, minmax(16rem, 1fr));<br>  container-type: inline-size;<br>  container-name: features;<br>}<br>.feature { padding: 1rem; border: 1px solid #ddd; border-radius: .5rem; }<br><br>@container features (width &gt;= 28rem) {<br>  .feature-list { gap: 1.25rem; }<br>  .feature { padding: 1.25rem; }<br>}<br><br>/* Optional density via style query */<br>@container style(--density: compact) {<br>  .feature { padding: .75rem; }<br>}<br><br>/* Scalable heading with container units */<br>.feature h3 { font-size: clamp(1rem, 2.5cqw + .5rem, 1.5rem); }</pre><h4>16) FAQs</h4><blockquote>Q: Do I still need media queries?</blockquote><blockquote>A: Yes. Keep page‑level layout and OS‑level preferences (dark mode, reduced motion) in media queries. Use container queries inside components.</blockquote><blockquote>Q: Should I use container-type: size everywhere?</blockquote><blockquote>A: No. Start with inline-size. Use size only when the block axis must be considered, and you’ve validated the layout.</blockquote><blockquote>Q: Can I nest containers?</blockquote><blockquote>A: Yes, but be intentional. Each @container without a name matches the nearest container ancestor. Use names when crossing component boundaries.</blockquote><blockquote>Q: Are style queries stable enough for production?</blockquote><blockquote>A: For custom property queries, yes in most evergreen browsers. For querying other properties, verify support and keep fallbacks.</blockquote><h4>References and further reading</h4><ul><li>MDN: Container queries overview — <a href="https://developer.mozilla.org/docs/Web/CSS/CSS_container_queries">https://developer.mozilla.org/docs/Web/CSS/CSS_container_queries</a></li><li>Spec drafts (CSS Containment Module Level 3/4)</li><li>“Style Queries” explainer — <a href="https://github.com/w3c/csswg-drafts/issues/6399">https://github.com/w3c/csswg-drafts/issues/6399</a></li><li>Can I use: container queries, style() queries, container units — <a href="https://caniuse.com/">https://caniuse.com</a></li><li>Chromium and WebKit release notes for latest property support</li></ul><p>If you adopt only one thing this quarter, make it this: move responsive logic into the component. Container and style queries make your UI more portable, robust, and easier to design. Ship them behind `<strong>@supports</strong>`, and you’ll be future‑proof without leaving any users behind.</p><h3>— Thanks for reading.</h3><p>If you ship something cool with container or style queries, I’d love to hear about it. Ping me on <a href="https://x.com/valeyakymenko">Twitter/X</a> or drop me a message on Medium to make this guide better.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c38af5a13aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Server Components in practice (Next.js]]></title>
            <link>https://medium.com/@vyakymenko/react-server-components-in-practice-next-js-d1c3c8a4971f?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1c3c8a4971f</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 11:21:41 GMT</pubDate>
            <atom:updated>2025-09-26T11:21:41.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Server Components in practice (Next.js App Router patterns, streaming, caching, partial pre‑render)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1sOrUA6_IRkGrjmZFrKqYw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@nahakiole?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Robin Glauser</a> on <a href="https://unsplash.com/photos/assorted-color-capacitors-on-white-surface-WgMlXuSv-8A?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><h3>TL;DR</h3><ul><li>React Server Components (RSC) let you render on the server by default in the Next.js App Router, shipping almost zero JS for those components and enabling data‑fetch close to the source.</li><li>Use server components for data fetching, composition, and heavy dependencies; use client components only when you need interactivity, browser APIs, or local state with hooks.</li><li>Stream with Suspense boundaries, loading.js, and nested layout/page segments to render critical UI first and progressively hydrate islands.</li><li>Know your caches: request memoization, the data cache, the full route cache (static/PPR), and the router cache. Control them with fetch cache modes, revalidate options, and cache tags.</li><li>Partial Prerendering (PPR) lets you statically pre‑render a shell while streaming dynamic holes on request. It gives the best of SSG’s TTFB and SSR’s freshness.</li></ul><h3><strong>1) </strong>What are React Server Components (RSC)?</h3><p>RSC allow components to run on the server at request time (or build/static time) and return a serialized description of UI to the client. In the App Router, all components are server components by default. Client components are opt‑in via the “use client” directive at the top of a file.</p><h4>Key properties</h4><ul><li>No client bundle for server components: they don’t ship JS to the browser.</li><li>Async/await in components: you can await promises directly in server components.</li><li>Component boundaries matter: a server component can render a client component as a child, but not the other way around.</li><li>Data proximity: fetch from the server component; avoid API ping‑pong.</li></ul><h4>When to use which</h4><ul><li>Server component (default): data fetching, heavy libs (DB/SDK), environment secrets, markdown/MDX processing, large lists.</li><li>Client component (“use client”): interactivity (onClick, forms with local state), browser APIs (window, localStorage), animations, focus management.</li></ul><h3>2) App Router mental model and file system patterns</h3><ul><li>app/layout.tsx: server component defining global chrome (header/footer). Can wrap children with Suspense for streaming.</li><li>app/page.tsx: the root route’s server component. Nested routes use app/(group)/segment/page.tsx.</li><li>app/loading.tsx: special component shown immediately while the nearest parent Suspense boundary streams children.</li><li>app/template.tsx vs layout.tsx: template re‑renders per navigation; layout persists across navigations.</li><li>Client islands: place “use client” at the top of files that need interactivity. Keep them leaf‑like.</li><li>Route handlers: app/api/foo/route.ts for server‑only endpoints when needed.</li><li>Server Actions: mutate data directly from a server component or client form without a bespoke API route.</li></ul><h4>Example structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*GK0FjaeQHcgxsOC8tCmy6g.png" /></figure><h3>3) Data fetching patterns in server components Simple fetch with caching</h3><pre>// app/dashboard/page.tsx (server component)<br>export default async function DashboardPage() {<br>  const res = await fetch(&quot;https://api.example.com/summary&quot;, {<br>    // default is &#39;force-cache&#39; in RSC, but make it explicit for clarity<br>    cache: &quot;force-cache&quot;,<br>    next: { revalidate: 3600, tags: [&quot;summary&quot;] },<br>  });<br>  const data = await res.json();<br>  return (<br>    &lt;main&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br>      &lt;Summary data={data} /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><h4>Fresh on every request</h4><pre>await fetch(url, { cache: &quot;no-store&quot; });</pre><h4>Time‑based revalidation (ISR)</h4><pre>await fetch(url, { next: { revalidate: 300 } }); // 5 minutes</pre><h4>Tag‑based cache invalidation</h4><pre>import { revalidateTag } from &quot;next/cache&quot;;<br><br>// In a server action after a mutation<br>revalidateTag(&quot;summary&quot;);</pre><h4>Path revalidation</h4><pre>import { revalidatePath } from &quot;next/cache&quot;;<br>await revalidatePath(&quot;/dashboard&quot;, &quot;page&quot;);</pre><h4>For per‑request memoization (avoid duplicate fetches within one render):</h4><ul><li>fetch is request‑memoized automatically in the same context.</li><li>You can also use the cache(fn) helper from react for idempotent computations.</li></ul><pre>import { cache } from &quot;react&quot;;<br><br>export const getUser = cache(async (id: string) =&gt; {<br>  const res = await fetch(`https://api.example.com/users/${id}`, { cache: &quot;force-cache&quot; });<br>  return res.json();<br>});</pre><h4>Dynamic vs static segments</h4><ul><li>Static by default if all data is cacheable (force-cache or revalidate) and no dynamic APIs (cookies(), headers()) are used.</li><li>Mark a route dynamic at the segment level: export const dynamic = “force-dynamic”; or revalidate = 0.</li><li>Or mark the whole route static: export const dynamic = “error”; or export const revalidate = 600.</li></ul><pre>// app/products/[id]/page.tsx<br>export const dynamic = &quot;force-dynamic&quot;; // always run on request<br>// OR<br>export const revalidate = 600;           // statically generate and revalidate</pre><h3>4) Streaming with Suspense, loading.js, and nested layouts</h3><p>Streaming lets the server flush HTML for resolved parts of the tree while slower branches continue in the background.</p><h4>Patterns</h4><ul><li>Wrap slow children with Suspense to stream a placeholder immediately.</li><li>Use app/segment/loading.tsx to show route‑level pending UI.</li><li>Use nested layouts for progressive reveal across sections.</li></ul><h4>Example</h4><pre>// app/layout.tsx (server)<br>import { Suspense } from &quot;react&quot;;<br><br>export default function RootLayout({ children }: { children: React.ReactNode }) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;Header /&gt;<br>        &lt;Suspense fallback={&lt;NavSkeleton /&gt;}&gt;<br>          {/* Nav may read user and permissions */}<br>          &lt;Nav /&gt;<br>        &lt;/Suspense&gt;<br>        &lt;main&gt;{children}&lt;/main&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><pre>// app/dashboard/page.tsx (server)<br>import { Suspense } from &quot;react&quot;;<br><br>export default function DashboardPage() {<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Dashboard&lt;/h1&gt;<br>      &lt;div className=&quot;grid&quot;&gt;<br>        &lt;Suspense fallback={&lt;CardSkeleton title=&quot;Revenue&quot; /&gt;}&gt;<br>          {/* Streams when ready */}<br>          &lt;Revenue /&gt;<br>        &lt;/Suspense&gt;<br>        &lt;Suspense fallback={&lt;CardSkeleton title=&quot;Top Products&quot; /&gt;}&gt;<br>          &lt;TopProducts /&gt;<br>        &lt;/Suspense&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><pre>// app/dashboard/loading.tsx<br>export default function Loading() {<br>  return &lt;PageSkeleton /&gt;; // immediate first paint while server streams<br>}</pre><h4>Notes</h4><ul><li>Avoid putting “use client” above a large subtree; it blocks server streaming for that subtree.</li><li>Keep client components as leaves, and pass data from server parents as props.</li></ul><h3>5) Partial Prerendering (PPR)</h3><p>PPR renders a static shell at build time (or ISR) and treats some child regions as dynamic “holes” that stream on request. This gives near‑SSG TTFB for the shell while keeping dynamic sections fresh.</p><h4>Enablement and behavior</h4><ul><li>PPR support depends on your Next.js version. In recent versions with the App Router, PPR can be enabled per route or project. Check the Next.js docs for the version you use.</li><li>A page becomes partially prerenderable when: the layout/template and immediate shell are static, and dynamic children are isolated behind Suspense boundaries.</li></ul><h4>Authoring for PPR</h4><ul><li>Make the shell static by default (cacheable fetches, no cookies()/headers() in the shell).</li><li>Wrap dynamic parts with Suspense so they can be deferred.</li><li>Use revalidate or cache tags on dynamic parts to tune freshness.</li></ul><h4>Example</h4><pre>// app/products/[id]/page.tsx<br>export const revalidate = 3600; // static shell with ISR<br><br>export default function ProductPage({ params }: { params: { id: string } }) {<br>  return (<br>    &lt;&gt;<br>      {/* Shell is static: title, meta, stable copy */}<br>      &lt;ProductHero id={params.id} /&gt;<br>      {/* Dynamic holes stream on request: price, stock, personalized offers */}<br>      &lt;Suspense fallback={&lt;PriceSkeleton /&gt;}&gt;<br>        &lt;LivePrice id={params.id} /&gt;<br>      &lt;/Suspense&gt;<br>      &lt;Suspense fallback={&lt;StockSkeleton /&gt;}&gt;<br>        &lt;StockLevel id={params.id} /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>6) Caching layers you should actually care about</h3><ul><li>Request memoization: dedupes identical fetch() calls within the same request/render.</li><li>Data Cache: persists fetch responses according to cache: and next: options. Revalidated by time or tags.</li><li>Full Route Cache: the HTML/Flight payload for static/PPR output, served by the edge/node without recompute until revalidation.</li><li>Router Cache (client): preserves component state between navigations and speeds up back/forward.</li></ul><h4>Choosing cache mode</h4><ul><li>Global freshness required: cache: “no-store”.</li><li>Mostly static with acceptable staleness: next: { revalidate: N }.</li><li>On‑demand invalidation after writes: next: { tags: […] } + revalidateTag().</li><li>Avoid cache stampede: prefer reasonable revalidate windows over no-store when possible; use suspense to stream.</li></ul><h4>Pitfall: mixing cookies()/headers() in a supposedly static shell marks the route dynamic and disables the full route cache. Isolate such reads to dynamic children behind Suspense.</h4><h3>7) Server Actions in practice</h3><p>Server Actions let you mutate data without creating an API route and then revalidate.</p><pre>// app/actions.ts<br>&quot;use server&quot;;<br>import { revalidatePath, revalidateTag } from &quot;next/cache&quot;;<br><br>export async function saveSettings(input: FormData) {<br>  // perform mutation (DB call)<br>  // ...<br>  revalidatePath(&quot;/dashboard&quot;);<br>  revalidateTag(&quot;summary&quot;);<br>}</pre><pre>// app/dashboard/SettingsForm.tsx<br>&quot;use client&quot;;<br>import { experimental_useFormStatus as useFormStatus } from &quot;react-dom&quot;;<br>import { saveSettings } from &quot;../actions&quot;;<br><br>export function SettingsForm() {<br>  const { pending } = useFormStatus();<br>  return (<br>    &lt;form action={saveSettings}&gt;<br>      &lt;input name=&quot;email&quot; type=&quot;email&quot; required /&gt;<br>      &lt;button disabled={pending}&gt;{pending ? &quot;Saving...&quot; : &quot;Save&quot;}&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><h4>Notes</h4><ul><li>Mark server action files with “use server” at the top.</li><li>Prefer tag/path revalidation that matches the data your page consumes.</li></ul><h4>8) Real‑world recipes</h4><p><strong>A.</strong> Personalized dashboard with fast TTFB</p><ul><li>Make layout and header static.</li><li>Use loading.tsx for instant shell.</li><li>Read user session only inside dynamic children (e.g.,), wrapped in Suspense.</li><li>Stream slow widgets individually with Suspense; set per‑widget revalidate windows.</li></ul><p><strong>B. </strong>Product page SEO with live price</p><ul><li>Statically prerender product details from CMS (revalidate 24h).</li><li>Stream and from commerce API with revalidate: 60.</li><li>Invalidate price tag on updates from webhook via revalidateTag(“product:123:price”).</li></ul><p><strong>C. </strong>Search results</p><ul><li>Mark route dynamic with export const dynamic = “force-dynamic”.</li><li>Use cache: “no-store” for the search request.</li><li>Stream filters sidebar (cacheable) and results list (dynamic) separately with Suspense.</li></ul><h3>9) Common pitfalls and how to avoid them</h3><ul><li>Accidentally promoting a whole subtree to client: putting “use client” high in the tree disables RSC benefits for that subtree. Keep client components leaf‑level.</li><li>Reading cookies/headers in layouts: this forces dynamic rendering and disables static/PPR. Read them only where truly needed.</li><li>Coupling fetch freshness to UI: prefer decoupling via Suspense + streaming rather than making everything dynamic.</li><li>Overusing revalidatePath: prefer fine‑grained tags so you don’t bust unrelated caches.</li><li>Blocking user interaction while streaming: use optimistic UI in client components and let server stream confirmatory data.</li></ul><h3>10) Debugging and observability tips</h3><ul><li>next dev shows which routes are static or dynamic during build/logs.</li><li>Use React DevTools Profiler and the Next.js overlay to see Suspense waterfalls.</li><li>Log cache headers on your API to validate caching behavior. Consider CDN caching for static assets and full route cache.</li></ul><h3>11) Migration notes (from Pages Router)</h3><ul><li>Move data fetching from getServerSideProps/getStaticProps into server components.</li><li>Replace client‑heavy pages with server components plus small client islands for interactivity.</li><li>Adopt loading.tsx and Suspense to preserve UX during SSR/streaming.</li></ul><h3>12) Checklist</h3><ul><li>Is the shell static or cacheable? If not, can I isolate dynamic bits behind Suspense?</li><li>Are client components leaf‑like and minimal?</li><li>Do I have clear revalidate windows or tags for each fetched dataset?</li><li>Are Server Actions revalidating only what’s necessary?</li><li>Are Suspense boundaries placed to maximize first paint and minimize waterfalls?</li></ul><h4>Further reading recomendation</h4><ul><li><a href="https://nextjs.org/docs/app">Next.js App Router docs</a></li><li><a href="https://react.dev/reference/rsc/server-components">React documentation on Server Components and Suspense</a></li><li><a href="https://nextjs.org/docs/app/getting-started/caching-and-revalidating">Caching and Revalidation in Next.js</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1c3c8a4971f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reducing NX + Next.js Docker Container Size for 94%]]></title>
            <link>https://medium.com/@vyakymenko/reducing-nx-next-js-docker-container-size-30fbeeb361cb?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fbeeb361cb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[nx]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Mon, 21 Oct 2024 06:59:40 GMT</pubDate>
            <atom:updated>2024-10-22T05:34:39.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wRV3q_SZtNYTsgr-B_VRdw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@frankiefoto?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">frank mckenna</a> on <a href="https://unsplash.com/photos/assorted-color-filed-intermodal-containers-tjX_sniNzgQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3m-UsxaXop6jIg59YqQ7bQ.png" /></figure><p>Optimizing the size of your Docker container will make your NX + Next.js applications faster to build, deploy, and run. This guide will walk you through several strategies to achieve a leaner Docker container for your <strong>NX</strong> + <strong>Next.js</strong> projects.</p><h4>Starting point</h4><p>Guys reached to me with question “Can we make our docker container smaller?” Size was around 4.75Gb and was impressed how did it happen. Ofcourse the first answer was incorrect Dockerfile so let’s check it as a starting point.</p><pre># Frontend Dockerfile<br><br># Step 1: Use an official Node.js image (LTS version)<br>FROM node:20-alpine<br><br># Step 2: Set the working directory inside the container<br>WORKDIR /app<br><br># Step 3: Copy the package.json and package-lock.json files<br>COPY package*.json ./<br><br># Step 4: Install the project dependencies<br>RUN npm install<br><br>ENV PORT 4200<br><br># Step 5: Copy the rest of your frontend code to the container<br>COPY ./ ./<br><br># Step 6: Expose the port your Next.js app will run on<br>EXPOSE 4200<br><br># Build Production Build<br>RUN npm run build.docker.web<br><br>WORKDIR /app/dist/apps/web<br><br># Step 7: Run the Next.js app with the specified script<br>CMD [&quot;npm&quot;, &quot;run&quot;, &quot;start&quot;]</pre><p>Then moving on to the next.config.js .</p><pre>//@ts-check<br><br>// eslint-disable-next-line @typescript-eslint/no-var-requires<br>const { composePlugins, withNx } = require(&#39;@nx/next&#39;);<br><br>/**<br> * @type {import(&#39;@nx/next/plugins/with-nx&#39;).WithNxOptions}<br> **/<br>const nextConfig = {<br>  reactStrictMode: false,<br>  nx: {<br>    // Set this to true if you would like to use SVGR<br>    // See: https://github.com/gregberge/svgr<br>    svgr: false,<br>  },<br>  images: {<br>    domains: [&#39;storage.googleapis.com&#39;],<br>  },<br>};<br><br>const plugins = [<br>  // Add more Next.js plugins to this list if needed.<br>  withNx,<br>];<br><br>module.exports = composePlugins(...plugins)(nextConfig);</pre><p>After analysis of these two files we can see that our build is not optimal at all.</p><p>I will <strong>NOT</strong> waste you time and divide each optimization step which is done, let’s dive into production ready solution, bellow I will explain the steps which we’ve did.</p><p>Dockerfile</p><pre># Variables<br>ARG VERSION=20-alpine<br>ARG DIR=app<br><br># BUILDER STAGE<br>FROM node:${VERSION} as builder<br>ARG DIR<br>WORKDIR /${DIR}<br><br>COPY . .<br>RUN npm install<br>RUN npm run build.docker.web<br><br># RUNNER STAGE<br>FROM node:${VERSION} as runner<br>ARG DIR<br>WORKDIR /${DIR}<br>ENV PORT 4200<br><br>COPY --from=builder ${DIR}/dist/apps/web/.next/standalone .<br>COPY --from=builder ${DIR}/dist/apps/web/public apps/web/public<br>COPY --from=builder ${DIR}/dist/apps/web/.next/static dist/apps/web/.next/static<br><br>EXPOSE 4200<br>ENTRYPOINT [&quot;node&quot;, &quot;apps/web/server.js&quot;]</pre><p><em>Note: Npm script</em> build.docker.web</p><pre>&quot;build.docker.web&quot;: &quot;nx build web&quot;,</pre><p>next.config.js</p><pre>//@ts-check<br><br>// eslint-disable-next-line @typescript-eslint/no-var-requires<br>const { composePlugins, withNx } = require(&#39;@nx/next&#39;);<br><br>/**<br> * @type {import(&#39;@nx/next/plugins/with-nx&#39;).WithNxOptions}<br> **/<br>const nextConfig = {<br>  reactStrictMode: false,<br>  output: &#39;standalone&#39;,<br>  outputStyle: &#39;compressed&#39;,<br>  nx: {<br>    // Set this to true if you would like to use SVGR<br>    // See: https://github.com/gregberge/svgr<br>    svgr: false,<br>  },<br>  images: {<br>    domains: [&#39;storage.googleapis.com&#39;],<br>  },<br>};<br><br>const plugins = [<br>  // Add more Next.js plugins to this list if needed.<br>  withNx,<br>];<br><br>module.exports = composePlugins(...plugins)(nextConfig);</pre><h4>Explanation</h4><p>So for our example we have a huge <strong>Next.js</strong> application with <strong>NX</strong> workspace called <strong>web</strong>.</p><p>Firstly we need to generate a proper Next.js build with node modules that required and of course it should be compressed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*KjYs3QEgguTYd37SckEcWA.png" /></figure><p>Once our initial configuration steps ready we moving to the Dockerfile and creating 2 stages: <strong>builder</strong>, <strong>runner</strong>.</p><p>During <strong>builder stage</strong> we are installing required dependencies and building our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/1*U8ez2kSDWeViz-50F_JVsw.png" /></figure><p>In <strong>runner stage</strong> we are taking our built application with dependencies and copying them to run our build.</p><p><em>Note:</em> <strong><em>It’s an example of NX + Next.js. </em></strong><em>If you are using standard Next.js </em><em>create-next-app </em><strong><em>copy</em></strong><em> </em><strong><em>path</em></strong><em> will be different.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*4gfXceQ2A7vF3hg9HuRKFw.png" /></figure><p>Also pay attention to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*FJ_i5osc8Vg3PDdT9KsmPg.png" /></figure><p><strong>Path will be different if you have a different app name!</strong></p><p>Example, if app called my-supper-app we will have something like this:</p><pre># RUNNER STAGE<br>FROM node:${VERSION} as runner<br>ARG DIR<br>WORKDIR /${DIR}<br>ENV PORT 4200<br><br>COPY --from=builder ${DIR}/dist/apps/my-supper-app/.next/standalone .<br>COPY --from=builder ${DIR}/dist/apps/my-supper-app/public apps/web/public<br>COPY --from=builder ${DIR}/dist/apps/my-supper-app/.next/static dist/apps/my-supper-app/.next/static<br><br>EXPOSE 4200<br>ENTRYPOINT [&quot;node&quot;, &quot;apps/my-supper-app/server.js&quot;]</pre><p>After all our optimizations container size is now only <strong>293.78mb</strong> against <strong>4.75Gb</strong> previously.</p><p>Thank for reeding, I hope this article will help you to create well optimized docker container for Nx+Next.js apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fbeeb361cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 18: A Comprehensive Guide to the Latest Features and Improvements]]></title>
            <link>https://medium.com/@vyakymenko/react-18-a-comprehensive-guide-to-the-latest-features-and-improvements-82825f209ae7?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/82825f209ae7</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Thu, 13 Apr 2023 07:14:55 GMT</pubDate>
            <atom:updated>2023-04-13T07:14:55.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVBPB8dmWCpGk4HJX8iFkg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@nublson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Nubelson Fernandes</a> on <a href="https://unsplash.com/s/photos/React?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Lets explore the most recent version of React, diving into key features, improvements, and best practices to leverage in your projects.</p><h3>Introduction to React 18</h3><p>Hey fellow developer! Welcome to this comprehensive guide on React 18. We’ll provide an overview of the latest version of React, discuss the key features and improvements, and compare it to previous versions. So, let’s dive in!</p><p>React 18 is the latest major release of the popular JavaScript library for building user interfaces. The React team has been hard at work to bring us new features and optimizations that improve both the developer experience and application performance.</p><p>Some of the most notable features and improvements in React 18 include:</p><ol><li>Concurrent Mode: This long-awaited feature allows React to work on multiple tasks simultaneously, leading to a smoother, more responsive user interface. This is particularly useful for complex and data-heavy applications, as it prevents the UI from becoming unresponsive due to long-running tasks.</li><li>React Server Components: This new feature enables developers to build modern applications with server-rendered components, improving performance and reducing the amount of JavaScript code that needs to be sent to the client.</li><li>Automatic Batching: React 18 now batches multiple state updates together, reducing the number of renders and improving performance. This is particularly useful in situations where multiple updates occur in quick succession, such as in response to user input.</li><li>Improved Suspense: React 18 brings enhancements to the Suspense feature, making it easier to handle data fetching, loading states, and error boundaries in your applications.</li></ol><p>Compared to previous versions, React 18 offers a more efficient and flexible approach to building user interfaces, with a strong focus on performance and developer experience. While some of these features were available as experimental features in previous versions, they are now stable and ready for use in production applications.</p><p>In the following chapters, we’ll dive deeper into each of these features and learn how to implement them in our projects. We’ll also explore best practices, migration strategies, and integration with other tools and libraries in the React ecosystem.</p><h3>Concurrent Mode in React 18</h3><p>Concurrent Mode is a new way for React to handle the rendering of components and updates to the DOM. It allows React to work on multiple tasks simultaneously without blocking the main thread, resulting in a smoother and more responsive user interface. This is especially beneficial for large, complex applications where long-running tasks can cause the UI to become unresponsive.</p><p>Here are some of the key benefits of Concurrent Mode:</p><ol><li>Improved responsiveness: By allowing React to work on multiple tasks at once, your application can remain responsive even during heavy workloads or when rendering large component trees.</li><li>Smoother transitions: Concurrent Mode helps to avoid janky animations and transitions by prioritizing user interactions over other tasks.</li><li>Easier to reason about: By introducing a more predictable rendering model, Concurrent Mode makes it easier to understand and reason about the behavior of your application.</li></ol><p>Now, let’s see how we can enable Concurrent Mode in our React application. It’s important to note that Concurrent Mode is an opt-in feature, which means you’ll need to explicitly enable it for your application.</p><p>First, you’ll need to update your React and ReactDOM packages to version 18 or higher. You can do this using your package manager of choice:</p><pre>npm install react@18 react-dom@18</pre><p>Next, you’ll need to wrap your application’s root component with the createRoot function from the react-dom package. Replace the traditional ReactDOM.render function with the new createRoot function like this:</p><pre>import ReactDOM from &#39;react-dom&#39;;<br>import App from &#39;./App&#39;;<br><br>const root = document.getElementById(&#39;root&#39;);<br>ReactDOM.createRoot(root).render(&lt;App /&gt;);</pre><p>That’s it! With just a few simple changes, you’ve enabled Concurrent Mode in your React application.</p><p>It’s important to note that while Concurrent Mode provides many benefits, it may also expose issues in your existing codebase. It’s recommended to test your application thoroughly after enabling Concurrent Mode to ensure everything works as expected.</p><h3>React Server Components</h3><p>React Server Components aim to improve application performance by reducing the amount of JavaScript code sent to the client. They enable you to offload some of the rendering work to the server, which can result in faster initial load times and improved user experience, especially on slower devices and networks.</p><p>Let’s first briefly compare server rendering and client rendering:</p><ol><li>Server rendering: Components are rendered on the server and sent to the client as HTML. This can lead to faster initial load times and improved SEO but may result in slower interactivity as the client waits for data to be fetched from the server.</li><li>Client rendering: Components are rendered on the client-side, usually in the browser. This approach provides faster interactivity but may result in slower initial load times as the client has to download and parse JavaScript code before rendering components.</li></ol><p>React Server Components strike a balance between these two approaches. They are rendered on the server but can be seamlessly integrated with client-rendered components, allowing you to build applications that are both fast and interactive.</p><p>Here’s how you can start using React Server Components in your application:</p><ol><li>Update your React and ReactDOM packages to version 18 or higher, if you haven’t already:</li></ol><pre>npm install react@18 react-dom@18</pre><ol><li>Create a new file for your Server Component with the .server.js extension, like MyServerComponent.server.js. This naming convention is important, as it tells React that this file contains a Server Component:</li></ol><pre>// MyServerComponent.server.js<br>import { useState } from &#39;react&#39;;<br><br>function MyServerComponent() {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Server-rendered count: {count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MyServerComponent;</pre><ol><li>Import and use your Server Component in a client component:</li></ol><pre>// App.js<br>import MyServerComponent from &#39;./MyServerComponent.server&#39;;<br><br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;React Server Components Demo&lt;/h1&gt;<br>      &lt;MyServerComponent /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Keep in mind that React Server Components have some limitations, such as not being able to use DOM-related APIs or certain React features like useLayoutEffect. Make sure to check the documentation for a complete list of limitations and best practices when working with Server Components.</p><h3>Automatic Batching for Improved Performance</h3><p>In React 18, automatic batching is introduced as a new feature to optimize performance. This chapter will provide an overview of automatic batching, explain how it works in React 18, and discuss the performance benefits and use cases of this feature.</p><p>Automatic batching is a mechanism that combines multiple state updates into a single render cycle. In previous versions of React, multiple state updates within event handlers were already batched. However, with React 18, this batching behavior is extended to asynchronous operations and other scenarios as well. This allows the application to render more efficiently by reducing the number of render cycles needed.</p><p>Here’s an example that demonstrates the difference in behavior between React 17 and React 18:</p><pre>// React 17 behavior<br>setTimeout(() =&gt; {<br>  setCount1(count1 + 1); // Render 1<br>  setCount2(count2 + 1); // Render 2<br>}, 1000);<br><br>// React 18 behavior<br>setTimeout(() =&gt; {<br>  setCount1(count1 + 1); // Batched render<br>  setCount2(count2 + 1); // Batched render<br>}, 1000);</pre><p>In React 17, the two state updates within the setTimeout would trigger two separate renders. However, in React 18, these updates are automatically batched together, resulting in just one render cycle.</p><p>The benefits of automatic batching include:</p><ol><li>Improved performance: By reducing the number of renders, automatic batching can lead to a significant performance improvement, especially when dealing with multiple state updates in quick succession.</li><li>Simplified code: With automatic batching, you don’t need to manually group state updates together using ReactDOM.unstable_batchedUpdates or other workarounds.</li><li>More predictable behavior: Automatic batching makes it easier to reason about your application’s behavior, as you no longer need to worry about the specific timing of state updates and renders.</li></ol><p>In conclusion, automatic batching is a powerful feature in React 18 that enables you to optimize the performance of your application by reducing the number of render cycles needed. By taking advantage of this feature, you can create more efficient and responsive applications, providing a better user experience.</p><p>In upcoming chapters, we’ll explore other new features and improvements in React 18, such as enhanced Suspense and React DevTools updates. Stay tuned as we continue to delve into the exciting world of React 18!</p><h3>New Suspense Features and Improvements</h3><p>React 18 brings several improvements to Suspense, including better support for handling loading states and error boundaries, integration with Concurrent Mode, and support for Server Components. These enhancements make it even more powerful and easier to work with.</p><p>Let’s start by discussing how to use Suspense for data fetching. In React 18, you can use the fetch function in combination with the useTransition and useDeferredValue hooks to fetch data and manage loading states:</p><ol><li>First, create a utility function to fetch data:</li></ol><pre>// api.js<br>async function fetchData(endpoint) {<br>  const response = await fetch(endpoint);<br>  const data = await response.json();<br>  return data;<br>}<br>export { fetchData };</pre><ol><li>Next, create a custom hook to fetch data using Suspense:</li></ol><pre>// useFetchData.js<br>import { useState, useEffect } from &#39;react&#39;;<br>import { fetchData } from &#39;./api&#39;;<br><br>function useFetchData(endpoint) {<br>  const [data, setData] = useState(null);<br>  useEffect(() =&gt; {<br>    const fetchAndSetData = async () =&gt; {<br>      const result = await fetchData(endpoint);<br>      setData(result);<br>    };<br>    fetchAndSetData();<br>  }, [endpoint]);<br>  return data;<br>}<br>export default useFetchData;</pre><ol><li>Finally, use the custom hook and Suspense in your component:</li></ol><pre>// App.js<br>import { Suspense } from &#39;react&#39;;<br>import useFetchData from &#39;./useFetchData&#39;;<br><br>function DataDisplay() {<br>  const data = useFetchData(&#39;https://api.example.com/data&#39;);<br>  return &lt;div&gt;{data ? data.value : &#39;Loading...&#39;}&lt;/div&gt;;<br>}<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;React Suspense Demo&lt;/h1&gt;<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;DataDisplay /&gt;<br>      &lt;/Suspense&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>In this example, the DataDisplay component uses the useFetchData hook to fetch data from an API endpoint. The Suspense component wraps the DataDisplay component, providing a fallback UI to display while the data is being fetched.</p><p>Error boundaries can also be integrated with Suspense to handle errors during data fetching and rendering. To do this, create an error boundary component and wrap it around your Suspense-wrapped components:</p><pre>// ErrorBoundary.js<br>import { Component } from &#39;react&#39;;<br><br>class ErrorBoundary extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { hasError: false };<br>  }<br><br>  static getDerivedStateFromError() {<br>      return { hasError: true };<br>    }<br>    componentDidCatch(error, info) {<br>      console.error(&#39;Error caught:&#39;, error, info);<br>    }<br>    render() {<br>      if (this.state.hasError) {<br>        return &lt;div&gt;Something went wrong.&lt;/div&gt;;<br>      }<br>      return this.props.children;<br>    }<br>}<br>export default ErrorBoundary;<br><br>// App.js<br>import ErrorBoundary from &#39;./ErrorBoundary&#39;;<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;React Suspense and Error Boundary Demo&lt;/h1&gt;<br>      &lt;ErrorBoundary&gt;<br>        &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>          &lt;DataDisplay /&gt;<br>        &lt;/Suspense&gt;<br>      &lt;/ErrorBoundary&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default App;</pre><p>In this setup, the ErrorBoundary component wraps the Suspense component. If an error occurs during data fetching or rendering, the ErrorBoundary component will catch the error and display a fallback UI, preventing the entire application from crashing.</p><p>By combining Suspense and error boundaries, you can create more robust and resilient applications that gracefully handle data fetching, loading states, and errors.</p><p>In addition to the improvements mentioned above, React 18 also includes better integration between Suspense and Concurrent Mode. This allows Suspense to take full advantage of the performance benefits provided by Concurrent Mode, such as smoother transitions and improved responsiveness.</p><p>In summary, React 18 brings a variety of improvements to the Suspense feature, making it even more powerful and easier to work with. By using Suspense in combination with error boundaries and Concurrent Mode, you can create applications that handle data fetching, loading states, and errors gracefully, providing a better user experience.</p><h3>Updated React DevTools for Enhanced Debugging</h3><p>React DevTools is a powerful browser extension that provides a suite of debugging tools to help you inspect and understand your React application’s component hierarchy, state, and props. With React 18, DevTools receives several updates that make it even more useful for debugging and profiling your applications.</p><p>Here are some of the key updates to React DevTools in React 18:</p><ol><li>Improved component filtering: React DevTools now allows you to filter components by name, state, and props more easily. This makes it simpler to find and focus on specific components within large and complex applications.</li><li>Concurrent Mode support: With the introduction of Concurrent Mode in React 18, DevTools now includes the ability to visualize and debug components rendered using Concurrent Mode. This helps you understand how your components are being prioritized and updated in real-time.</li><li>Server Components support: React DevTools has been updated to support React Server Components, allowing you to inspect server-rendered components and their props, state, and context. This makes it easier to debug and understand the behavior of your Server Components.</li><li>Enhanced performance profiling: The performance profiler in React DevTools has been improved to provide more accurate and detailed information about component render times, state updates, and other performance metrics. This can help you identify performance bottlenecks and optimize your application.</li><li>Improved error handling: React DevTools now provides more helpful error messages and stack traces when an error occurs in your application. This makes it easier to identify and fix issues as they arise.</li></ol><p>To get started with the updated React DevTools, you’ll need to install or update the browser extension for your preferred browser:</p><ul><li>For Google Chrome: <a href="https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi">React Developer Tools</a></li><li>For Mozilla Firefox: <a href="https://addons.mozilla.org/en-US/firefox/addon/react-devtools/">React Developer Tools</a></li><li>For Microsoft Edge: <a href="https://microsoftedge.microsoft.com/addons/detail/react-developer-tools/gpphkfbcpidddadnkolkpfckpihlkkil">React Developer Tools</a></li></ul><p>After installing or updating the extension, open your React application in the browser and open the browser’s developer tools. You should see a new “React” tab, which gives you access to the React DevTools features.</p><p>In conclusion, the updates to React DevTools in React 18 provide even more powerful and useful tools for debugging and profiling your applications. By taking advantage of these enhancements, you can gain deeper insights into your application’s behavior, performance, and component hierarchy, making it easier to identify and fix issues and optimize your application.</p><h3>Migration Strategies for Upgrading to React 18</h3><p>Upgrading to a new major version of a library or framework can be challenging, but the React team has put significant effort into ensuring a smooth and gradual migration path. We’ll cover the recommended steps and best practices for upgrading your application to React 18 while minimizing disruptions to your development process and users.</p><p>Here’s a high-level overview of the recommended migration process for upgrading to React 18:</p><ol><li>Update your dependencies: Before upgrading to React 18, ensure that your application’s dependencies are compatible with React 18 or have been updated to support the new version. Check the documentation and release notes of your dependencies for compatibility information and follow any necessary upgrade steps.</li><li>Install React 18: Update your react and react-dom packages to version 18:</li></ol><pre>npm install react@18 react-dom@18</pre><ol><li>Opt-in to Concurrent Mode (optional): React 18 introduces Concurrent Mode, a new rendering strategy that can significantly improve the performance and responsiveness of your application. While opting into Concurrent Mode is not required, it’s recommended to take advantage of its benefits. To enable Concurrent Mode, update the ReactDOM.render call in your application&#39;s entry point:</li></ol><pre>// Before<br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));<br><br>// After<br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(&lt;App /&gt;);</pre><ol><li>Test your application: After updating to React 18 and enabling Concurrent Mode, thoroughly test your application to ensure that it continues to work correctly. Pay special attention to areas where new features and changes in React 18 may have an impact, such as error boundaries, Suspense, and component lifecycle methods.</li><li>Address any warnings and deprecations: React 18 may introduce new warnings and deprecations for features or patterns that are no longer recommended. Carefully review any warnings or deprecations in your application and follow the recommended migration steps to address them.</li><li>Adopt new features incrementally: Once your application is running smoothly on React 18, you can start adopting new features and improvements incrementally. For example, you might begin using React Server Components, the improved Suspense features, or the automatic batching of state updates. Introduce these changes one at a time and thoroughly test your application to ensure a smooth transition.</li><li>Monitor and optimize performance: As you adopt new features in React 18, monitor your application’s performance to ensure that it remains optimal. Use tools like React DevTools, browser developer tools, and third-party monitoring solutions to identify any performance bottlenecks or regressions and make any necessary optimizations.</li></ol><p>In summary, upgrading to React 18 is a manageable process that can be carried out in a gradual and controlled manner. By following the recommended migration steps and best practices, you can ensure a smooth transition to React 18 while minimizing disruptions to your development process and users.</p><p>With your application now running on React 18, you can take full advantage of the new features and improvements it offers. As we’ve explored throughout this series, React 18 brings many exciting enhancements, such as React Server Components, improved Suspense features, automatic batching, and more. I hope that you find these new features valuable in building more performant, responsive, and enjoyable applications for your users.</p><h3>Best Practices for Building React 18 Applications</h3><p>By following these recommendations, you can create more maintainable, performant, and scalable applications that are easier to debug and provide a better user experience.</p><ol><li>Leverage React Server Components: React Server Components allow you to build parts of your application that run on the server, reducing the amount of JavaScript that needs to be sent to the client. This can result in faster load times and improved performance. Consider using Server Components for parts of your application that do not require interactivity or immediate updates.</li><li>Embrace Concurrent Mode: Concurrent Mode is a powerful new rendering strategy introduced in React 18 that can significantly improve the performance and responsiveness of your application. By opting into Concurrent Mode, you can take advantage of features like automatic batching, improved Suspense, and smoother transitions.</li><li>Use React.lazy and Suspense for code splitting: Code splitting is an important technique for reducing the initial load time of your application by loading only the necessary parts of the application when needed. Use React.lazy in combination with Suspense to split your application into smaller chunks that can be loaded on-demand.</li><li>Handle errors gracefully with error boundaries: Error boundaries allow you to catch and handle errors in your application more effectively, preventing the entire application from crashing. Use error boundaries in combination with Suspense to handle errors during data fetching, rendering, and other operations.</li><li>Optimize performance with React DevTools: React DevTools is an essential tool for debugging and profiling your React applications. Use the updated DevTools in React 18 to gain deeper insights into your application’s behavior, performance, and component hierarchy. This can help you identify and fix issues, optimize performance, and improve the overall quality of your application.</li><li>Use functional components and hooks: Functional components and hooks have become the recommended way to build components in React. They provide a simpler and more concise syntax, better performance, and improved support for features like Concurrent Mode. When building new components or refactoring existing ones, consider using functional components and hooks.</li><li>Keep your component hierarchy shallow and modular: A shallow and modular component hierarchy makes it easier to understand, maintain, and optimize your application. Break down complex components into smaller, reusable parts, and avoid deep nesting of components whenever possible.</li><li>Write tests for your components: Writing tests for your components helps ensure that they work correctly and continue to do so as your application evolves. Use testing libraries like React Testing Library or Enzyme to write unit and integration tests for your components.</li><li>Stay up-to-date with React releases and best practices: The React ecosystem is constantly evolving, with new features, improvements, and best practices being introduced regularly. Stay informed about new releases and best practices by following the React team’s blog, attending conferences, and participating in the React community.</li></ol><p>By following these best practices, you can create more maintainable, performant, and scalable applications using React 18. As you continue to explore the new features and improvements in React 18, you’ll find even more ways to build better applications that provide a great user experience.</p><h3>React 18 and the Future of Web Development</h3><p>As a major release, React 18 brings numerous new features and improvements that have the potential to shape the way we build web applications moving forward.</p><ol><li>The rise of server-side rendering and hybrid applications: With the introduction of React Server Components, React 18 has brought server-side rendering back into the spotlight. As developers embrace the benefits of reduced JavaScript payloads and faster load times, we can expect to see more hybrid applications that leverage both server-rendered and client-rendered components for an optimal balance of performance and interactivity.</li><li>Enhanced performance with Concurrent Mode: Concurrent Mode is a game-changing feature that enables React to work on multiple tasks simultaneously, leading to smoother transitions and improved responsiveness. As more developers adopt Concurrent Mode, we can expect web applications to become more performant and provide better user experiences.</li><li>Focus on user experience and accessibility: React 18’s improved Suspense and error handling capabilities make it easier to build applications that gracefully handle data fetching, loading states, and errors. This focus on user experience and accessibility will continue to be a priority for the React team and the broader web development community.</li><li>Greater emphasis on web performance optimization: React 18’s enhancements, such as automatic batching and the updated DevTools, provide developers with more tools to optimize their applications’ performance. As web applications become increasingly complex, performance optimization will continue to be a critical aspect of web development.</li><li>Growing adoption of React in new platforms and environments: React has already expanded beyond the web with projects like React Native and React VR. With React 18’s improvements and innovations, we can expect React to be adopted in even more platforms and environments, enabling developers to build consistent and performant user interfaces across a wide range of devices and technologies.</li><li>Continued growth of the React ecosystem: As React continues to evolve, we can expect the React ecosystem to grow alongside it. This includes the development of new tools, libraries, and best practices that help developers build better applications more efficiently. By staying up-to-date with the latest trends and innovations in the React ecosystem, you’ll be well-equipped to navigate the ever-changing landscape of web development.</li></ol><p>In conclusion, React 18 marks an exciting new chapter in the world of web development. Its many new features and improvements have the potential to shape the way we build web applications for years to come. As you continue to explore React 18 and build your applications using the latest best practices, you’ll be well-prepared for the future of web development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82825f209ae7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Top 10 Front-End Mistakes to Avoid]]></title>
            <link>https://medium.com/@vyakymenko/the-top-10-front-end-mistakes-to-avoid-ec94d859d99?source=rss-480104d31c3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec94d859d99</guid>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Valentyn Yakymenko]]></dc:creator>
            <pubDate>Wed, 15 Mar 2023 18:49:29 GMT</pubDate>
            <atom:updated>2023-03-15T18:49:29.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rOb6Dphn-E4p7CbkjO3oA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@matscha?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniela Holzer</a> on <a href="https://unsplash.com/photos/u_3rD02dmkw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Failing to Optimize Images</h4><p>One of the most common mistakes made by front-end developers is failing to optimize images before uploading them to a website. Large, unoptimized images can significantly slow down your website, which can lead to a poor user experience and hurt your search engine ranking.</p><p>To optimize images, you should:</p><ol><li>Use the appropriate file format: JPEG is the best format for photographs, while PNG is best for images with text or graphics.</li><li>Compress images: Use a tool like TinyPNG or Kraken.io to reduce the file size of your images without sacrificing quality.</li><li>Resize images: Make sure your images are the correct size for the location they will be displayed on your website. Resizing an image in HTML or CSS is not the same as actually resizing the image file, and can still result in large file sizes.</li></ol><p>By taking the time to properly optimize your images, you can ensure that your website loads quickly and provides a better experience for your users.</p><h4>Not Using a Responsive Design</h4><p>With the increasing number of people accessing the internet on their phones and tablets, it’s important to make sure your website looks good on all devices. Failing to use a responsive design, which adjusts the layout of your website to fit different screen sizes, can result in a poor user experience and lost traffic.</p><p>To create a responsive design, you should:</p><ol><li>Use responsive design frameworks: Tools like Tailwind can help you create a responsive website quickly and easily.</li><li>Use relative units: Instead of specifying the size of elements in pixels, use relative units like percentages or “em” units, which are based on the size of the user’s screen.</li><li>Test your website on different devices: Make sure to test your website on a variety of devices, including phones, tablets, and desktop computers, to ensure it looks and functions correctly.</li></ol><p>By following these tips, you can create a website that looks great and is easy to use on any device.</p><h4>Ignoring Accessibility</h4><p>Your website should be accessible to users with disabilities, as well as users with older or non-standard devices. Failing to consider accessibility can exclude a significant portion of your audience and can also lead to legal issues.</p><p>To make your website more accessible, you should:</p><ol><li>Use semantic HTML tags: Properly using HTML tags such as “header,” “nav,” and “footer” can help screen readers understand the structure of your website.</li><li>Add alt text to images: Alt text describes the content of an image for users who are unable to see it. This is important for users with visual impairments who use screen readers.</li><li>Use proper color contrast: Make sure the colors you use on your website have sufficient contrast, so that users with visual impairments can read your content easily.</li><li>Use headings and lists: Properly using headings and lists can make your content easier to understand and navigate for users with disabilities.</li></ol><p>By following these guidelines, you can make your website more accessible and inclusive for all users.</p><h4>Using Outdated Technologies</h4><p>To create a modern, functional website, it’s important to keep up with the latest front-end technologies. Using outdated technologies can result in a website that looks and functions poorly, and can also make it more difficult to maintain and update.</p><p>Some technologies to consider using in your front-end development include:</p><ol><li>HTML5: HTML5 is the latest version of HTML, the markup language used to structure and format content on the web. It introduces new elements and attributes that make it easier to create rich, interactive content.</li><li>CSS3: CSS3 is the latest version of CSS, the stylesheet language used to control the look and layout of a website. It introduces new selectors, properties, and modules that make it easier to create responsive, modern designs.</li><li>JavaScript: JavaScript is a programming language used to add interactivity and functionality to websites. It’s essential for creating dynamic, user-friendly websites, and there are many libraries and frameworks available to make it easier to use.</li></ol><p>By staying up-to-date with these technologies, you can create a website that looks and functions well and is easier to maintain.</p><h4>NOT Properly Structuring Your HTML</h4><p>Properly structured HTML is important for search engine optimization and accessibility. Failing to use semantic tags and follow best practices for HTML structure can result in a website that is difficult to understand and navigate.</p><p>To properly structure your HTML, you should:</p><ol><li>Use semantic tags: Instead of using generic tags like “div” and “span,” use tags that describe the content they contain, such as “header,” “nav,” and “footer.”</li><li>Use headings correctly: Use the “h1” through “h6” tags to mark headings and subheadings, and make sure to use them in a logical hierarchy.</li><li>Use lists correctly: Use the “ul” and “ol” tags to mark unordered and ordered lists, respectively.</li><li>Use the “alt” attribute for images: The “alt” attribute describes the content of an image for users who are unable to see it, and is important for accessibility and search engine optimization.</li></ol><p>By following these guidelines, you can create an HTML structure that is easy to understand and navigate, and that helps improve your website’s search engine ranking and accessibility.</p><h4>NOT Testing Across Browsers and Devices</h4><p>It’s important to test your website on different browsers and devices to ensure it looks and functions correctly. Failing to do so can result in a website that looks and functions poorly for some users.</p><p>To test your website across browsers and devices, you should:</p><ol><li>Test on different browsers: Different browsers, such as Chrome, Firefox, and Safari, can render websites differently. Make sure to test your website on a variety of browsers to ensure it looks and functions correctly.</li><li>Test on different devices: With the increasing number of people accessing the internet on their phones and tablets, it’s important to make sure your website looks and functions well on these devices.</li><li>Use browser and device testing tools: Tools like BrowserStack and Responsive Design Checker can help you test your website on a variety of browsers and devices.</li></ol><p>By thoroughly testing your website, you can ensure that it provides a good user experience for all users.</p><h4>NOT Paying Attention to Performance</h4><p>A slow-loading website can turn off users, so it’s important to optimize your website for performance. Failing to do so can result in a poor user experience and lost traffic.</p><p>To improve the performance of your website, you should:</p><ol><li>Optimize images: As mentioned in chapter 1, make sure to use the appropriate file format and compress images to reduce their file size.</li><li>Minify and concatenate CSS and JavaScript: Use tools like CSSNano and UglifyJS to remove unnecessary characters and combine multiple files into one, which can reduce the amount of time it takes for your website to load.</li><li>Use a content delivery network (CDN): A CDN stores copies of your website’s static assets (such as images and stylesheets) on servers located around the world, which can help reduce the load time for users who are far from your server.</li><li>Use caching: Caching can help reduce the amount of time it takes for your website to load by storing frequently accessed assets in the user’s browser or on a server.</li></ol><p>By following these tips, you can create a website that loads quickly and provides a better experience for your users.</p><h4>NOT Keeping Your Code Organized</h4><p>Properly organizing your code makes it easier to read, maintain, and update. Failing to do so can result in a website that is difficult to work with and prone to errors.</p><p>To keep your code organized, you should:</p><ol><li>Use descriptive, meaningful names for variables and functions: Using names that clearly describe the purpose of a variable or function can make your code easier to understand.</li><li>Use comments: Comments are lines of text in your code that are ignored by the browser, but can help explain what your code is doing. Use comments to describe the purpose of a section of code or to explain any complex or confusing parts.</li><li>Use indentation: Properly indenting your code can help make it easier to read and understand.</li><li>Use whitespace: Adding whitespace between lines of code and around blocks of code can help make your code more readable.</li></ol><p>By following these guidelines, you can create code that is easy to read and understand, and that is easier to maintain and update.</p><h4>NOT Using a Version Control System</h4><p>A version control system, such as Git, can help you track changes to your code and revert back to previous versions if necessary. Failing to use a version control system can make it difficult to keep track of changes to your code and can lead to lost work.</p><p>To use a version control system, you should:</p><ol><li>Learn how to use the system: Version control system has its own set of commands and workflow. Make sure to familiarize yourself with the system you choose and follow best practices for using it.</li><li>Use branches: Branches allow you to work on different versions of your code at the same time, which can be useful for working on new features or fixing bugs.</li><li>Use commits: Commits are like snapshots of your code at a specific point in time. Make sure to commit your code regularly, and use clear, descriptive commit messages to explain the changes you made.</li></ol><p>By using a version control system, you can keep track of changes to your code and easily revert back to previous versions if necessary.</p><h4>NOT Seeking Feedback</h4><p>Getting feedback from users, stakeholders, and other developers can help identify any issues with your website and improve its usability and functionality. Failing to seek feedback can result in a website that doesn’t meet the needs of its users.</p><p>To seek feedback, you should:</p><ol><li>Use feedback tools: Tools like UserTesting and Crazy Egg can help you gather feedback from users on your website.</li><li>Ask for feedback from stakeholders: Reach out to stakeholders, such as business owners or project managers, to get their feedback on your website.</li><li>Ask for feedback from other developers: Other developers can provide valuable insights on how to improve your website’s code and functionality.</li><li>Use analytics: Tools like Google Analytics can help you understand how users are interacting with your website, and can identify any areas that may need improvement.</li></ol><p>By seeking feedback and using analytics, you can improve your website and create a better experience for your users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec94d859d99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>