<?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 Ruver Dornelas on Medium]]></title>
        <description><![CDATA[Stories by Ruver Dornelas on Medium]]></description>
        <link>https://medium.com/@ruverd?source=rss-8a121fa12126------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*qcfGsp2DnTQjQgpa.jpg</url>
            <title>Stories by Ruver Dornelas on Medium</title>
            <link>https://medium.com/@ruverd?source=rss-8a121fa12126------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 09:54:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ruverd/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[Jest vs Vitest: Which Test Runner Should You Use in 2025?]]></title>
            <link>https://medium.com/@ruverd/jest-vs-vitest-which-test-runner-should-you-use-in-2025-5c85e4f2bda9?source=rss-8a121fa12126------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c85e4f2bda9</guid>
            <dc:creator><![CDATA[Ruver Dornelas]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 06:42:29 GMT</pubDate>
            <atom:updated>2025-11-16T06:42:29.833Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing is a fundamental part of building reliable JavaScript and TypeScript applications. As projects grow, having a fast, predictable, and maintainable test setup becomes essential especially when working with modern frameworks like React, Next.js, Vite, SolidJS, and Node-based backend services.</p><p>For years, <strong>Jest</strong> has been the de facto standard for unit testing in the JavaScript ecosystem. But with the rise of faster build tools like <strong>Vite</strong>, a new alternative has emerged: <strong>Vitest</strong>. Combining native ES modules, blazing-fast performance, and tight integration with modern tooling, Vitest has quickly become a serious contender and for many teams, a better choice.</p><p>In this article, we’ll break down the differences between Jest and Vitest, when to choose each, their advantages and limitations, and which one is the right fit for your project.</p><h3>Topics</h3><p>This article explains the core differences between <strong>Jest</strong> and <strong>Vitest</strong>, why Vitest has gained popularity in modern frontend stacks, when Jest is still the better option, how each tool performs in real-world scenarios, and the advantages and trade-offs of adopting either testing framework.</p><h3>What Is Jest?</h3><p><strong>Jest</strong> is a popular JavaScript testing framework created by Facebook (Meta). It includes:</p><ul><li>Test runner</li><li>Assertion library</li><li>Mocking utilities</li><li>Snapshot testing</li><li>Code coverage tools</li></ul><p>It is widely used in React applications, Node.js backends, and legacy JavaScript codebases.</p><p>A typical Jest test looks like this:</p><pre>test(&quot;adds numbers&quot;, () =&gt; {<br>  expect(1 + 2).toBe(3);<br>});</pre><p>Jest uses a custom module system (via Babel or ts-jest) and often requires additional configuration for TypeScript, ESM, or modern bundlers.</p><h3>What Is Vitest?</h3><p><strong>Vitest</strong> is a modern test runner built on top of <strong>Vite</strong>, offering instant startup, native ESM, TypeScript support out of the box, and extremely fast HMR-driven test execution.</p><p>Vitest includes:</p><ul><li>Test runner</li><li>Assertions (powered by Chai + built-in matchers)</li><li>Mocking (Jest-compatible API)</li><li>Snapshot testing</li><li>Coverage (via V8 or Istanbul)</li></ul><p>A simple Vitest test:</p><pre>import { describe, it, expect } from &quot;vitest&quot;;<br><br>describe(&quot;math&quot;, () =&gt; {<br>  it(&quot;adds numbers&quot;, () =&gt; {<br>    expect(1 + 2).toBe(3);<br>  });<br>});</pre><p>Vitest is designed to be Jest-compatible, so migrating from Jest is often straightforward.</p><h3>Key Differences: Jest vs. Vitest</h3><h3>1. Performance &amp; Speed</h3><p><strong>Vitest: Lightning fast</strong></p><p>Vitest leverages Vite’s dev server, ESBuild, and HMR:</p><ul><li>Instant test startup</li><li>Near-real-time test runs</li><li>Perfect for large TypeScript + frontend projects</li></ul><p><strong>Jest: Slower, especially on cold starts</strong></p><p>Jest uses JSDOM by default and processes modules through Babel or ts-jest, which increases overhead.</p><p>If performance matters (CI pipelines, large apps, rapid feedback loops), <strong>Vitest wins clearly</strong>.</p><h3>2. Ecosystem &amp; Integration</h3><p><strong>Vitest shines in:</strong></p><ul><li><strong>Vite-based projects</strong> (React, Vue, Svelte, SolidJS)</li><li><strong>Next-gen frameworks</strong> (SolidStart, SvelteKit, Astro)</li><li><strong>TypeScript-first codebases</strong></li></ul><p>Vitest integrates seamlessly with Vite’s config, aliases, plugins, and ESM pipeline.</p><p><strong>Jest shines in:</strong></p><ul><li><strong>Legacy apps</strong> using Webpack, Babel, or CommonJS</li><li><strong>React Native</strong> (Vitest does not support RN yet)</li><li><strong>Existing enterprise systems</strong> built around Jest tooling</li></ul><p>If you’re using Vite, <strong>Vitest is almost always the better choice</strong>.</p><h3>3. TypeScript Support</h3><p><strong>Vitest: First-class TS support</strong></p><p>No Babel. No ts-jest. No heavy configuration.</p><p>Vite handles TS + JSX natively with ESBuild.</p><p><strong>Jest: Needs extra setup</strong></p><p>To run TypeScript smoothly, you need:</p><ul><li>Babel</li><li>ts-jest</li><li>custom configs</li></ul><p>Vitest is significantly simpler for TypeScript-heavy apps.</p><h3>4. Mocking &amp; API compatibility</h3><p><strong>Vitest supports Jest’s mocking API</strong></p><p>You can use:</p><pre>vi.fn();<br>vi.spyOn();<br>vi.mock();</pre><p>This makes migration extremely easy.</p><p><strong>Jest has more mature mocking behavior</strong></p><ul><li>Edge cases</li><li>Jest-environment-specific mocks</li><li>JSDOM interactions</li></ul><p>Vitest is 95% compatible, but some Jest-specific mocks may require adjustments.</p><h3>5. Snapshot Testing</h3><p>Both support snapshot testing, but:</p><ul><li>Vitest snapshot diffs feel more modern</li><li>Jest has broader editor ecosystem support</li></ul><p>For most frontend teams, they’re functionally equivalent.</p><h3>6. Test Environment</h3><p><strong>Vitest</strong></p><ul><li>Node</li><li>JSDOM</li><li>Custom environments</li></ul><p><strong>Jest</strong></p><ul><li>Node</li><li>JSDOM</li><li>React Native (Vitest does <em>not</em> support this)</li></ul><p>If you’re building React Native apps: <strong>Jest is mandatory</strong>.</p><h3>7. Debugging</h3><p>Vitest wins again:</p><ul><li>Built-in watch mode UI</li><li>Instant reload</li><li>Better stack traces</li><li>Native ESM debugging</li></ul><p>Jest debugging works, but it’s noticeably slower, especially with TypeScript.</p><h3>Advantages of Vitest</h3><p><strong>1. Blazing-fast performance</strong></p><p>Perfect for modern SPAs, dashboards, and component-heavy apps.</p><p><strong>2. Built on Vite</strong></p><p>If your project uses Vite, the integration is unmatched.</p><p><strong>3. TS + ESM support without headaches</strong></p><p>Writes less config, spends less time fighting tooling.</p><p><strong>4. Better developer experience</strong></p><p>Live-reloading tests feel like developing with HMR.</p><p><strong>5. Jest-compatible API</strong></p><p>Easy migration.</p><p><strong>6. Faster CI pipelines</strong></p><p>Often reduces test runtime by 30–70%.</p><h3>Advantages of Jest</h3><p><strong>1. Massive ecosystem</strong></p><p>Almost every tool, plugin, or library already supports Jest.</p><p><strong>2. React Native support</strong></p><p>Vitest can’t replace Jest for RN.</p><p><strong>3. Battle-tested</strong></p><p>Used across big tech companies and mature codebases.</p><p><strong>4. Rich plugin ecosystem (e.g., Jest Circus, testing-library integrations)</strong></p><p>Though many tools now support Vitest as well.</p><h3>Cons of Vitest</h3><ul><li>No React Native support</li><li>Some Jest plugins may not work</li><li>A few Jest mock edge cases behave differently</li><li>Not ideal for purely Node.js CJS-heavy backend systems</li></ul><h3>Cons of Jest</h3><ul><li>Slower due to Babel, ts-jest, and JSDOM overhead</li><li>More configuration required</li><li>Poor ESM support compared to Vitest</li><li>Doesn’t integrate with Vite</li><li>Heavier memory usage</li></ul><h3>When to Use Vitest</h3><p>Use Vitest if:</p><ul><li>You use <strong>Vite</strong></li><li>You use <strong>TypeScript</strong></li><li>You build modern SPAs (React, Vue, Svelte, Solid)</li><li>You want faster CI</li><li>You want instant feedback while coding</li><li>You’re starting a new project in 2025</li></ul><p>Vitest is the new default for most frontend apps.</p><h3>When to Use Jest</h3><p>Use Jest if:</p><ul><li>You’re building <strong>React Native</strong></li><li>Your project uses <strong>Webpack/Babel</strong></li><li>Your app heavily depends on <strong>CommonJS</strong></li><li>Your company already has a large Jest ecosystem</li><li>You rely on Jest-only plugins or test environments</li></ul><h3>Which One Should You Choose? (Short Answer)</h3><ul><li>New modern frontend project? → Vitest</li><li>Vite project? → Vitest, no discussion</li><li>React Native? → Jest</li><li>Legacy Webpack/Babel project? → Jest</li><li>Node.js backend with ESM/TS? → Vitest</li><li>Large enterprise with existing Jest infra? → Jest, unless migrating</li></ul><h3>Conclusion</h3><p>Vitest has quickly become the ideal choice for modern TypeScript and frontend development. It’s faster, simpler, and deeply integrated with Vite’s ecosystem. For teams using React with Vite, SolidJS, Vue, or Svelte, Vitest delivers an outstanding developer experience and significantly faster feedback loops.</p><p>Jest, on the other hand, remains a reliable and powerful solution especially in legacy systems or React Native apps. Its ecosystem maturity and long history make it a safe choice for many large or older codebases.</p><p>Ultimately:</p><ul><li>Vitest = speed, modern DX, Vite-native projects</li><li>Jest = compatibility, legacy support, React Native</li></ul><p>As the ecosystem continues evolving toward ESM and next-gen tooling, Vitest is clearly leading the future. But both frameworks have their place and the right choice depends on your project’s constraints and goals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c85e4f2bda9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why You Should Use nuqs: Smarter URL State Management for React & Next.js]]></title>
            <link>https://medium.com/@ruverd/why-you-should-use-nuqs-smarter-url-state-management-for-react-next-js-26a8b51ca1ac?source=rss-8a121fa12126------2</link>
            <guid isPermaLink="false">https://medium.com/p/26a8b51ca1ac</guid>
            <dc:creator><![CDATA[Ruver Dornelas]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 06:21:33 GMT</pubDate>
            <atom:updated>2025-11-16T06:21:33.412Z</atom:updated>
            <content:encoded><![CDATA[<p>Managing state in the URL is one of the trickiest parts of building modern web apps. Query params often end up inconsistent, manually encoded, duplicated across components, or tightly coupled to your router. And as your app grows, this problem multiplies — filters, pagination, search, sorting, tab state, UI preferences, etc.</p><p>This is where <strong>nuqs</strong> comes in.</p><p>nuqs is a lightweight library that provides <strong>typed, reactive, and declarative URL query state</strong> for React and Next.js applications. Instead of manually parsing, stringifying, encoding, syncing, and updating query parameters, nuqs allows you to bind state directly to the URL with minimal boilerplate.</p><p>In this article, we’ll explore what nuqs is, why you might want to use it, when it makes sense, and the biggest advantages and trade-offs.</p><h3>What is nuqs?</h3><p>nuqs (short for <em>Next.js URL Query State</em>) is a small library that makes URL search parameters behave like React state.</p><p>It provides hooks such as:</p><pre>const [page, setPage] = useQueryState(&quot;page&quot;, parseNumber());</pre><p>Now:</p><ul><li>page always reflects the value in the URL</li><li>setPage updates both the React state <strong>and the URL</strong></li><li>the value is automatically parsed/validated/typed</li><li>the URL stays clean, consistent, and controlled</li></ul><p>Behind the scenes, nuqs handles:</p><ul><li>parsing</li><li>encoding</li><li>serialization</li><li>debouncing</li><li>shallow routing</li><li>SSR-safe hydration</li></ul><p>All while keeping a <strong>simple developer experience</strong>.</p><h3>Why Use nuqs?</h3><h3>1. Declarative URL State Without Boilerplate</h3><p>Traditionally, you need to manually work with useRouter, router.push, router.replace, URLSearchParams, and type conversions:</p><pre>const router = useRouter();<br>const page = Number(router.query.page ?? 1);<br><br>const changePage = (newPage: number) =&gt; {<br>  const params = new URLSearchParams(router.query);<br>  params.set(&quot;page&quot;, newPage.toString());<br>  router.replace(`?${params.toString()}`, undefined, { shallow: true });<br>};</pre><p>With nuqs:</p><pre>const [page, setPage] = useQueryState(&quot;page&quot;, parseNumber().withDefault(1));</pre><p>That’s it.</p><h3>2. Built-in Parsers and Type Safety</h3><p>nuqs ships with common parsers:</p><ul><li>parseNumber</li><li>parseBoolean</li><li>parseString</li><li>parseArray</li><li>parseJson</li><li>parseTimestamp</li></ul><p>Each parser enforces runtime correctness while keeping TypeScript inference perfectly aligned.</p><p>No more “URL parameters are always strings so I must convert everything manually”.</p><h3>3. Perfect for Filters, Search, Pagination, Tabs</h3><p>Any state that you want to be:</p><ul><li>shareable</li><li>bookmarkable</li><li>persistent across reloads</li><li>RESTful</li><li>synced between components</li></ul><p>…can be stored in the URL with nuqs.</p><p>This eliminates complex global stores and avoids losing state when navigating or refreshing.</p><h3>4. Automatic Shallow Routing &amp; Debounced Updates</h3><p>nuqs automatically uses router.replace with shallow routing, preventing full page reloads.</p><p>And you can debounce updates:</p><pre>const [search, setSearch] = useQueryState(<br>  &quot;q&quot;,<br>  parseString().withDefault(&quot;&quot;).withOptions({ debounceMs: 300 })<br>);</pre><p>Great for search bars or filter-heavy pages.</p><h3>5. SSR-Friendly &amp; Next.js App Router Compatible</h3><p>Unlike other URL-state solutions, nuqs is built specifically for the <strong>Next.js App Router</strong>:</p><ul><li>works in server components</li><li>no hydration mismatches</li><li>safe for streaming</li><li>supports parallel routes</li></ul><p>It’s the “React Server Components–era” solution.</p><h3>6. Tiny and Dependency-Free</h3><p>nuqs is extremely small and has no external dependencies — ideal for performance-focused applications.</p><h3>When Should You Use nuqs?</h3><p>Use nuqs when:</p><ol><li><strong>Your UI state must appear in the URL</strong></li></ol><p>Filters, sorting, search queries, pagination, dashboard settings, selected tabs, etc.</p><p><strong>2. Your users should be able to share the page state</strong></p><p>“Send me the link to the filtered results.”</p><p><strong>3. You want SSR-friendly and typed query parameters</strong></p><p>Perfect for Next.js e-commerce, dashboards, SaaS, and admin panels.</p><p><strong>4. You want to reduce global state complexity</strong></p><p>URL becomes the single source of truth.</p><p><strong>5. You want to eliminate inconsistencies between client &amp; server</strong></p><p>nuqs ensures both sides interpret query params the same way.</p><h3>When NOT to Use nuqs</h3><p>Avoid nuqs if:</p><ol><li><strong>The state should be private (e.g., passwords, tokens)</strong></li></ol><p>URL params are visible and persistent.</p><p><strong>2. The state does not affect navigation or page identity</strong></p><p>Modal visibility, hover states, temporary UI transitions.</p><p><strong>3. You need extremely complex serialization</strong></p><p>nuqs supports JSON but is not meant for storing large nested objects.</p><p><strong>4. You don’t want the URL to change on every interaction</strong></p><p>e.g., dragging sliders or animations (unless debounced).</p><h3>Key Advantages</h3><ol><li><strong>Incredible Developer Experience</strong></li></ol><p>Two lines of code bind a value to the URL with type safety and parsing.</p><p><strong>2. Cleaner and More Predictable State</strong></p><p>The URL becomes the single source of truth, eliminating inconsistent local states.</p><p><strong>3. SSR, RSC, and App Router Native</strong></p><p>Unlike older libraries that try to support both old and new routing systems, nuqs is modern-first.</p><p><strong>4. Automatic Parsing and Serialization</strong></p><p>No need to worry about converting strings to numbers/booleans/arrays.</p><p><strong>5. URL Sharing and Bookmarking Work for Free</strong></p><p>State persists naturally.</p><p><strong>6. No Dependencies, Tiny Bundle</strong></p><p>Adds almost nothing to your bundle size.</p><h3>Cons and Limitations</h3><p><strong>1. Not suitable for high-frequency state changes</strong></p><p>Updating the URL repeatedly can cause performance issues.</p><p><strong>2. Only for URL-based state</strong></p><p>You still need Zustand/Jotai/Context for internal UI state.</p><p><strong>3. Requires the Next.js App Router</strong></p><p>It does not support older Next.js versions.</p><p><strong>4. Limited complexity for nested types</strong></p><p>JSON parser exists, but storing big objects in the URL is not ideal.</p><p><strong>Example: Filter + Search + Pagination in 10 Lines</strong></p><pre>const [page, setPage] = useQueryState(&quot;page&quot;, parseNumber().withDefault(1));<br>const [query, setQuery] = useQueryState(&quot;q&quot;, parseString().withDefault(&quot;&quot;));<br>const [tags, setTags] = useQueryState(&quot;tags&quot;, parseArray(parseString()));</pre><p>Changing state updates the URL automatically:</p><pre>setPage(2)           // /products?page=2&amp;q=&amp;tags=<br>setQuery(&quot;apple&quot;)    // /products?page=2&amp;q=apple&amp;tags=<br>setTags([&quot;green&quot;])   // /products?page=2&amp;q=apple&amp;tags=green</pre><p>And on refresh or share, everything restores correctly.</p><p><strong>Example: Using nuqs in a Server Component</strong></p><pre>import { searchParamsCache } from &quot;nuqs/server&quot;;<br><br>export default function Page() {<br>  const params = searchParamsCache();<br>  const tag = params.get(&quot;tag&quot;) ?? &quot;all&quot;;<br><br>  return &lt;Products selectedTag={tag} /&gt;;<br>}</pre><p>Perfect for hybrid server/client filtering.</p><h3>Common Pitfalls &amp; Best Practices</h3><p><strong>Use defaults to avoid </strong><strong>null values</strong></p><pre>arseNumber().withDefault(1)</pre><p><strong>Use debouncing for search inputs</strong></p><pre>withOptions({ debounceMs: 300 })</pre><p><strong>Don’t store sensitive data</strong></p><p>URLs persist everywhere (history, logs, analytics).</p><p><strong>Avoid storing large objects</strong></p><p>Stick to shallow, simple types.</p><p><strong>Don’t overuse it</strong></p><p>Not all UI state belongs in the URL.</p><h3>Conclusion</h3><p>nuqs is a powerful and elegant solution for URL state management in React and Next.js applications. Its strengths include:</p><ul><li>🌐 Declarative URL ↔ state synchronization</li><li>🔒 Runtime-safe and TypeScript-first parsers</li><li>⚡ No boilerplate, no dependencies</li><li>⭐ Perfect for filters, search, tabs, preferences, dashboards</li><li>🧩 First-class support for the Next.js App Router</li><li>🚀 Improves state consistency across client and server</li></ul><p>If your app relies on query parameters — think dashboards, SaaS products, filters, searches, e-commerce, data exploration tools — <strong>nuqs can clean up your codebase dramatically</strong>.</p><p>While it’s not meant for large or private state values, and shouldn’t replace your global state management solution, nuqs fills a very important niche: <strong>typed, reactive, URL-driven application state</strong>.</p><p>If you value clarity, maintainability, and a modern Next.js-friendly DX, nuqs is absolutely worth integrating into your stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26a8b51ca1ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Use ArkType Instead of Zod?]]></title>
            <link>https://medium.com/@ruverd/why-use-arktype-instead-of-zod-08c401fd4f6f?source=rss-8a121fa12126------2</link>
            <guid isPermaLink="false">https://medium.com/p/08c401fd4f6f</guid>
            <dc:creator><![CDATA[Ruver Dornelas]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 14:18:47 GMT</pubDate>
            <atom:updated>2025-03-31T14:18:47.590Z</atom:updated>
            <content:encoded><![CDATA[<p>When building robust TypeScript applications, runtime schema validation is essential. It allows developers to ensure data correctness not just at compile time, but also during execution — especially when dealing with external input (APIs, forms, etc). Two popular libraries in this space are <strong>Zod</strong> and <strong>ArkType</strong>. While both serve similar purposes, ArkType introduces a new, expressive way of defining types that might be a better fit for certain use cases.</p><p>In this article, we’ll explore the key differences between ArkType and Zod, and why you might choose <strong>ArkType</strong> as your go-to validation tool.</p><h3>What is ArkType?</h3><p><strong>ArkType</strong> is a TypeScript-first runtime validation library designed to offer <strong>concise, composable</strong>, and <strong>powerful</strong> type definitions with <strong>zero dependencies</strong>. Its syntax resembles TypeScript itself, which makes it intuitive for TypeScript developers.</p><pre>import { type } from &#39;arktype&#39;<br><br>const user = type({<br>  id: &#39;number&#39;,<br>  name: &#39;string&#39;,<br>  email: &#39;string?&#39;<br>})<br><br>user({ id: 1, name: &#39;Alice&#39; }) // valid<br>user({ id: &#39;wrong&#39;, name: &#39;Bob&#39; }) // throws</pre><h3>What is Zod?</h3><p><strong>Zod</strong> is a widely used schema declaration and validation library for TypeScript and JavaScript. It allows you to create schemas that validate data and automatically infer static types from those schemas.</p><pre>import { z } from &#39;zod&#39;<br><br>const user = z.object({<br>  id: z.number(),<br>  name: z.string(),<br>  email: z.string().optional()<br>})<br><br>user.parse({ id: 1, name: &#39;Alice&#39; }) // valid<br>user.parse({ id: &#39;wrong&#39;, name: &#39;Bob&#39; }) // throws</pre><h3>Why Choose ArkType Over Zod?</h3><h3>1. Concise and Readable Syntax</h3><p>ArkType shines when it comes to brevity. Instead of chaining method calls (z.string().optional()), ArkType allows a <strong>TypeScript-like literal syntax</strong>, which reduces visual noise and boosts readability:</p><pre>// ArkType<br>type({ age: &#39;number&gt;=18&#39; })<br><br>// Zod<br>z.object({ age: z.number().gte(18) })</pre><h3>2. Built-In Type Constraints</h3><p>ArkType supports powerful inline constraints, like:</p><pre>type({ username: &#39;string(minLength: 3, maxLength: 20)&#39; })</pre><p>This kind of inline constraint system is not as concise in Zod, which requires chained methods.</p><h3>3. Zero Dependencies and Lightweight</h3><p>ArkType is extremely lightweight and dependency-free, which is a win for performance-critical or bundle-size-sensitive applications.</p><h3>4. Type Inference Matches Type Definitions</h3><p>ArkType lets you <strong>write validations that look almost exactly like TypeScript types</strong>, and the inferred types reflect that directly — there’s no drift between the runtime and the static type world.</p><h3>5. No Chain Hell</h3><p>Instead of nested chains like:</p><pre>z.object({<br>  profile: z.object({<br>    age: z.number().min(18),<br>    bio: z.string().optional()<br>  })<br>})</pre><p>ArkType allows:</p><pre>type({<br>  profile: {<br>    age: &#39;number&gt;=18&#39;,<br>    bio: &#39;string?&#39;<br>  }<br>})</pre><h3>6. More Natural for Complex Types</h3><p>Union types, intersections, optional fields, array validation — ArkType handles them with elegance and familiarity:</p><pre>// An array of strings or numbers<br>type(&#39;string[] | number[]&#39;)<br><br>// Intersection of two objects<br>type(&#39;({ name: string } &amp; { age: number })&#39;) </pre><h3>7. Custom Error messages</h3><p>Both Zod and ArkType support custom error messages — but ArkType lets you go further with <strong>contextual error messages per rule</strong>, using labeled constraints:</p><pre>const product = type({<br>  price: {<br>    type: &#39;number&gt;0&#39;,<br>    error: &#39;Price must be greater than zero.&#39;<br>  },<br>  name: {<br>    type: &#39;string(minLength: 3)&#39;,<br>    error: &#39;Product name must be at least 3 characters.&#39;<br>  }<br>})</pre><p>Error messages become more meaningful and specific with less boilerplate.<br>Imagine you want to validate a user object where:</p><ul><li>If isActive is true, then email is required.</li><li>Otherwise, email can be optional.</li></ul><p>Here’s how you’d handle that with ArkType <strong>with a custom message:</strong></p><pre>const user = type({<br>  isActive: &#39;boolean&#39;,<br>  email: {<br>    type: &quot;string? &amp; (|&lt;$self.isActive=true&gt;)&quot;,<br>    error: &quot;Email is required when user is active&quot;<br>  }<br>})<br><br>user({ isActive: true }) // ❌ Error: &quot;Email is required when user is active&quot;<br>user({ isActive: false }) // ✅ Valid<br>user({ isActive: true, email: &quot;test@example.com&quot; }) // ✅ Valid</pre><h3>8. JSON Parsing</h3><pre>const parseJson = type(&quot;string.json.parse&quot;).to({<br>  name: &quot;string&quot;,<br>  version: &quot;string.semver&quot;<br>})<br><br>const result = parseJson(&#39;{ &quot;name&quot;: true, &quot;version&quot;: &quot;v2.0.0&quot; }&#39;)<br><br>if (result instanceof type.errors) {<br>  console.error(&quot;❌ Invalid input:&quot;)<br>  console.error(result.summary)<br>  // Optional: console.log(result.issues) for full breakdown<br>} else {<br>  console.log(&quot;✅ Valid data:&quot;, result)<br>}</pre><h4>What’s happening:</h4><p>&quot;string.json.parse&quot; is a <strong>built-in parser</strong> that:</p><ul><li>Confirms the input is a string.</li><li>Tries to JSON.parse it.</li></ul><p>.to({...}) pipes the parsed result into a validation schema.</p><ul><li>This is syntactic sugar for .pipe(...).</li></ul><h3>Quick Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*KiMoJOyekZd78ycFQ-Zl3w.png" /></figure><h3>🔥 1. Performance</h3><p>ArkType is <strong>faster than Zod</strong> in most real-world benchmarks. It achieves this by compiling its validation logic into efficient, reusable functions. This makes ArkType an excellent choice for performance-critical applications like:</p><ul><li>APIs with high throughput</li><li>Real-time data processing</li><li>Mobile or edge apps with limited resources</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*DLPbetgl_b22INBSi9y9JQ.png" /></figure><blockquote><strong><em>Example:</em></strong><em> Validating a large dataset (10k+ objects) can be </em><strong><em>2–4x faster</em></strong><em> with ArkType.</em></blockquote><h3>🚀 Bonus: Use ArkType with React Hook Form</h3><p>If you’re working in the frontend and using <strong>React Hook Form</strong>, you can easily use ArkType as your validation layer with first-class support via the @hookform/resolvers package.</p><pre>import { useForm } from &#39;react-hook-form&#39;<br>import { arktypeResolver } from &#39;@hookform/resolvers/arktype&#39;<br>import { type } from &#39;arktype&#39;<br><br>const schema = type({<br>  username: &#39;string&gt;1&#39;,<br>  password: &#39;string&gt;1&#39;,<br>})<br><br>type FormData = typeof schema.infer<br><br>export const App = () =&gt; {<br>  const {<br>    register,<br>    handleSubmit,<br>    formState: { errors },<br>  } = useForm&lt;FormData&gt;({<br>    resolver: arktypeResolver(schema),<br>  })<br><br>  return (<br>    &lt;form onSubmit={handleSubmit((data) =&gt; console.log(data))}&gt;<br>      &lt;div&gt;<br>        &lt;input placeholder=&quot;Username&quot; {...register(&#39;username&#39;)} /&gt;<br>        {errors.username &amp;&amp; &lt;p&gt;{errors.username.message}&lt;/p&gt;}<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;input<br>          type=&quot;password&quot;<br>          placeholder=&quot;Password&quot;<br>          {...register(&#39;password&#39;)}<br>        /&gt;<br>        {errors.password &amp;&amp; &lt;p&gt;{errors.password.message}&lt;/p&gt;}<br>      &lt;/div&gt;<br>      &lt;input type=&quot;submit&quot; /&gt;<br>    &lt;/form&gt;<br>  )<br>}</pre><h3>Conclusion</h3><p><strong>ArkType</strong> is a <strong>high-performance</strong>, <strong>lightweight</strong>, and <strong>expressive</strong> alternative to <strong>Zod</strong>. Its strengths lie in:</p><ul><li>📄 Clean, readable validation definitions</li><li>⚡ High performance for large or frequent validations</li><li>🧠 Complex conditional rules with minimal boilerplate</li><li>💬 Custom error messages that improve developer and user experience</li><li>🔗 Tight alignment between TypeScript types and runtime logic</li></ul><p>If you value developer experience, performance, and clean code, <strong>ArkType is absolutely worth trying</strong> — especially in new projects where you want type definitions and validation to live close together.</p><p>While Zod may still be the better option when built-in transformations or wider ecosystem support are required, <strong>ArkType is a serious contender</strong> — particularly for teams that prioritize speed, simplicity, and maintainability.</p><p>Whether you’re validating forms on the frontend, handling API payloads on the backend, or doing both — <strong>ArkType is a powerful tool worth adding to your toolbox</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08c401fd4f6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do You Really Understand useEffect in React?]]></title>
            <link>https://medium.com/@ruverd/do-you-really-understand-useeffect-in-react-5d0b0316d2c6?source=rss-8a121fa12126------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d0b0316d2c6</guid>
            <dc:creator><![CDATA[Ruver Dornelas]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 06:21:25 GMT</pubDate>
            <atom:updated>2023-09-17T06:21:25.078Z</atom:updated>
            <content:encoded><![CDATA[<p>React, one of the most popular JavaScript libraries for building user interfaces, has revolutionized the way developers create web applications. With its component-based architecture, React allows developers to create reusable and modular UI components. One crucial aspect of React’s functional components is the useEffect hook. But do you really understand how to harness its power?</p><h3>Understanding the Need for useEffect</h3><p>In the early days of React, class components were the primary way to manage component lifecycle and handle side effects. Developers relied on methods like componentDidMount, componentDidUpdate, and componentWillUnmount to interact with the DOM and manage asynchronous operations.</p><p>However, React introduced functional components, which simplified component structure and improved performance. But this shift also brought a challenge: how to manage side effects and lifecycle events in functional components.</p><p>That’s where useEffect comes into play.</p><h3>The Basics of useEffect</h3><p>useEffect is a hook that enables you to perform side effects in functional components. These side effects can include data fetching, DOM manipulation, setting up subscriptions, or any async operation.</p><p>The basic syntax of useEffect is straightforward:</p><pre>import { useEffect } from &#39;react&#39;;<br><br>function MyComponent() {<br>  useEffect(() =&gt; {<br>    // Your side effect code here<br>  }, [/* dependencies */]);<br><br>  return &lt;div&gt;Component content&lt;/div&gt;;<br>}</pre><h3>The Function Inside useEffect</h3><p>The function you provide inside useEffect will run after the component renders. This function can contain any code that performs side effects. For example, you might want to fetch data from an API or set the title of the webpage based on component data.</p><h3>Dependency Array</h3><p>The second argument of useEffect is an array of dependencies. It determines when the effect will run. If any of the values in the dependency array change between renders, the effect runs.</p><p>For instance, if you want an effect to run only when a specific state variable changes, you would include that variable in the dependency array. If the dependency array is empty, the effect runs after every render.</p><h3>Controlling Component Side Effects</h3><p>Understanding when and how useEffect runs is crucial for controlling side effects effectively.</p><h3>Cleanup Function</h3><p>useEffect can return a cleanup function, which is executed when the component unmounts or before the effect runs again due to changes in dependencies. This cleanup function is essential for resource management and avoiding memory leaks.</p><p>Here’s an example of using a cleanup function:</p><pre>useEffect(() =&gt; {<br>  // Side effect code here<br><br>  return () =&gt; {<br>    // Cleanup code here<br>  };<br>}, [/* dependencies */]);</pre><h3>Order of Execution</h3><p>You can use multiple useEffect hooks in a single component, and they will run in the order they appear. This allows you to organize and separate different types of side effects.</p><pre>useEffect(() =&gt; {<br>  // First effect<br>}, [/* dependencies */]);<br><br>useEffect(() =&gt; {<br>  // Second effect<br>}, [/* dependencies */]);</pre><h3>Running useEffect Only on the First Render</h3><p>By default, useEffect runs after every render. However, there are cases when you want an effect to run only during the initial render, similar to componentDidMount in class components. You can achieve this by using the useRef hook to track whether the component has rendered before.</p><p>Here’s how you can do it:</p><pre>import { useEffect, useRef } from &#39;react&#39;;<br><br>function MyComponent() {<br>  const hasRendered = useRef(false);<br><br>  useEffect(() =&gt; {<br>    if (!hasRendered.current) {<br>      // Your first-render-only code here<br>      hasRendered.current = true;<br>    } else {<br>      // Code for subsequent renders here<br>    }<br>  }, [/* dependencies */]);<br><br>  return &lt;div&gt;Component content&lt;/div&gt;;<br>}</pre><h3>Common Patterns with useEffect</h3><p>Understanding useEffect opens up numerous possibilities for managing side effects and component behavior. Here are some common patterns:</p><h3>Data Fetching</h3><p>Fetching data from APIs or external sources is a common use case for useEffect. You can make API calls when the component mounts and update the component&#39;s state with the fetched data.</p><h3>DOM Manipulation</h3><p>useEffect allows you to interact with the DOM. You can manipulate elements, add event listeners, or perform other operations that involve the DOM tree.</p><h3>Subscriptions</h3><p>For applications with real-time updates or event-driven behavior, useEffect can set up subscriptions to data sources. When data changes, the effect can update the component.</p><h3>Managing Timers</h3><p>You can use useEffect to create and manage timers for tasks like animations, notifications, or automatic updates.</p><h3>Pitfalls to Avoid</h3><p>While useEffect is a powerful tool, there are common pitfalls to be aware of:</p><h3>Infinite Loops</h3><p>Carefully choose dependencies in the dependency array to avoid unintentional infinite loops.</p><h3>Overusing useEffect</h3><p>Avoid putting too many unrelated side effects into a single useEffect. Split them into separate effects for better code organization.</p><h3>Incorrect Cleanup</h3><p>Ensure that cleanup functions are correctly implemented to prevent memory leaks.</p><h3>Tip: Using Multiple useEffect Hooks for Better Organization</h3><p>React allows you to use multiple useEffect hooks within a single component. This feature can greatly enhance the organization and readability of your code, as it allows you to isolate different side effects and their associated logic.</p><p>For example, if you have a component that needs to fetch data from an API, update the document title, and subscribe to a real-time event source, you can use separate useEffect hooks for each of these tasks. This separation of concerns makes your code more modular and easier to maintain.</p><p>Here’s an example of how you can use multiple useEffect hooks:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>function MyComponent() {<br>  const [data, setData] = useState(null);<br><br>  // Effect for data fetching<br>  useEffect(() =&gt; {<br>    // Fetch data from an API<br>    const fetchData = async () =&gt; {<br>      const response = await fetch(&#39;https://api.example.com/data&#39;);<br>      const result = await response.json();<br>      setData(result);<br>    };<br>    fetchData();<br>  }, []);<br><br>  // Effect for updating document title<br>  useEffect(() =&gt; {<br>    document.title = `MyComponent | ${data ? data.title : &#39;Loading...&#39;}`;<br>  }, [data]);<br><br>  // Effect for subscribing to real-time events<br>  useEffect(() =&gt; {<br>    const eventSource = new EventSource(&#39;https://api.example.com/events&#39;);<br>    eventSource.addEventListener(&#39;message&#39;, (event) =&gt; {<br>      // Handle incoming events<br>    });<br><br>    return () =&gt; {<br>      eventSource.close();<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {/* Render component content */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>By using separate useEffect hooks, you can clearly see the purpose of each effect, making your code more maintainable and easier to debug. This modular approach also allows you to manage dependencies for each effect independently, ensuring that they run only when necessary.</p><p>In conclusion, utilizing multiple useEffect hooks can significantly improve the structure and organization of your React components, making your codebase more robust and maintainable.</p><h3>Conclusion</h3><p>The useEffect hook is a cornerstone of React functional components. Understanding its usage is essential for managing side effects, controlling component behavior, and building robust web applications. By mastering useEffect, you unlock the full potential of React&#39;s functional components and become a more proficient React developer. So, do you really understand useEffect? Dive deep, experiment, and embrace the power it brings to your React applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d0b0316d2c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>