<?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 om prakash on Medium]]></title>
        <description><![CDATA[Stories by om prakash on Medium]]></description>
        <link>https://medium.com/@kom50?source=rss-f50e58802a25------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VfNItIT14PyV_ANwbHX17g.jpeg</url>
            <title>Stories by om prakash on Medium</title>
            <link>https://medium.com/@kom50?source=rss-f50e58802a25------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:53:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kom50/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Type-Safe Express API with Zod and OpenAPI]]></title>
            <link>https://medium.com/@kom50/building-a-type-safe-express-api-with-zod-and-openapi-938563eba54f?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/938563eba54f</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[zod]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 02:52:51 GMT</pubDate>
            <atom:updated>2026-08-21T03:04:24.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsORaXXcZcsXRgQrFTub5w.png" /><figcaption>Building a Type-Safe Express API with Zod and OpenAPI</figcaption></figure><p>When building APIs with Express and TypeScript, I often found myself repeating the same things:</p><ul><li>Define a Zod schema for validation.</li><li>Define TypeScript types from that schema.</li><li>Validate requests inside middleware.</li><li>Validate responses separately.</li><li>Write OpenAPI documentation manually.</li><li>Keep the implementation and documentation in sync.</li></ul><p>It worked, but it didn’t feel right.</p><p>I wanted the <strong>API contract to be defined only once</strong>.</p><p>That idea led me to build <strong>express-zod-router</strong>.</p><p><a href="https://github.com/kom50/express-zod-router?utm_source=chatgpt.com">GitHub — express-zod-router</a></p><h3>The idea</h3><p>The goal is simple:</p><blockquote><strong><em>Define your API contract once, and use it for validation, types, responses, and OpenAPI documentation.</em></strong></blockquote><p>For example:</p><pre>const CreateUserSchema = z.object({<br>  name: z.string(),<br>  email: z.string().email(),<br>});<br><br>api.post(&quot;/users&quot;, {<br>  body: CreateUserSchema,<br>  response: {<br>    201: UserSchema,<br>  },<br>  handler: async (req) =&gt; {<br>    const user = await createUser(req.body);<br>    return {<br>      status: 201,<br>      body: user,<br>    };<br>  },<br>});</pre><p>From this single route definition, the library can use the Zod schemas for runtime validation and TypeScript inference, while also generating OpenAPI documentation.</p><p>The intention isn’t to replace Express.</p><p>Instead, it provides a thin layer on top of Express to make contract-driven APIs easier to build.</p><h3>Why build another Express library?</h3><p>Express is intentionally minimal, which is one of the reasons I like it.</p><p>But as an application grows, API contracts become harder to maintain.</p><p>You may have validation in one place, TypeScript types somewhere else, Swagger definitions somewhere else, and the actual route implementation somewhere else.</p><p>Eventually, these can drift apart.</p><p>I wanted to explore a different approach:</p><p><strong>Schema → Request validation → Type inference → Response validation → OpenAPI</strong></p><p>One contract, multiple benefits.</p><h3>Where it is today</h3><p>express-zod-router currently focuses on the core API contract experience:</p><ul><li>Request validation with Zod</li><li>TypeScript inference</li><li>Response validation</li><li>OpenAPI generation</li><li>Express integration</li><li>Route-level API definitions</li><li>API documentation</li></ul><p>I’m also working on improving the developer experience around middleware, authentication, versioning, error handling, observability, testing, and more advanced HTTP features.</p><h3>I’d love developer feedback</h3><p>This project is still evolving, and that’s exactly why I’m sharing it.</p><p>I’m particularly interested in feedback on:</p><p><strong>Is the API intuitive?</strong></p><p><strong>Does the route definition feel natural to an Express developer?</strong></p><p><strong>Is the documentation easy to follow?</strong></p><p><strong>Would you use this approach in a real project?</strong></p><p><strong>What would you change or add?</strong></p><p>If you’re interested in Express, TypeScript, Zod, OpenAPI, or contract-driven APIs, I’d genuinely appreciate your thoughts.</p><p>You can explore the project here:</p><p><a href="https://github.com/kom50/express-zod-router?utm_source=chatgpt.com">express-zod-router on GitHub</a></p><p><a href="https://www.npmjs.com/package/express-zod-router?utm_source=chatgpt.com">express-zod-router on npm</a></p><p><strong>I’d love to hear what you think.</strong></p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=938563eba54f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing API Code Manually: Generate TypeScript API Clients with Hey API]]></title>
            <link>https://medium.com/@kom50/stop-writing-api-code-manually-generate-typescript-api-clients-with-hey-api-75820c332018?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/75820c332018</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[open-api]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 18:34:35 GMT</pubDate>
            <atom:updated>2026-08-02T18:41:38.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Stop Writing API Code Manually: Generate TypeScript API Clients with Hey API" src="https://cdn-images-1.medium.com/max/1024/1*aASgDaGm3tLHlF14weTupA.png" /></figure><p>If you’ve worked on a frontend application that consumes REST APIs, you’ve probably written code like this again and again:</p><pre>export interface User {<br>  id: string;<br>  name: string;<br>  email: string;<br>}<br><br>export const getUsers = async (): Promise&lt;User[]&gt; =&gt; {<br>  const response = await fetch(&#39;/api/users&#39;);<br>  return response.json();<br>};</pre><p>Then the backend API changes.</p><p>A field is renamed.</p><p>A new endpoint is added.</p><p>The request body changes.</p><p>The response structure changes.</p><p>And suddenly, you’re spending time updating TypeScript interfaces, API functions, hooks, and validation code manually.</p><p><strong>What if your OpenAPI/Swagger specification could generate all of this for you?</strong></p><p>That’s where <strong>Hey API</strong> comes in.</p><h3>What is Hey API?</h3><p><a href="https://heyapi.dev/?utm_source=chatgpt.com">Hey API</a> is an OpenAPI-based code generation ecosystem that can turn your API specification into production-ready TypeScript code.</p><p>Its OpenAPI TypeScript generator can generate:</p><ul><li>TypeScript types</li><li>Type-safe API SDKs</li><li>Zod schemas</li><li>TanStack Query hooks</li><li>HTTP clients</li><li>And many other integrations through plugins</li></ul><p>The project currently provides 20+ plugins and supports HTTP clients/integrations including Fetch, Axios, Angular, Next.js, and Nuxt.</p><p>The basic idea is simple:</p><pre>OpenAPI / Swagger<br>       ↓<br>   Hey API<br>       ↓<br> ┌───────────────┐<br> │ TypeScript    │<br> │ API SDK       │<br> │ Zod schemas   │<br> │ Query hooks   │<br> │ HTTP client   │<br> └───────────────┘</pre><p>Instead of manually maintaining your frontend API layer, your OpenAPI specification becomes the source of truth.</p><h3>The Problem With Writing API Code Manually</h3><p>Imagine your backend exposes this endpoint:</p><pre>GET /users</pre><p>The API response looks like:</p><pre>[<br>  {<br>    &quot;id&quot;: &quot;123&quot;,<br>    &quot;name&quot;: &quot;Om&quot;,<br>    &quot;email&quot;: &quot;om@example.com&quot;<br>  }<br>]</pre><p>Normally, you might create:</p><pre>export interface User {<br>  id: string;<br>  name: string;<br>  email: string;<br>}</pre><p>Then create an API function:</p><pre>export async function getUsers() {<br>  const response = await fetch(&#39;/api/users&#39;);<br>  if (!response.ok) {<br>      throw new Error(&#39;Failed to fetch users&#39;);<br>    }<br>    return response.json();<br>}</pre><p>And if you’re using React Query, you might create another layer:</p><pre>export function useUsers() {<br>  return useQuery({<br>    queryKey: [&#39;users&#39;],<br>    queryFn: getUsers,<br>  });<br>}</pre><p>Now imagine you have:</p><ul><li>100+ endpoints</li><li>Request types</li><li>Response types</li><li>Query parameters</li><li>Path parameters</li><li>Authentication</li><li>Mutations</li><li>React Query hooks</li><li>Validation schemas</li></ul><p>That’s a lot of repetitive code.</p><p>And repetitive code eventually becomes maintenance work.</p><h3>Enter OpenAPI</h3><p>If your backend already exposes an OpenAPI specification, you already have most of the information required to generate this code.</p><p>For example:</p><pre>paths:<br>  /users:<br>    get:<br>      operationId: getUsers<br>      responses:<br>        &#39;200&#39;:<br>          description: Users<br>          content:<br>            application/json:<br>              schema:<br>                type: array<br>                items:<br>                  $ref: &#39;#/components/schemas/User&#39;</pre><p>And your schema:</p><pre>components:<br>  schemas:<br>    User:If you found this useful…<br>Follow me for more articles about:<br><br>React<br>TypeScript<br>Node.js<br>API development<br>OpenAPI<br>Developer tooling<br>Frontend architecture<br>And if you’re still writing hundreds of API interfaces manually…<br><br>Maybe it’s time to automate them.<br>      type: object<br>      required:<br>        - id<br>        - name<br>        - email<br>      properties:<br>        id:<br>          type: string<br>        name:<br>          type: string<br>        email:<br>          type: string</pre><p>Now Hey API can use this specification to generate the TypeScript client.</p><h3>Getting Started</h3><p>First, install the package:</p><pre>npm install @hey-api/openapi-ts -D -E</pre><h3>Create the Configuration</h3><pre>// openapi-ts.config.ts<br>import { defineConfig } from &#39;@hey-api/openapi-ts&#39;;<br><br>export default defineConfig({<br>  input: &#39;./openapi.json&#39;, // <br>  output: &#39;./src/client&#39;,<br>});</pre><p>That’s enough for a basic setup.</p><p>Run the generator:</p><pre>npx @hey-api/openapi-ts</pre><p>Or add it to package.json:</p><pre>{<br>  &quot;scripts&quot;: {<br>    &quot;generate-api&quot;: &quot;openapi-ts&quot;<br>  }<br>}</pre><p>Then:</p><pre>npm run generate-api</pre><p>Hey API reads your OpenAPI specification and generates the client inside src/client.</p><h3>What Gets Generated?</h3><p>This is where things become interesting.</p><p>Instead of manually creating API functions and TypeScript interfaces, the generator creates them from your OpenAPI definition.</p><p>Generated types similar to:</p><pre>export type User = {<br>  id: string;<br>  name: string;<br>  email: string;<br>};</pre><p>And generated API operations:</p><pre>import { getUsers } from &#39;./client/sdk.gen&#39;;<br>const { data, error } = await getUsers();</pre><p>Now your frontend doesn’t need to manually define the API’s.</p><p>The OpenAPI specification defines it.</p><h3>Type-Safe API Calls</h3><p>One of the biggest advantages is type safety.</p><p>Suppose your API expects:</p><pre>GET /users/{id}</pre><p>The generated function knows that it requires an id.</p><p>Instead of manually remembering the API contract, TypeScript can guide you:</p><pre>const response = await getUser({<br>  path: {<br>    id: &#39;123&#39;<br>  }<br>});</pre><p>If the API expects a different structure, your editor can catch incorrect usage during development.</p><p>That’s much better than discovering the problem at runtime.</p><h3>Generate Zod Schemas</h3><p>This is one of the features I particularly like.</p><p>Hey API supports plugins, including Zod schema generation.</p><p>For example, you can configure:</p><pre>import { defineConfig } from &#39;@hey-api/openapi-ts&#39;;<br>export default defineConfig({<br>  input: &#39;./openapi.json&#39;,<br>  output: &#39;./src/client&#39;,<br>  plugins: [<br>      &#39;@hey-api/client-fetch&#39;,<br>      &#39;@hey-api/sdk&#39;,<br>      &#39;@hey-api/typescript&#39;,<br>      &#39;zod&#39;,<br>    ],<br>});</pre><p>Now your OpenAPI schemas can also become runtime validation schemas.</p><p>For example:</p><pre>import { z } from &#39;zod&#39;;<br> <br>export const UserSchema = z.object({<br>  id: z.string(),<br>  name: z.string(),<br>  email: z.string().email(),<br>});</pre><p>This gives you both:</p><p><strong>Compile-time safety: </strong>TypeScript</p><p><strong>Runtime validation: </strong>Zod</p><p>That’s a powerful combination when working with external API responses.</p><p><strong>Note:</strong> Hey API provides multiple validation options.</p><h3>Generate TanStack Query Hooks</h3><p>If you’re using TanStack Query, you don’t necessarily want to manually write:</p><pre>useQuery()<br>useMutation()<br>useInfiniteQuery()</pre><p>for every API endpoint.</p><p>Hey API provides plugins for integrations such as TanStack Query.</p><p>That means your API specification can become the foundation for both:</p><pre>API types<br>     +<br>API client<br>     +<br>Data fetching hooks</pre><p>Instead of maintaining all three layers separately.</p><h3>Configure Your API Client</h3><p>You can configure the generated client with your API’s base URL.</p><p>For example:</p><pre>import { client } from &#39;./client&#39;;<br><br>client.setConfig({<br>  baseUrl: &#39;https://api.example.com&#39;,<br>});</pre><p>Then use the generated SDK:</p><pre>import { getPets } from &#39;./client/sdk.gen&#39;;<br>const { data, error } = await getPets();</pre><p>The official documentation follows this same generated-client approach.</p><h3>What About Authentication?</h3><p>Most real-world applications need authentication.</p><p>For example:</p><pre>Authorization: Bearer &lt;token&gt;</pre><p>Instead of manually adding authentication logic to every API function, the generated client can be configured around the HTTP client you’re using.</p><p>This is particularly useful for applications using:</p><ul><li>JWT</li><li>Bearer tokens</li><li>Cookies</li><li>API keys</li><li>Custom headers</li></ul><p>The important architectural idea is:</p><pre>Authentication<br>       ↓<br>HTTP Client<br>       ↓<br>Generated SDK<br>       ↓<br>Application</pre><p>Your API functions remain clean.</p><h3>It Isn’t Just About TypeScript Types</h3><p>At first glance, you might think:</p><blockquote><em>“Isn’t this just another TypeScript type generator?”</em></blockquote><p>Not really.</p><p>The interesting part of Hey API is its <strong>plugin architecture</strong>.</p><p>You can choose what you actually need.</p><p>For example:</p><pre>OpenAPI<br>                   │<br>                   ▼<br>             Hey API Generator<br>                   │<br>        ┌──────────┼──────────┐<br>        ▼          ▼          ▼<br>     Types       SDK        Zod<br>                             <br>                   │<br>                   ▼<br>             Query plugins</pre><p>The documentation describes the generator as a plugin-based system where functionality such as SDKs, types, schemas, and data-fetching integrations can be added independently.</p><p>This makes it much more flexible than generating one huge client and accepting everything it produces.</p><h3>The Real Benefit: One Source of Truth</h3><p>This is probably the biggest reason I like OpenAPI code generation.</p><p>Without code generation:</p><pre>Backend<br>   │<br>   ├── API implementation<br>   │<br>   └── Documentation<br><br><br><br>Frontend<br>   │<br>   ├── Interfaces<br>   ├── API functions<br>   ├── Hooks<br>   └── Validation</pre><p>There are multiple places where the API contract can become inconsistent.</p><p>With OpenAPI + code generation:</p><pre>              OpenAPI<br>                 │<br>        ┌────────┼─────────┐<br>        ▼        ▼         ▼<br>      Types     SDK       Zod<br>                 │<br>                 ▼<br>             Frontend</pre><p>The OpenAPI specification becomes the contract.</p><p>When the backend changes the contract, regenerate the client.</p><h3>What I Like About Hey API</h3><p>A few things stand out to me.</p><h4>1. OpenAPI-first</h4><p>If your backend already maintains an OpenAPI specification, you can use it as the source of truth.</p><h4>2. Type safety</h4><p>Generated TypeScript types make API usage much safer.</p><h4>3. SDK generation</h4><p>You don’t just get interfaces; you can generate a usable API client.</p><h4>4. Plugin architecture</h4><p>You can add functionality when you need it instead of adopting everything at once.</p><h4>5. Zod support</h4><p>Generating runtime validation schemas is extremely useful for applications where API data needs to be validated.</p><h4>6. Multiple integrations</h4><p>The ecosystem supports different HTTP clients and data-fetching libraries, making it useful beyond a single frontend stack.</p><h3>When Should You Use It?</h3><p>I would consider Hey API when:</p><ul><li>Your backend already has OpenAPI/Swagger.</li><li>Your frontend is TypeScript-based.</li><li>You have many API endpoints.</li><li>API contracts change frequently.</li><li>You want to redcccuce repetitive API code.</li><li>You use Zod.</li><li>You use TanStack Query.</li><li>You want generated SDKs.</li><li>You want your frontend and backend contracts to stay synchronized.</li></ul><p>For a small project with two or three endpoints, manual code might be perfectly fine.</p><p>But when your application grows…</p><p><strong>Code generation starts making a lot more sense.</strong></p><h3>Final Thoughts</h3><p>I’ve used API generators before, and the reason I keep coming back to this approach is simple:</p><blockquote><strong><em>Don’t manually write code that can reliably be generated from a contract.</em></strong></blockquote><p>Your backend already knows what the API looks like.</p><p>Your OpenAPI specification describes that contract.</p><p>So instead of manually converting:</p><pre> OpenAPI<br>   ↓<br>TypeScript types<br>   ↓<br> API functions<br>   ↓<br> Hooks<br>   ↓<br> Validation</pre><p>you can automate the pipeline:</p><pre>OpenAPI<br>   ↓<br>Hey API<br>   ↓<br>TypeScript + SDK + Zod + Query integrations</pre><p>That means less boilerplate, fewer duplicated definitions, and a much easier API layer to maintain.</p><p>If you’re working on a TypeScript frontend with a reasonably large REST API, <strong>Hey API is definitely worth trying.</strong></p><p><strong>Documentation:</strong> <a href="https://heyapi.dev/">Hey API — OpenAPI TypeScript</a></p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75820c332018" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orval: The Tool That Saved Me from Writing API Code Again and Again]]></title>
            <link>https://medium.com/@kom50/orval-the-tool-that-saved-me-from-writing-api-code-again-and-again-f3f705d41829?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3f705d41829</guid>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Tue, 16 Jun 2026 05:31:57 GMT</pubDate>
            <atom:updated>2026-06-16T05:45:02.910Z</atom:updated>
            <content:encoded><![CDATA[<h4>Orval turns your OpenAPI specification into fully typed API clients, React Query hooks, Zod schemas, mocks, and validators — so you can focus on building features instead of writing boilerplate.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pcwrNjF91DDWtykWEeZhSQ.png" /><figcaption>Orval turns your OpenAPI specification into fully typed API clients, React Query hooks, Zod schemas, mocks, and validators — so you can focus on building features instead of writing boilerplate.</figcaption></figure><p>As a frontend developer, I spent a lot of time writing the same API code over and over again. Every new endpoint required TypeScript types, Axios functions, and React Query hooks.</p><p>It took time, and small mistakes could easily cause bugs.</p><p>Then I discovered <strong>Orval</strong>.</p><h3>What is Orval?</h3><p>Orval is an open-source tool that reads an <strong>OpenAPI (Swagger)</strong> file and automatically generates:</p><ul><li>TypeScript types</li><li>API clients and functions</li><li>React Query hooks (and support for Vue Query, SWR, Angular, and more)</li><li>Mock data for testing and development</li><li>Zod validation schemas for request and response validation</li></ul><p>This helps keep the frontend and backend in sync.</p><h3>The Problem</h3><p>Suppose the backend has this API:</p><pre>GET /users</pre><p>Without Orval, we usually write code like this:</p><pre>import axios from &quot;axios&quot;;<br><br>export interface User {<br>  id: number;<br>  name: string;<br>  email: string;<br>}<br>export const getUsers = async (): Promise&lt;User[]&gt; =&gt; {<br>  const { data } = await axios.get(&quot;/api/users&quot;);<br>  return data;<br>};</pre><p>If the backend changes the response, we need to update everything manually.</p><h3>How Orval Helps</h3><p>With Orval, you only need the Swagger file.</p><p>Install it:</p><pre>npm install orval --save-dev</pre><p>Create an orval.config.js file:</p><pre>module.exports = {<br>  api: {<br>    input: &quot;./swagger.json&quot;,<br>    output: {<br>      target: &quot;./src/api/generated.ts&quot;,<br>      client: &quot;react-query&quot;,<br>    },<br>  },<br>};</pre><p>Run:</p><pre>npx orval</pre><p>Orval automatically creates API functions and React Query hooks.</p><h3>Using Orval in React</h3><p>Instead of writing API logic yourself, you can directly use the generated hook:</p><pre>import { useGetUsers } from &quot;./api/generated&quot;;<br><br>function UserList() {<br>  const { data, isLoading } = useGetUsers();<br>  if (isLoading) {<br>    return &lt;p&gt;Loading...&lt;/p&gt;;<br>  }<br>  return (<br>    &lt;div&gt;<br>      {data?.map((user) =&gt; (<br>        &lt;p key={user.id}&gt;{user.name}&lt;/p&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}<br>export default UserList;</pre><p>No manual API function.<br>No manual TypeScript types.<br>Everything is generated automatically.</p><h3>Mock Data for Testing</h3><p>Orval can also generate mock data.</p><p>This becomes helpful when the backend team hasn’t finished their task, but you have to develop your frontend.</p><p>The developers do not have to wait until they implement the APIs.</p><h3>Why I Like Orval</h3><p>After using Orval, I noticed several benefits:</p><ul><li>Less repetitive coding</li><li>Strong TypeScript support</li><li>Better integration with React Query, Vue Query, SWR, and more.</li><li>Easy maintenance when APIs change</li><li>Request and response validators</li><li>Faster frontend development</li></ul><h3>Final Thoughts</h3><p><a href="https://orval.dev/">Orval</a> is a simple but powerful tool for modern frontend development.</p><p>If your project uses Swagger or OpenAPI, Orval can save a lot of development time and reduce bugs caused by manual API coding.</p><p>You should check out this — <a href="https://orval.dev/">https://orval.dev/</a></p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3f705d41829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Complete Guide to Formik in React: From Zero to Hero]]></title>
            <link>https://medium.com/@kom50/the-complete-guide-to-formik-in-react-from-zero-to-hero-6107274102e4?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/6107274102e4</guid>
            <category><![CDATA[formik]]></category>
            <category><![CDATA[form-validation]]></category>
            <category><![CDATA[yup]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Thu, 11 Dec 2025 07:08:50 GMT</pubDate>
            <atom:updated>2025-12-11T07:09:50.667Z</atom:updated>
            <content:encoded><![CDATA[<h4>A comprehensive tutorial on building powerful forms with Formik</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WI-2Ni0Lw8T6fH3tNFCGw.png" /></figure><p>Forms are the backbone of user interaction in web applications, but managing form state, validation, and submission in React can quickly become overwhelming. Enter Formik — the most popular form library in the React ecosystem.</p><p>In this comprehensive guide, we’ll explore everything you need to know about Formik, from basic setup to advanced patterns.</p><h3>Why Formik?</h3><p>Before Formik, React developers faced these challenges:</p><p>❌ Manual state management for each input field<br>❌ Complex validation logic<br>❌ Handling touched/dirty states<br>❌ Error message management<br>❌ Form submission handling</p><h3>What Formik Provides:</h3><p>✅ Automatic form state management<br>✅ Built-in validation support<br>✅ Error handling out of the box<br>✅ Field-level and form-level validation<br>✅ Powerful API with minimal boilerplate</p><h3>Installation &amp; Setup</h3><p><strong>Install Formik</strong></p><p>First, let’s install Formik in your React project. Open your terminal and run:</p><pre>npm install formik<br><br># or with yarn<br>yarn add formik</pre><p><strong>Install Yup (for validation schema)</strong></p><p>Yup is a JavaScript schema builder for value parsing and validation. It works seamlessly with Formik:</p><pre>npm install yup<br><br># or with yarn<br>yarn add yup</pre><h3>Basic Form Implementation</h3><h4>Example 1: Simple Login Form (useFormik Hook)</h4><p>The useFormik hook is the simplest way to get started with Formik. It&#39;s perfect for smaller forms where you want direct control.</p><p><strong>What this example demonstrates:</strong></p><ul><li>Basic form state management</li><li>Handling input changes</li><li>Form submission</li><li>The useFormik hook approach</li></ul><pre>import React from &#39;react&#39;;<br>import { useFormik } from &#39;formik&#39;;<br><br>const LoginForm = () =&gt; { <br>  const formik = useFormik({ <br>    initialValues: {<br>      email: &#39;&#39;,<br>      password: &#39;&#39;,<br>    }, <br>    onSubmit: values =&gt; {<br>      console.log(&#39;Form values:&#39;, values);<br>      // Handle login logic here (API call, authentication, etc.)<br>    },<br>  });<br><br>  return (<br>    &lt;form onSubmit={formik.handleSubmit}&gt;<br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>        &lt;input<br>          id=&quot;email&quot;<br>          name=&quot;email&quot;<br>          type=&quot;email&quot;<br>          onChange={formik.handleChange}  // Updates formik state<br>          onBlur={formik.handleBlur}      <br>          value={formik.values.email}     // Controlled input<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Password&lt;/label&gt;<br>        &lt;input<br>          id=&quot;password&quot;<br>          name=&quot;password&quot;<br>          type=&quot;password&quot;<br>          onChange={formik.handleChange}<br>          onBlur={formik.handleBlur}<br>          value={formik.values.password}<br>        /&gt;<br>      &lt;/div&gt;<br><br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default LoginForm;</pre><p><strong>Key Concepts:</strong></p><ul><li>formik.handleChange: Automatically updates the form state</li><li>formik.handleBlur: Marks fields as &quot;touched&quot;</li><li>formik.values: Contains current form values</li><li>formik.handleSubmit: Handles form submission</li></ul><h4>Example 2: Using Formik Component</h4><p>The &lt;Formik&gt; component provides a cleaner, more declarative approach. It uses the render props pattern and reduces boilerplate code.</p><p><strong>Advantages of this approach:</strong></p><ul><li>Less repetitive code with &lt;Field&gt; components</li><li>Automatic binding of onChange, onBlur, and value</li><li>Better for medium to large forms</li><li>Access to form state through render props</li></ul><pre>import React from &#39;react&#39;;<br>import { Formik, Form, Field } from &#39;formik&#39;;<br><br>const LoginFormComponent = () =&gt; {<br>  return (<br>    &lt;Formik<br>      // Set initial values for the form<br>      initialValues={{ email: &#39;&#39;, password: &#39;&#39; }}<br>      <br>      // Handle form submission<br>      onSubmit={(values, { setSubmitting }) =&gt; {<br>        // Simulate async API call<br>        setTimeout(() =&gt; {<br>          console.log(values);<br>          setSubmitting(false); // Re-enable submit button<br>        }, 400);<br>      }}<br>    &gt;<br>      {/* Render props: get form state and helpers */}<br>      {({ isSubmitting }) =&gt; (<br>        &lt;Form&gt; {/* Automatically handles onSubmit */}<br>          &lt;div&gt;<br>            &lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>            {/* Field automatically connects to Formik */}<br>            &lt;Field type=&quot;email&quot; name=&quot;email&quot; /&gt;<br>          &lt;/div&gt;<br><br>          &lt;div&gt;<br>            &lt;label htmlFor=&quot;password&quot;&gt;Password&lt;/label&gt;<br>            &lt;Field type=&quot;password&quot; name=&quot;password&quot; /&gt;<br>          &lt;/div&gt;<br><br>          {/* Disable button while submitting */}<br>          &lt;button type=&quot;submit&quot; disabled={isSubmitting}&gt;<br>            Submit<br>          &lt;/button&gt;<br>        &lt;/Form&gt;<br>      )}<br>    &lt;/Formik&gt;<br>  );<br>};<br><br>export default LoginFormComponent;</pre><p><strong>What’s happening here:</strong></p><ul><li>&lt;Form&gt;: Replaces &lt;form&gt; and auto-binds to Formik&#39;s handleSubmit</li><li>&lt;Field&gt;: Automatically wired to Formik (no need for onChange/onBlur/value)</li><li>isSubmitting: Tracks submission state</li><li>setSubmitting(false): Manually control submission state</li></ul><h3>Validation with Yup</h3><p>Validation is crucial for data integrity and user experience. Formik supports both schema-based validation (with Yup) and custom validation functions.</p><h4>Basic Validation Schema</h4><p>Yup allows you to define validation rules declaratively. This example shows a comprehensive signup form with various validation types.</p><p><strong>What we’re validating:</strong></p><ul><li>String length constraints</li><li>Email format</li><li>Password complexity</li><li>Password confirmation matching</li><li>Required fields</li></ul><pre>import React from &#39;react&#39;;<br>import { Formik, Form, Field, ErrorMessage } from &#39;formik&#39;;<br>import * as Yup from &#39;yup&#39;;<br><br>// Define validation schema using Yup<br>const SignupSchema = Yup.object().shape({<br>  firstName: Yup.string()<br>    .min(2, &#39;Too Short!&#39;)           <br>    .max(50, &#39;Too Long!&#39;)           <br>    .required(&#39;Required&#39;),        <br>  <br>  lastName: Yup.string()<br>    .min(2, &#39;Too Short!&#39;)<br>    .max(50, &#39;Too Long!&#39;)<br>    .required(&#39;Required&#39;)<br>});<br><br>const SignupForm = () =&gt; {<br>  return (<br>    &lt;Formik<br>      initialValues={{<br>        firstName: &#39;&#39;,<br>        lastName: &#39;&#39;<br>      }}<br>      // Pass the validation schema to Formik<br>      validationSchema={SignupSchema}<br>      onSubmit={(values) =&gt; {<br>        console.log(values);<br>      }}<br>    &gt;<br>      {({ errors, touched }) =&gt; (<br>        &lt;Form&gt;<br>          &lt;div&gt;<br>            &lt;label&gt;First Name&lt;/label&gt;<br>            &lt;Field name=&quot;firstName&quot; /&gt;<br>            {/* Display error message if field is touched and has error */}<br>            &lt;ErrorMessage name=&quot;firstName&quot; component=&quot;div&quot; className=&quot;error&quot; /&gt;<br>          &lt;/div&gt;<br><br>          &lt;div&gt;<br>            &lt;label&gt;Last Name&lt;/label&gt;<br>            &lt;Field name=&quot;lastName&quot; /&gt;<br>            &lt;ErrorMessage name=&quot;lastName&quot; component=&quot;div&quot; className=&quot;error&quot; /&gt;<br>          &lt;/div&gt;<br><br>          &lt;button type=&quot;submit&quot;&gt;Sign Up&lt;/button&gt;<br>        &lt;/Form&gt;<br>      )}<br>    &lt;/Formik&gt;<br>  );<br>};<br><br>export default SignupForm;</pre><p><strong>Understanding the validation flow:</strong></p><ol><li>User types in a field</li><li>Formik validates on blur (when the user leaves the field)</li><li>Errors are stored in errors object</li><li>touched tracks which fields the user has interacted with</li><li>ErrorMessage displays error only if the field is touched AND has an error</li></ol><h3>Custom Validation Function</h3><p>Sometimes you need custom validation logic that Yup doesn’t cover. Here’s how to write your own validation function.</p><p><strong>When to use custom validation:</strong></p><ul><li>Complex business rules</li><li>Cross-field validation</li><li>Custom regex patterns</li><li>API-based validation</li></ul><pre>// Custom validation function<br>// Returns an object with field names as keys and error messages as values<br>const validate = values =&gt; {<br>  const errors = {};<br><br>  // Email validation<br>  if (!values.email) {<br>    errors.email = &#39;Required&#39;;<br>  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)) {<br>    errors.email = &#39;Invalid email address&#39;;<br>  }<br><br>  // Password validation<br>  if (!values.password) {<br>    errors.password = &#39;Required&#39;;<br>  } else if (values.password.length &lt; 8) {<br>    errors.password = &#39;Password must be at least 8 characters&#39;;<br>  }<br><br>  return errors; // Return empty object if no errors<br>};<br><br>const FormWithCustomValidation = () =&gt; {<br>  return (<br>    &lt;Formik<br>      initialValues={{ email: &#39;&#39;, password: &#39;&#39; }}<br>      validate={validate} // Pass custom validation function<br>      onSubmit={values =&gt; console.log(values)}<br>    &gt;<br>      {/* Form content */}<br>    &lt;/Formik&gt;<br>  );<br>};</pre><h3>Advanced Features</h3><h4>Field Arrays (Dynamic Fields)</h4><p>Field Arrays are perfect for dynamic lists like “Add Friend”, “Add Item”, or any scenario where users can add/remove fields.</p><p><strong>Use cases:</strong></p><ul><li>Multiple phone numbers</li><li>List of addresses</li><li>Product variants</li><li>Team members</li></ul><p><strong>How it works:</strong></p><ul><li>values.friends is an array</li><li>push() adds a new item</li><li>remove(index) deletes an item</li><li>Each field has a unique indexed name</li></ul><pre>import React from &#39;react&#39;;<br>import { Formik, Form, Field, FieldArray } from &#39;formik&#39;;<br><br>const FriendsForm = () =&gt; {<br>  return (<br>    &lt;Formik<br>      // Initialize with an array containing one empty string<br>      initialValues={{<br>        friends: [&#39;&#39;]<br>      }}<br>      onSubmit={values =&gt; console.log(values)}<br>      // Output example: { friends: [&#39;John&#39;, &#39;Jane&#39;, &#39;Bob&#39;] }<br>    &gt;<br>      {({ values }) =&gt; (<br>        &lt;Form&gt;<br>          {/* FieldArray manages array of fields */}<br>          &lt;FieldArray name=&quot;friends&quot;&gt;<br>            {/* Render prop provides helper methods */}<br>            {({ push, remove }) =&gt; (<br>              &lt;div&gt;<br>                {/* Loop through friends array */}<br>                {values.friends.map((friend, index) =&gt; (<br>                  &lt;div key={index}&gt;<br>                    {/* Dynamic field name using index */}<br>                    &lt;Field <br>                      name={`friends.${index}`} <br>                      placeholder={`Friend #${index + 1}`}<br>                    /&gt;<br>                    &lt;button<br>                      type=&quot;button&quot;<br>                      onClick={() =&gt; remove(index)} // Remove this field<br>                    &gt;<br>                      Remove<br>                    &lt;/button&gt;<br>                  &lt;/div&gt;<br>                ))}<br>                &lt;button<br>                  type=&quot;button&quot;<br>                  onClick={() =&gt; push(&#39;&#39;)} // Add new empty field<br>                &gt;<br>                  Add Friend<br>                &lt;/button&gt;<br>              &lt;/div&gt;<br>            )}<br>          &lt;/FieldArray&gt;<br>          &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/Form&gt;<br>      )}<br>    &lt;/Formik&gt;<br>  );<br>};</pre><p><strong>Important notes:</strong></p><ul><li>Each field must have a unique key prop (use index)</li><li>Field names use dot notation: friends.0, friends.1, etc.</li><li>Always use helper methods (push, remove) instead of direct array manipulation</li></ul><h4>Nested Objects</h4><p>When your form data has a hierarchical structure, nested objects keep your data organized and maintainable.</p><p><strong>Real-world scenarios:</strong></p><ul><li>User profile with a separate address object</li><li>Order with billing and shipping info</li><li>Product with specifications object</li></ul><p><strong>Benefits</strong>:</p><ul><li>Organized data structure</li><li>Easier to work with APIs</li><li>Better separation of concerns</li></ul><pre>import React from &#39;react&#39;;<br>import { Formik, Form, Field } from &#39;formik&#39;;<br>import * as Yup from &#39;yup&#39;;<br><br>// Validation schema mirrors the nested structure<br>const ProfileSchema = Yup.object().shape({<br>  user: Yup.object().shape({<br>    name: Yup.string().required(&#39;Required&#39;),<br>    email: Yup.string().email(&#39;Invalid email&#39;).required(&#39;Required&#39;),<br>  }),<br>});<br><br>const ProfileForm = () =&gt; {<br>  return (<br>    &lt;Formik<br>      // Nested object structure<br>      initialValues={{<br>        user: {<br>          name: &#39;&#39;,<br>          email: &#39;&#39;,<br>        },<br>      }}<br>      validationSchema={ProfileSchema}<br>      onSubmit={values =&gt; console.log(values)}<br>    &gt;<br>      &lt;Form&gt;<br>        &lt;h3&gt;User Information&lt;/h3&gt;<br>        {/* Access nested fields with dot notation */}<br>        &lt;Field name=&quot;user.name&quot; placeholder=&quot;Name&quot; /&gt;<br>        &lt;Field name=&quot;user.email&quot; placeholder=&quot;Email&quot; /&gt;<br><br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/Form&gt;<br>    &lt;/Formik&gt;<br>  );<br>};</pre><p><strong>Key points:</strong></p><ul><li>Use dot notation for field names: user.name, address.city</li><li>The validation schema should match the nested structure</li><li>Submitted data maintains the nested structure</li></ul><h4>Custom Input Components</h4><p>Creating reusable input components makes your forms more consistent and easier to maintain.</p><p><strong>Advantages</strong>:</p><ul><li>DRY (Don’t Repeat Yourself)</li><li>Consistent styling across your app</li><li>Centralized error handling</li><li>Easier to maintain and update</li></ul><p><strong>Custom Input</strong></p><p>This component encapsulates label, input, and error message in one reusable component.</p><pre>import React from &#39;react&#39;;<br>import { useField } from &#39;formik&#39;;<br><br>// Custom Text Input Component<br>// useField hook provides field props and meta information<br>const TextInput = ({ label, ...props }) =&gt; {<br>  // useField returns [fieldProps, meta]<br>  // fieldProps: { name, value, onChange, onBlur }<br>  // meta: { touched, error, initialValue }<br>  const [field, meta] = useField(props);<br>  <br>  return (<br>    &lt;div className=&quot;form-group&quot;&gt;<br>      &lt;label htmlFor={props.id || props.name}&gt;{label}&lt;/label&gt;<br>      {/* Spread field props to get all necessary attributes */}<br>      &lt;input className=&quot;form-control&quot; {...field} {...props} /&gt;<br>      {/* Show error only if field was touched and has error */}<br>      {meta.touched &amp;&amp; meta.error ? (<br>        &lt;div className=&quot;error&quot;&gt;{meta.error}&lt;/div&gt;<br>      ) : null}<br>    &lt;/div&gt;<br>  );<br>};<br><br><br>// Custom Checkbox Component<br>const Checkbox = ({ children, ...props }) =&gt; {<br>  // Specify type as checkbox<br>  const [field, meta] = useField({ ...props, type: &#39;checkbox&#39; });<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;label className=&quot;checkbox&quot;&gt;<br>        &lt;input type=&quot;checkbox&quot; {...field} {...props} /&gt;<br>        {children}<br>      &lt;/label&gt;<br>      {meta.touched &amp;&amp; meta.error ? (<br>        &lt;div className=&quot;error&quot;&gt;{meta.error}&lt;/div&gt;<br>      ) : null}<br>    &lt;/div&gt;<br>  );<br>};<br><br><br>// Custom Select Component<br>const Select = ({ label, ...props }) =&gt; {<br>  const [field, meta] = useField(props);<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;label htmlFor={props.id || props.name}&gt;{label}&lt;/label&gt;<br>      &lt;select {...field} {...props} /&gt;<br>      {meta.touched &amp;&amp; meta.error ? (<br>        &lt;div className=&quot;error&quot;&gt;{meta.error}&lt;/div&gt;<br>      ) : null}<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>Using Custom Components</strong></p><p>Now you can use these components throughout your app with much cleaner code.</p><pre>// Usage Example - Much cleaner!<br>const CustomComponentForm = () =&gt; {<br>  return (<br>    &lt;Formik<br>      initialValues={{<br>        firstName: &#39;&#39;,<br>        lastName: &#39;&#39;,<br>        acceptedTerms: false,<br>        jobType: &#39;&#39;,<br>      }}<br>      onSubmit={values =&gt; console.log(values)}<br>    &gt;<br>      &lt;Form&gt;<br>        {/* No need to manually handle errors or labels */}<br>        &lt;TextInput<br>          label=&quot;First Name&quot;<br>          name=&quot;firstName&quot;<br>          type=&quot;text&quot;<br>          placeholder=&quot;John&quot;<br>        /&gt;<br><br>        &lt;TextInput<br>          label=&quot;Last Name&quot;<br>          name=&quot;lastName&quot;<br>          type=&quot;text&quot;<br>          placeholder=&quot;Doe&quot;<br>        /&gt;<br><br>        &lt;Select label=&quot;Job Type&quot; name=&quot;jobType&quot;&gt;<br>          &lt;option value=&quot;&quot;&gt;Select a job type&lt;/option&gt;<br>          &lt;option value=&quot;designer&quot;&gt;Designer&lt;/option&gt;<br>          &lt;option value=&quot;development&quot;&gt;Developer&lt;/option&gt;<br>          &lt;option value=&quot;product&quot;&gt;Product Manager&lt;/option&gt;<br>        &lt;/Select&gt;<br><br>        &lt;Checkbox name=&quot;acceptedTerms&quot;&gt;<br>          I accept the terms and conditions<br>        &lt;/Checkbox&gt;<br><br>        &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;/Form&gt;<br>    &lt;/Formik&gt;<br>  );<br>};</pre><p><strong>Benefits you just gained:</strong></p><ul><li>50% less code in your forms</li><li>Consistent error handling</li><li>Easy to update styling globally</li><li>Better maintainability</li></ul><h3>Best Practices</h3><p>Understanding these best practices will help you write cleaner, more maintainable Formik code.</p><h4>1. Use Validation Schema Instead of the Validate Function</h4><p>Validation schemas are declarative, easier to read, and more maintainable than imperative validation functions.</p><p>✅ Good — Using Yup Schema:</p><pre>// Declarative and easy to understand<br>const schema = Yup.object().shape({<br>  email: Yup.string().email().required(),<br>  password: Yup.string().min(8).required(),<br>});<br><br>&lt;Formik validationSchema={schema}&gt;<br>  {/* form */}<br>&lt;/Formik&gt;</pre><p><strong>Why this is better:</strong></p><ul><li>Clear and readable</li><li>Type-safe</li><li>Better error messages</li><li>Easier to test</li><li>Can be reused</li></ul><p><strong>Avoid — Manual Validation</strong>:</p><pre>// Imperative and harder to maintain<br>&lt;Formik validate={values =&gt; { <br>  const errors = {};<br>  // Manual validation logic...<br>  return errors;<br>}}&gt;</pre><h4>2. Reset Form After Successful Submission</h4><p>Clear the form after successful submission for better UX.</p><p><strong>When to reset:</strong></p><ul><li>Contact forms</li><li>Comment forms</li><li>Search forms</li><li>Any form that should start fresh after submission</li></ul><pre>&lt;Formik<br>  initialValues={{ email: &#39;&#39;, message: &#39;&#39; }}<br>  onSubmit={(values, { resetForm, setSubmitting }) =&gt; {<br>    submitForm(values).then(() =&gt; {<br>      // Reset to initial values<br>      resetForm();<br>      <br>      // Or reset to custom values<br>      // resetForm({ values: { email: &#39;&#39;, message: &#39;Thank you!&#39; } });<br><br>      // Reset with new values<br>      // resetForm({ values: { email: &#39;&#39;, message: &#39;&#39; } });<br><br>      // Reset and clear errors<br>      // resetForm({ errors: {} });<br>      <br>      setSubmitting(false);<br>    });<br>  }}<br>&gt;<br>  {/* form */}<br>&lt;/Formik&gt;</pre><h4>3. Handle Server Errors Gracefully</h4><p>API errors need to be displayed to users in a helpful way.</p><p><strong>Types of server errors:</strong></p><ul><li>Field-specific errors (email already exists)</li><li>Form-level errors (authentication failed)</li><li>Network errors</li><li>Validation errors from the backend</li></ul><pre>&lt;Formik<br>  onSubmit={async (values, { setErrors, setStatus, setSubmitting }) =&gt; {<br>    try {<br>      await submitForm(values);<br>      setStatus({ success: true });<br>    } catch (error) {<br>      // Handle field-specific errors<br>      if (error.response?.data?.errors) {<br>        // Server returns: { errors: { email: &quot;Already taken&quot;, username: &quot;Invalid&quot; } }<br>        setErrors(error.response.data.errors);<br>      }<br>      <br>      // Handle general form errors<br>      if (error.response?.data?.message) {<br>        setStatus({ error: error.response.data.message });<br>      }<br>      <br>      // Handle network errors<br>      if (!error.response) {<br>        setStatus({ error: &#39;Network error. Please try again.&#39; });<br>      }<br>    } finally {<br>      setSubmitting(false);<br>    }<br>  }}<br>&gt;<br>  {({ status }) =&gt; (<br>    &lt;Form&gt;<br>      {/* Display general error */}<br>      {status?.error &amp;&amp; (<br>        &lt;div className=&quot;alert-error&quot;&gt;{status.error}&lt;/div&gt;<br>      )}<br>      <br>      {/* Display success */}<br>      {status?.success &amp;&amp; (<br>        &lt;div className=&quot;alert-success&quot;&gt;Form submitted!&lt;/div&gt;<br>      )}<br>      <br>      {/* Field errors automatically displayed by ErrorMessage */}<br>      &lt;Field name=&quot;email&quot; /&gt;<br>      &lt;ErrorMessage name=&quot;email&quot; component=&quot;div&quot; /&gt;<br>      <br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/Form&gt;<br>  )}<br>&lt;/Formik&gt;</pre><p><strong>Error handling flow:</strong></p><ol><li>Try to submit the form</li><li>If the server returns field errors → use setErrors()</li><li>If the server returns a general error → use setStatus()</li><li>Display errors to the user</li><li>User fixes and retries</li></ol><h3>Common Patterns &amp; Solutions</h3><h4>Pattern 1: Dependent Fields</h4><p>One field’s options depend on another field’s value.</p><p><strong>Real-world examples:</strong></p><ul><li>Country → States</li><li>Category → Subcategories</li><li>Make → Model (cars)</li></ul><p><strong>How it works:</strong></p><ul><li>Watch the parent field value</li><li>Conditionally render child field</li><li>Reset child value when parent changes</li></ul><pre>const DependentFieldsForm = () =&gt; {<br>  return (<br>    &lt;Formik<br>      initialValues={{ country: &#39;&#39;, state: &#39;&#39; }}<br>      onSubmit={values =&gt; console.log(values)}<br>    &gt;<br>      {({ values, setFieldValue }) =&gt; (<br>          &lt;Field <br>            as=&quot;select&quot; <br>            name=&quot;country&quot;<br>            onChange={(e) =&gt; {<br>              setFieldValue(&#39;country&#39;, e.target.value);<br>              setFieldValue(&#39;state&#39;, &#39;&#39;); // Reset dependent field<br>            }}<br>          &gt;<br>            &lt;option value=&quot;&quot;&gt;Select Country&lt;/option&gt;<br>            &lt;option value=&quot;usa&quot;&gt;USA&lt;/option&gt;<br>            &lt;option value=&quot;canada&quot;&gt;Canada&lt;/option&gt;<br>          &lt;/Field&gt;<br><br>          {/* Child field - only shows when country is selected */}<br>          {values.country === &#39;usa&#39; &amp;&amp; (<br>            &lt;Field as=&quot;select&quot; name=&quot;state&quot;&gt;<br>              &lt;option value=&quot;&quot;&gt;Select State&lt;/option&gt;<br>              &lt;option value=&quot;ny&quot;&gt;New York&lt;/option&gt;<br>              &lt;option value=&quot;ca&quot;&gt;California&lt;/option&gt;<br>              &lt;option value=&quot;tx&quot;&gt;Texas&lt;/option&gt;<br>            &lt;/Field&gt;<br>          )}<br><br>          {values.country === &#39;canada&#39; &amp;&amp; (<br>            &lt;Field as=&quot;select&quot; name=&quot;state&quot;&gt;<br>              &lt;option value=&quot;&quot;&gt;Select Province&lt;/option&gt;<br>              &lt;option value=&quot;on&quot;&gt;Ontario&lt;/option&gt;<br>              &lt;option value=&quot;qc&quot;&gt;Quebec&lt;/option&gt;<br>            &lt;/Field&gt;<br>          )}<br><br>          &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>        &lt;/Form&gt;<br>      )}<br>    &lt;/Formik&gt;<br>  );<br>};</pre><h4>Pattern 2: Conditional Validation</h4><p>Validation rules that change based on other field values.</p><p><strong>Use cases:</strong></p><ul><li>Business vs Personal account (different required fields)</li><li>Shipping address (required if “ship to different address” is checked)</li><li>Payment method (different fields for credit card vs PayPal)</li></ul><pre><br>const ConditionalValidationSchema = Yup.object().shape({<br>  accountType: Yup.string().required(),<br>  <br>  // businessName is ONLY required if accountType is &#39;business&#39;<br>  businessName: Yup.string().when(&#39;accountType&#39;, {<br>    is: &#39;business&#39;, // When accountType equals &#39;business&#39;<br>    then: Yup.string().required(&#39;Business name is required for business accounts&#39;),<br>    otherwise: Yup.string(), // Not required for personal accounts<br>  }),<br>  <br>  // More complex conditions<br>  taxId: Yup.string().when(&#39;accountType&#39;, {<br>    is: (value) =&gt; value === &#39;business&#39; || value === &#39;nonprofit&#39;,<br>    then: Yup.string().required(&#39;Tax ID required&#39;),<br>    otherwise: Yup.string(),<br>  }),<br>});<br><br>// Usage<br>&lt;Formik validationSchema={ConditionalValidationSchema}&gt;<br>  &lt;Form&gt;<br>    &lt;Field as=&quot;select&quot; name=&quot;accountType&quot;&gt;<br>      &lt;option value=&quot;personal&quot;&gt;Personal&lt;/option&gt;<br>      &lt;option value=&quot;business&quot;&gt;Business&lt;/option&gt;<br>    &lt;/Field&gt;<br>    <br>    {/* This field is only validated if accountType is &#39;business&#39; */}<br>    &lt;Field name=&quot;businessName&quot; /&gt;<br>    &lt;ErrorMessage name=&quot;businessName&quot; /&gt;<br>  &lt;/Form&gt;<br>&lt;/Formik&gt;</pre><h3>Using Other Validation Libraries (Zod, Joi, Vest)</h3><h4>The Challenge</h4><p>Formik’s validationSchema prop only works with Yup out of the box. If you prefer Zod, Joi, or Superstruct, you&#39;re out of luck... or are you?</p><h4>Solution: formik-validation-adaptors</h4><p>I created <a href="https://github.com/kom50/formik-validation-adaptors">formik-validation-adaptors</a> to bridge this gap. It’s a lightweight package that lets you use any popular validation library with Formik.</p><p>Supported validators:</p><ul><li>✅ Zod</li><li>✅ Joi</li><li>✅ Vest</li></ul><h4>Why Use This Package?</h4><p>✅ Use any validator — Not locked into Yup<br>✅ Same Formik API — Familiar pattern<br>✅ TypeScript support — Full type safety <br>✅ Easy switching — Try different validators</p><h4>Resources</h4><ul><li>📦 NPM: <a href="https://www.npmjs.com/package/formik-validation-adaptors">formik-validation-adaptors</a></li><li>💻 GitHub: <a href="https://github.com/kom50/formik-validation-adaptors">kom50/formik-validation-adaptors</a></li><li>⭐ Star the repo if you find it useful!</li></ul><h4>Useful Links:</h4><ul><li><a href="https://formik.org/">Official Formik Documentation</a></li><li><a href="https://github.com/jquense/yup">Yup Documentation</a></li></ul><h3>Conclusion</h3><p>Formik is an incredibly powerful library that simplifies form management in React.</p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6107274102e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TanStack Query: The Ultimate Complete Guide with All Best Features]]></title>
            <link>https://medium.com/@kom50/tanstack-query-the-ultimate-complete-guide-with-all-best-features-bd01806dc86c?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd01806dc86c</guid>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Sun, 07 Dec 2025 15:07:48 GMT</pubDate>
            <atom:updated>2025-12-07T15:07:48.646Z</atom:updated>
            <content:encoded><![CDATA[<h4>A deep-dive into React’s most powerful data-syncing library — caching, mutations, infinite queries, optimistic updates, prefetching, and everything in between.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f22QRRgxlGg231D90yf7uw.png" /><figcaption>TanStack Query</figcaption></figure><h4>Why Your React App Needs TanStack Query (And You Didn’t Even Know It)</h4><p>Have you ever written code like this in React?</p><pre>const [data, setData] = useState(null);<br>const [loading, setLoading] = useState(true);<br>const [error, setError] = useState(null);<br><br>useEffect(() =&gt; {<br>  fetch(&#39;/api/users&#39;)<br>    .then(res =&gt; res.json())<br>    .then(data =&gt; {<br>      setData(data);<br>      setLoading(false);<br>    })<br>    .catch(err =&gt; {<br>      setError(err);<br>      setLoading(false);<br>    });<br>}, []);</pre><p>If yes, you’re not alone. But there’s a better way. <strong>TanStack Query</strong> (formerly <strong>React Query</strong>) makes data fetching feel like magic.</p><h3>What is TanStack Query?</h3><p>Think of <strong>TanStack Query</strong> as your personal assistant for handling server data. It manages:</p><ul><li>Data fetching</li><li>Caching</li><li>Loading states</li><li>Error handling</li><li>Refetching</li><li>Infinite scrolling</li><li>Prefetching</li><li>Optimistic updates</li><li>And much more!</li></ul><p>All with minimal code.</p><h3>The Problem TanStack Query Solves</h3><p><strong>Without TanStack Query</strong></p><pre>function UserProfile() {<br>  const [user, setUser] = useState(null);<br>  const [loading, setLoading] = useState(true);<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    setLoading(true);<br>    fetch(`/api/user/1`)<br>      .then(res =&gt; res.json())<br>      .then(data =&gt; {<br>        setUser(data);<br>        setLoading(false);<br>      })<br>      .catch(err =&gt; {<br>        setError(err);<br>        setLoading(false);<br>      });<br>  }, []);<br><br>  if (loading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br>  <br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>}</pre><p><strong>Problems</strong>:</p><ul><li>Boilerplate code everywhere</li><li>No caching (refetch on every mount)</li><li>Manual state management</li><li>No background updates</li></ul><p><strong>With TanStack Query</strong></p><pre>function UserProfile() {<br>  const { data, isLoading, error } = useQuery({<br>    queryKey: [&#39;user&#39;, 1],<br>    queryFn: () =&gt; fetch(&#39;/api/user/1&#39;).then(res =&gt; res.json())<br>  });<br><br>  if (isLoading) return &lt;div&gt;Loading...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br>  <br>  return &lt;div&gt;{data.name}&lt;/div&gt;;<br>}</pre><p><strong>Benefits</strong>:</p><ul><li>Less code</li><li>Automatic caching</li><li>Smart refetching</li><li>Built-in loading/error states</li></ul><h3>Getting Started</h3><p><strong>Installation</strong></p><pre>npm install @tanstack/react-query<br># or<br>yarn add @tanstack/react-query</pre><p><strong>Setup</strong></p><p>Wrap your app with QueryClientProvider:</p><pre>// App.jsx<br>import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;;<br>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;;<br><br>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      staleTime: 1000 * 60 * 5, // 5 minutes<br>      cacheTime: 1000 * 60 * 10, // 10 minutes<br>      refetchOnWindowFocus: true,<br>      refetchOnReconnect: true,<br>      retry: 3,<br>    },<br>  },<br>});<br><br>function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;YourApp /&gt;<br>      &lt;ReactQueryDevtools initialIsOpen={false} /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><h3>Feature #1: Basic Queries (Data Fetching)</h3><pre>import { useQuery } from &#39;@tanstack/react-query&#39;;<br><br>function Posts() {<br>  const { data, isLoading, error, isFetching } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: async () =&gt; {<br>      const response = await fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;);<br>      if (!response.ok) throw new Error(&#39;Network error&#39;);<br>      return response.json();<br>    }<br>  });<br><br> // rest of code<br>}</pre><h3>Feature #2: Query with Parameters</h3><pre>function Post({ postId }) {<br>  const { data, isLoading } = useQuery({<br>    queryKey: [&#39;post&#39;, postId], // ⭐ Unique key per post<br>    queryFn: async () =&gt; {<br>      const res = await fetch(`https://api.example.com/posts/${postId}`);<br>      return res.json();<br>    },<br>    enabled: !!postId, // Only run if postId exists<br>  });<br><br>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  <br>  return &lt;h1&gt;{data.title}&lt;/h1&gt;;<br>}</pre><p><strong>Key States:</strong></p><ul><li>isLoading: Initial load (no cached data)</li><li>isFetching: Any fetch (including background refetch)</li><li>isError: Query failed</li><li>isSuccess: Query succeeded</li></ul><h3>Feature #3: Mutations (Create, Update, Delete)</h3><pre>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br>function CreatePost() {<br>  const queryClient = useQueryClient();<br><br>  const mutation = useMutation({<br>    mutationFn: async (newPost) =&gt; {<br>      const response = await fetch(&#39;https://api.example.com/posts&#39;, {<br>        method: &#39;POST&#39;,<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>        body: JSON.stringify(newPost)<br>      });<br>      return response.json();<br>    },<br>    onMutate: async (newPost) =&gt; {<br>      // Called before mutation function<br>      console.log(&#39;Starting mutation...&#39;, newPost);<br>    },<br>    onSuccess: (data, variables, context) =&gt; {<br>      // Invalidate and refetch<br>      queryClient.invalidateQueries({ queryKey: [&#39;posts&#39;] });<br>      console.log(&#39;Success!&#39;, data);<br>    },<br>    onError: (error, variables, context) =&gt; {<br>      console.error(&#39;Error:&#39;, error);<br>    },<br>    onSettled: (data, error, variables, context) =&gt; {<br>      // Called on success or error<br>      console.log(&#39;Mutation finished&#39;);<br>    }<br>  });<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    mutation.mutate({<br>      title: &#39;New Post&#39;,<br>      body: &#39;Content here&#39;<br>    });<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;button type=&quot;submit&quot; disabled={mutation.isPending}&gt;<br>        {mutation.isPending ? &#39;Creating...&#39; : &#39;Create Post&#39;}<br>      &lt;/button&gt;<br>      {mutation.isError &amp;&amp; &lt;p&gt;Error: {mutation.error.message}&lt;/p&gt;}<br>      {mutation.isSuccess &amp;&amp; &lt;p&gt;Post created! ✅&lt;/p&gt;}<br>    &lt;/form&gt;<br>  );<br>}</pre><h3>Feature #4: Optimistic Updates (Instant UI)</h3><p>Make your UI feel lightning-fast!</p><pre>function UpdateTodo() {<br>  const queryClient = useQueryClient();<br><br>  const updateMutation = useMutation({<br>    mutationFn: async (updatedTodo) =&gt; {<br>      const res = await fetch(`/api/todos/${updatedTodo.id}`, {<br>        method: &#39;PUT&#39;,<br>        body: JSON.stringify(updatedTodo),<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; }<br>      });<br>      return res.json();<br>    },<br>    <br>    // ⭐ Optimistic update<br>    onMutate: async (updatedTodo) =&gt; {<br>      // Cancel outgoing refetches<br>      await queryClient.cancelQueries({ queryKey: [&#39;todos&#39;] });<br><br>      // Snapshot previous value<br>      const previousTodos = queryClient.getQueryData([&#39;todos&#39;]);<br><br>      // Optimistically update cache<br>      queryClient.setQueryData([&#39;todos&#39;], (old) =&gt;<br>        old.map(todo =&gt; <br>          todo.id === updatedTodo.id ? updatedTodo : todo<br>        )<br>      );<br><br>      // Return context with snapshot<br>      return { previousTodos };<br>    },<br>    <br>    onError: (err, updatedTodo, context) =&gt; {<br>      // Rollback to previous value on error<br>      queryClient.setQueryData([&#39;todos&#39;], context.previousTodos);<br>    },<br>    <br>    onSettled: () =&gt; {<br>      // Refetch to ensure sync<br>      queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] });<br>    }<br>  });<br><br>  return (<br>    &lt;button onClick={() =&gt; updateMutation.mutate({ id: 1, completed: true })}&gt;<br>      Mark Complete<br>    &lt;/button&gt;<br>  );<br>}</pre><h3>Feature #5: Infinite Queries (Infinite Scrolling)</h3><p>Perfect for feeds, lists, and pagination!</p><pre>import { useInfiniteQuery } from &#39;@tanstack/react-query&#39;;<br><br>function InfinitePosts() {<br>  const {<br>    data,<br>    fetchNextPage,<br>    hasNextPage,<br>    isFetchingNextPage,<br>    isLoading,<br>  } = useInfiniteQuery({<br>    queryKey: [&#39;posts&#39;, &#39;infinite&#39;],<br>    queryFn: async ({ pageParam = 1 }) =&gt; {<br>      const res = await fetch(<br>        `https://api.example.com/posts?page=${pageParam}&amp;limit=10`<br>      );<br>      return res.json();<br>    },<br>    getNextPageParam: (lastPage, allPages) =&gt; {<br>      // Return next page number or undefined if no more pages<br>      return lastPage.hasMore ? allPages.length + 1 : undefined;<br>    },<br>    initialPageParam: 1,<br>  });<br><br>  if (isLoading) return &lt;p&gt;Loading...&lt;/p&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      {data.pages.map((page, i) =&gt; (<br>        &lt;div key={i}&gt;<br>          {page.posts.map(post =&gt; (<br>            &lt;div key={post.id}&gt;{post.title}&lt;/div&gt;<br>          ))}<br>        &lt;/div&gt;<br>      ))}<br>      <br>      &lt;button<br>        onClick={() =&gt; fetchNextPage()}<br>        disabled={!hasNextPage || isFetchingNextPage}<br>      &gt;<br>        {isFetchingNextPage<br>          ? &#39;Loading more...&#39;<br>          : hasNextPage<br>          ? &#39;Load More&#39;<br>          : &#39;No more posts&#39;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>With Intersection Observer (Auto-load on scroll)</strong></p><pre>function InfiniteScrollPosts() {<br>  const observerTarget = useRef(null);<br><br>  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = <br>    useInfiniteQuery({<br>      queryKey: [&#39;posts&#39;, &#39;infinite&#39;],<br>      queryFn: fetchPosts,<br>      getNextPageParam: (lastPage) =&gt; lastPage.nextCursor,<br>      initialPageParam: 1,<br>    });<br><br>  useEffect(() =&gt; {<br>    const observer = new IntersectionObserver(<br>      entries =&gt; {<br>        if (entries[0].isIntersecting &amp;&amp; hasNextPage) {<br>          fetchNextPage();<br>        }<br>      },<br>      { threshold: 1 }<br>    );<br><br>    if (observerTarget.current) {<br>      observer.observe(observerTarget.current);<br>    }<br><br>    return () =&gt; observer.disconnect();<br>  }, [fetchNextPage, hasNextPage]);<br><br>  return (<br>    &lt;div&gt;<br>      {data?.pages.map((page, i) =&gt; (<br>        &lt;div key={i}&gt;<br>          {page.posts.map(post =&gt; (<br>            &lt;PostCard key={post.id} post={post} /&gt;<br>          ))}<br>        &lt;/div&gt;<br>      ))}<br>      &lt;div ref={observerTarget} /&gt;<br>      {isFetchingNextPage &amp;&amp; &lt;p&gt;Loading more...&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Feature #6: Prefetching (Lightning Fast Navigation)</h3><p>Load data before the user needs it!</p><pre>import { useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br>function PostList() {<br>  const queryClient = useQueryClient();<br><br>  const { data: posts } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts<br>  });<br><br>  const handleMouseEnter = (postId) =&gt; {<br>    // Prefetch post details on hover<br>    queryClient.prefetchQuery({<br>      queryKey: [&#39;post&#39;, postId],<br>      queryFn: () =&gt; fetchPost(postId),<br>      staleTime: 1000 * 60 * 5, // 5 minutes<br>    });<br>  };<br><br>  return (<br>    &lt;ul&gt;<br>      {posts.map(post =&gt; (<br>        &lt;li <br>          key={post.id}<br>          onMouseEnter={() =&gt; handleMouseEnter(post.id)}<br>        &gt;<br>          &lt;Link to={`/posts/${post.id}`}&gt;{post.title}&lt;/Link&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p><strong>Prefetch on Route</strong></p><pre>function ProductsPage() {<br>  const queryClient = useQueryClient();<br><br>  useEffect(() =&gt; {<br>    // Prefetch next page<br>    queryClient.prefetchQuery({<br>      queryKey: [&#39;products&#39;, &#39;page-2&#39;],<br>      queryFn: () =&gt; fetchProducts(2)<br>    });<br>  }, [queryClient]);<br><br>  return &lt;ProductList /&gt;;<br>}</pre><h3>Feature #7: Parallel Queries</h3><p>Fetch multiple queries simultaneously!</p><pre>function Dashboard() {<br>  const userQuery = useQuery({<br>    queryKey: [&#39;user&#39;],<br>    queryFn: fetchUser<br>  });<br><br>  const postsQuery = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts<br>  });<br><br>  const analyticsQuery = useQuery({<br>    queryKey: [&#39;analytics&#39;],<br>    queryFn: fetchAnalytics<br>  });<br><br>  if (userQuery.isLoading || postsQuery.isLoading || analyticsQuery.isLoading) {<br>    return &lt;div&gt;Loading...&lt;/div&gt;;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome {userQuery.data.name}&lt;/h1&gt;<br>      &lt;Posts posts={postsQuery.data} /&gt;<br>      &lt;Analytics data={analyticsQuery.data} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Using useQueries (Dynamic Parallel Queries)</strong></p><pre>function UserPosts({ userIds }) {<br>  const userQueries = useQueries({<br>    queries: userIds.map(id =&gt; ({<br>      queryKey: [&#39;user&#39;, id],<br>      queryFn: () =&gt; fetchUser(id),<br>      staleTime: 1000 * 60 * 5,<br>    }))<br>  });<br><br>  const allLoading = userQueries.some(query =&gt; query.isLoading);<br>  const allData = userQueries.map(query =&gt; query.data);<br><br>  if (allLoading) return &lt;div&gt;Loading users...&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      {allData.map(user =&gt; (<br>        &lt;UserCard key={user.id} user={user} /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Feature #8: Dependent Queries</h3><p>Run queries based on other query results!</p><pre>function UserProfile({ userId }) {<br>  // First: Fetch user<br>  const { data: user } = useQuery({<br>    queryKey: [&#39;user&#39;, userId],<br>    queryFn: () =&gt; fetchUser(userId)<br>  });<br><br>  // Second: Fetch user&#39;s posts (depends on user)<br>  const { data: posts } = useQuery({<br>    queryKey: [&#39;posts&#39;, user?.id],<br>    queryFn: () =&gt; fetchUserPosts(user.id),<br>    enabled: !!user, // ⭐ Only run when user exists<br>  });<br><br>  // Third: Fetch post comments (depends on posts)<br>  const { data: comments } = useQuery({<br>    queryKey: [&#39;comments&#39;, posts?.[0]?.id],<br>    queryFn: () =&gt; fetchComments(posts[0].id),<br>    enabled: !!posts &amp;&amp; posts.length &gt; 0,<br>  });<br><br>  return &lt;div&gt;...&lt;/div&gt;;<br>}</pre><h3>Feature #9: Initial Data &amp; Placeholder Data</h3><p><strong>Initial Data (from cache or props)</strong></p><pre>function Post({ postId, initialData }) {<br>  const { data } = useQuery({<br>    queryKey: [&#39;post&#39;, postId],<br>    queryFn: () =&gt; fetchPost(postId),<br>    initialData: initialData, // Use this until real data loads<br>  });<br><br>  return &lt;div&gt;...&lt;/div&gt;;<br>}</pre><p><strong>Placeholder Data (temporary fallback)</strong></p><pre>function Posts() {<br>  const { data, isPlaceholderData } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts,<br>    placeholderData: [<br>      { id: 1, title: &#39;Loading...&#39; },<br>      { id: 2, title: &#39;Loading...&#39; },<br>    ]<br>  });<br><br>  return (<br>    &lt;div style={{ opacity: isPlaceholderData ? 0.5 : 1 }}&gt;<br>      {data.map(post =&gt; &lt;Post key={post.id} {...post} /&gt;)}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Initialize from Another Query</strong></p><pre>function Post({ postId }) {<br>  const queryClient = useQueryClient();<br><br>  const { data } = useQuery({<br>    queryKey: [&#39;post&#39;, postId],<br>    queryFn: () =&gt; fetchPost(postId),<br>    initialData: () =&gt; {<br>      // Get from posts list cache<br>      return queryClient<br>        .getQueryData([&#39;posts&#39;])<br>        ?.find(post =&gt; post.id === postId);<br>    },<br>    initialDataUpdatedAt: () =&gt; {<br>      return queryClient.getQueryState([&#39;posts&#39;])?.dataUpdatedAt;<br>    }<br>  });<br><br>  return &lt;div&gt;{data?.title}&lt;/div&gt;;<br>}</pre><h3>Feature #10: Polling / Auto Refetching</h3><p>Keep data fresh automatically!</p><pre>// Refetch every 5 seconds<br>function LivePrices() {<br>  const { data } = useQuery({<br>    queryKey: [&#39;prices&#39;],<br>    queryFn: fetchPrices,<br>    refetchInterval: 5000, // Refetch every 5 seconds<br>  });<br><br>  return &lt;div&gt;BTC: ${data.btc}&lt;/div&gt;;<br>}</pre><p><strong>Smart Polling (only when tab is active)</strong></p><pre>function LiveData() {<br>  const { data } = useQuery({<br>    queryKey: [&#39;liveData&#39;],<br>    queryFn: fetchLiveData,<br>    refetchInterval: 3000,<br>    refetchIntervalInBackground: false, // ⭐ Pause when tab inactive<br>  });<br><br>  return &lt;div&gt;{data.value}&lt;/div&gt;;<br>}</pre><p><strong>Conditional Polling</strong></p><pre>function OrderStatus({ orderId }) {<br>  const { data } = useQuery({<br>    queryKey: [&#39;order&#39;, orderId],<br>    queryFn: () =&gt; fetchOrder(orderId),<br>    refetchInterval: (data) =&gt; {<br>      // Stop polling when order is complete<br>      return data?.status === &#39;completed&#39; ? false : 2000;<br>    }<br>  });<br><br>  return &lt;div&gt;Status: {data.status}&lt;/div&gt;;<br>}</pre><h3>Feature #11: Window Focus Refetching</h3><p>Auto-refetch when user returns to tab!</p><pre>function Posts() {<br>  const { data } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts,<br>    refetchOnWindowFocus: true, // ⭐ Default is true<br>  });<br><br>  return &lt;PostList posts={data} /&gt;;<br>}</pre><p><strong>Disable Globally</strong></p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      refetchOnWindowFocus: false, // Disable for all queries<br>    },<br>  },<br>});</pre><h3>Feature #12: Retry Logic</h3><p>Smart retry with exponential backoff!</p><pre>function Posts() {<br>  const { data } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts,<br>    retry: 3, // Retry 3 times on failure<br>    retryDelay: attemptIndex =&gt; Math.min(1000 * 2 ** attemptIndex, 30000),<br>    // 1st retry: 1s, 2nd: 2s, 3rd: 4s, max: 30s<br>  });<br><br> // Conditional Retry<br> const { data } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts,<br>    retry: (failureCount, error) =&gt; {<br>      // Don&#39;t retry on 404<br>      if (error.status === 404) return false;<br>      // Retry up to 3 times for other errors<br>      return failureCount &lt; 3;<br>    }<br>  });<br><br>  return &lt;PostList posts={data} /&gt;;<br>}</pre><h3>Feature #13: Query Cancellation</h3><p>Cancel queries with AbortController!</p><pre>function Search({ query }) {<br>  const { data } = useQuery({<br>    queryKey: [&#39;search&#39;, query],<br>    queryFn: async ({ signal }) =&gt; {<br>      const res = await fetch(`/api/search?q=${query}`, {<br>        signal, // ⭐ Pass abort signal<br>      });<br>      return res.json();<br>    },<br>    enabled: query.length &gt; 2,<br>  });<br><br>  return &lt;SearchResults results={data} /&gt;;<br>}</pre><h3>Feature #14: Suspense Mode</h3><p>Use with React Suspense!</p><pre>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      suspense: true,<br>    },<br>  },<br>});<br><br>function Post({ postId }) {<br>  const { data } = useQuery({<br>    queryKey: [&#39;post&#39;, postId],<br>    queryFn: () =&gt; fetchPost(postId),<br>  });<br><br>  // No loading state needed!<br>  return &lt;h1&gt;{data.title}&lt;/h1&gt;;<br>}<br><br>// Wrap with Suspense<br>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>      &lt;Post postId={1} /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><h3>Feature #15: Select / Transform Data</h3><p>Transform data before it reaches your component!</p><pre>function TodoCount() {<br>  const { data: completedCount } = useQuery({<br>    queryKey: [&#39;todos&#39;],<br>    queryFn: fetchTodos,<br>    select: (data) =&gt; {<br>      // ⭐ Transform data<br>      return data.filter(todo =&gt; todo.completed).length;<br>    }<br>  });<br><br>  return &lt;div&gt;Completed: {completedCount}&lt;/div&gt;;<br>}</pre><h3>Feature #16: Pagination</h3><p>Keep previous data while fetching the new page!</p><pre>function Posts() {<br>  const [page, setPage] = useState(1);<br><br>  const { data, isLoading, isPlaceholderData } = useQuery({<br>    queryKey: [&#39;posts&#39;, page],<br>    queryFn: () =&gt; fetchPosts(page),<br>    placeholderData: keepPreviousData, // ⭐ Keep old data while loading<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div style={{ opacity: isPlaceholderData ? 0.5 : 1 }}&gt;<br>        {data.posts.map(post =&gt; (<br>          &lt;Post key={post.id} {...post} /&gt;<br>        ))}<br>      &lt;/div&gt;<br><br>      &lt;button<br>        onClick={() =&gt; setPage(old =&gt; Math.max(old - 1, 1))}<br>        disabled={page === 1}<br>      &gt;<br>        Previous<br>      &lt;/button&gt;<br><br>      &lt;span&gt;Page {page}&lt;/span&gt;<br><br>      &lt;button<br>        onClick={() =&gt; {<br>          if (!isPlaceholderData &amp;&amp; data.hasMore) {<br>            setPage(old =&gt; old + 1);<br>          }<br>        }}<br>        disabled={isPlaceholderData || !data?.hasMore}<br>      &gt;<br>        Next<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Feature #17: Query Invalidation Strategies</h3><pre>// Invalidate all queries<br>queryClient.invalidateQueries();<br><br>// Exact match<br>queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] });<br><br>// Partial match (all posts)<br>queryClient.invalidateQueries({ queryKey: [&#39;posts&#39;] });<br><br>// This will invalidate:<br>// [&#39;posts&#39;]<br>// [&#39;posts&#39;, 1]<br>// [&#39;posts&#39;, 1, &#39;comments&#39;]<br><br>// Only invalidate exact key<br>queryClient.invalidateQueries({<br>  queryKey: [&#39;posts&#39;, 1],<br>  exact: true<br>});<br><br>// Invalidate with predicate<br>queryClient.invalidateQueries({<br>  predicate: (query) =&gt; {<br>    return query.queryKey[0] === &#39;posts&#39; &amp;&amp; query.queryKey[1] &gt; 10;<br>  }<br>});<br><br>// Refetch Active Queries Only<br>queryClient.invalidateQueries({<br>  queryKey: [&#39;posts&#39;],<br>  refetchType: &#39;active&#39;, // only refetch active queries<br>});</pre><h3>Feature #18: Manual Cache Updates</h3><p>Update cache without refetching!</p><pre>function UpdateCache() {<br>  const queryClient = useQueryClient();<br><br>  const handleUpdate = () =&gt; {<br>    // Set query data manually<br>    queryClient.setQueryData([&#39;todos&#39;], (oldData) =&gt; {<br>      return [...oldData, { id: Date.now(), title: &#39;New Todo&#39; }];<br>    });<br>  };<br><br>  const handlePartialUpdate = () =&gt; {<br>    // Update specific todo<br>    queryClient.setQueryData([&#39;todos&#39;], (oldData) =&gt; {<br>      return oldData.map(todo =&gt;<br>        todo.id === 1 ? { ...todo, completed: true } : todo<br>      );<br>    });<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={handleUpdate}&gt;Add Todo&lt;/button&gt;<br>      &lt;button onClick={handlePartialUpdate}&gt;Update Todo&lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>Feature #19: Persistence (LocalStorage/SessionStorage)</h3><p>Persist cache across page reloads!</p><p><strong>Installation</strong></p><pre>npm install @tanstack/react-query-persist-client</pre><p><strong>Setup with LocalStorage</strong></p><pre>import { QueryClient } from &#39;@tanstack/react-query&#39;;<br>import { PersistQueryClientProvider } from &#39;@tanstack/react-query-persist-client&#39;;<br>import { createSyncStoragePersister } from &#39;@tanstack/query-sync-storage-persister&#39;;<br><br>const queryClient = new QueryClient({<br>  defaultOptions: {<br>    queries: {<br>      cacheTime: 1000 * 60 * 60 * 24, // 24 hours<br>    },<br>  },<br>});<br><br>const persister = createSyncStoragePersister({<br>  storage: window.localStorage,<br>});<br><br>function App() {<br>  return (<br>    &lt;PersistQueryClientProvider<br>      client={queryClient}<br>      persistOptions={{ persister }}<br>    &gt;<br>      &lt;YourApp /&gt;<br>    &lt;/PersistQueryClientProvider&gt;<br>  );<br>}</pre><p><strong>Custom Persister</strong></p><pre>const persister = createSyncStoragePersister({<br>  storage: window.localStorage,<br>  serialize: JSON.stringify,<br>  deserialize: JSON.parse,<br>  key: &#39;MY_APP_CACHE&#39;,<br>});</pre><h3>Feature #20: Error Boundaries Integration</h3><pre>import { useQueryErrorResetBoundary } from &#39;@tanstack/react-query&#39;;<br>import { ErrorBoundary } from &#39;react-error-boundary&#39;;<br><br>function App() {<br>  const { reset } = useQueryErrorResetBoundary();<br><br>  return (<br>    &lt;ErrorBoundary<br>      onReset={reset}<br>      fallbackRender={({ error, resetErrorBoundary }) =&gt; (<br>        &lt;div&gt;<br>          &lt;h1&gt;Error: {error.message}&lt;/h1&gt;<br>          &lt;button onClick={resetErrorBoundary}&gt;Try again&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &gt;<br>      &lt;Posts /&gt;<br>    &lt;/ErrorBoundary&gt;<br>  );<br>}<br><br>function Posts() {<br>  const { data } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts,<br>    useErrorBoundary: true, // Throw errors to boundary<br>  });<br><br>  return &lt;PostList posts={data} /&gt;;<br>}</pre><h3>Feature #21: Network Mode</h3><p>Handle offline scenarios!</p><pre>function OfflineFirst() {<br>  const { data } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts,<br>    networkMode: &#39;offlineFirst&#39;, <br>    // &#39;online&#39; | &#39;always&#39; | &#39;offlineFirst&#39;<br>  });<br><br>  return &lt;PostList posts={data} /&gt;;<br>}</pre><p><strong>Network Modes:</strong></p><ul><li>online: Only run when online (default)</li><li>always: Run even when offline</li><li>offlineFirst: Try cache first, then network</li></ul><h3>Feature #22: Query Status &amp; States</h3><p>Understanding all query states:</p><pre>function Posts() {<br>  const { <br>    data,<br>    error,<br>    status,        // &#39;pending&#39; | &#39;error&#39; | &#39;success&#39;<br>    fetchStatus,   // &#39;fetching&#39; | &#39;paused&#39; | &#39;idle&#39;<br>    isLoading,     // status === &#39;pending&#39;<br>    isPending,     // status === &#39;pending&#39;<br>    isError,       // status === &#39;error&#39;<br>    isSuccess,     // status === &#39;success&#39;<br>    isFetching,    // fetchStatus === &#39;fetching&#39;<br>    isPaused,      // fetchStatus === &#39;paused&#39;<br>    isStale,       // data is stale<br>    isPlaceholderData,<br>    isInitialLoading, // isLoading &amp;&amp; isFetching<br>  } = useQuery({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: fetchPosts<br>  });<br><br>  // Different UI based on states<br>  if (isLoading) return &lt;div&gt;Initial load...&lt;/div&gt;;<br>  if (isError) return &lt;div&gt;Error: {error.message}&lt;/div&gt;;<br><br>  return (<br>    &lt;div&gt;<br>      {isFetching &amp;&amp; &lt;div&gt;Updating...&lt;/div&gt;}<br>      {isStale &amp;&amp; &lt;div&gt;Data is stale&lt;/div&gt;}<br>      {data.map(post =&gt; &lt;Post key={post.id} {...post} /&gt;)}<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>Feature #23: TypeScript Support</h3><p>Full type safety!</p><pre>import { useQuery, useMutation } from &#39;@tanstack/react-query&#39;;<br><br>interface Post {<br>  id: number;<br>  title: string;<br>  body: string;<br>  userId: number;<br>}<br><br>interface NewPost {<br>  title: string;<br>  body: string;<br>  userId: number;<br>}<br><br>// Typed query<br>function Posts() {<br>  const { data, isLoading } = useQuery&lt;Post[], Error&gt;({<br>    queryKey: [&#39;posts&#39;],<br>    queryFn: async () =&gt; {<br>      const res = await fetch(&#39;https://api.example.com/posts&#39;);<br>      if (!res.ok) throw new Error(&#39;Failed to fetch&#39;);<br>      return res.json();<br>    }<br>  });<br><br>  if (isLoading) return &lt;div&gt;Loading...&lt;/div&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data?.map(post =&gt; (<br>        &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>// Typed mutation<br>function CreatePost() {<br>  const mutation = useMutation&lt;Post, Error, NewPost&gt;({<br>    mutationFn: async (newPost) =&gt; {<br>      const res = await fetch(&#39;https://api.example.com/posts&#39;, {<br>        method: &#39;POST&#39;,<br>        body: JSON.stringify(newPost),<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      });<br>      return res.json();<br>    }<br>  });<br><br>  const handleSubmit = () =&gt; {<br>    mutation.mutate({<br>      title: &#39;Hello&#39;,<br>      body: &#39;World&#39;,<br>      userId: 1<br>    });<br>  };<br><br>  return &lt;button onClick={handleSubmit}&gt;Create&lt;/button&gt;;<br>}</pre><h3>Feature #24: Custom Hooks Pattern</h3><p>Create reusable query hooks!</p><pre>// hooks/useTodos.js<br>export function useTodos() {<br>  return useQuery({<br>    queryKey: [&#39;todos&#39;],<br>    queryFn: async () =&gt; {<br>      const res = await fetch(&#39;/api/todos&#39;);<br>      if (!res.ok) throw new Error(&#39;Failed to fetch&#39;);<br>      return res.json();<br>    },<br>    staleTime: 1000 * 60, // 1 minute<br>  });<br>}<br><br>export function useTodo(id) {<br>  return useQuery({<br>    queryKey: [&#39;todo&#39;, id],<br>    queryFn: async () =&gt; {<br>      const res = await fetch(`/api/todos/${id}`);<br>      if (!res.ok) throw new Error(&#39;Failed to fetch&#39;);<br>      return res.json();<br>    },<br>    enabled: !!id,<br>  });<br>}<br><br>export function useAddTodo() {<br>  const queryClient = useQueryClient();<br><br>  return useMutation({<br>    mutationFn: async (newTodo) =&gt; {<br>      const res = await fetch(&#39;/api/todos&#39;, {<br>        method: &#39;POST&#39;,<br>        body: JSON.stringify(newTodo),<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      });<br>      return res.json();<br>    },<br>    onSuccess: () =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] });<br>    },<br>  });<br>}<br><br>export function useUpdateTodo() {<br>  const queryClient = useQueryClient();<br><br>  return useMutation({<br>    mutationFn: async ({ id, ...updates }) =&gt; {<br>      const res = await fetch(`/api/todos/${id}`, {<br>        method: &#39;PUT&#39;,<br>        body: JSON.stringify(updates),<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>      });<br>      return res.json();<br>    },<br>    onMutate: async (updatedTodo) =&gt; {<br>      await queryClient.cancelQueries({ queryKey: [&#39;todos&#39;] });<br>      const previous = queryClient.getQueryData([&#39;todos&#39;]);<br><br>      queryClient.setQueryData([&#39;todos&#39;], (old) =&gt;<br>        old.map(todo =&gt;<br>          todo.id === updatedTodo.id ? { ...todo, ...updatedTodo } : todo<br>        )<br>      );<br><br>      return { previous };<br>    },<br>    onError: (err, variables, context) =&gt; {<br>      queryClient.setQueryData([&#39;todos&#39;], context.previous);<br>    },<br>    onSettled: () =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] });<br>    },<br>  });<br>}<br><br>export function useDeleteTodo() {<br>  const queryClient = useQueryClient();<br><br>  return useMutation({<br>    mutationFn: async (id) =&gt; {<br>      await fetch(`/api/todos/${id}`, { method: &#39;DELETE&#39; });<br>    },<br>    onSuccess: () =&gt; {<br>      queryClient.invalidateQueries({ queryKey: [&#39;todos&#39;] });<br>    },<br>  });<br>}</pre><h3>Feature #25: Advanced DevTools</h3><p>Visualize everything happening in your app!</p><pre>import { ReactQueryDevtools } from &#39;@tanstack/react-query-devtools&#39;;<br><br>function App() {<br>  return (<br>    &lt;QueryClientProvider client={queryClient}&gt;<br>      &lt;YourApp /&gt;<br>      &lt;ReactQueryDevtools <br>        initialIsOpen={false}<br>        position=&quot;bottom-right&quot;<br>        toggleButtonProps={{<br>          style: {<br>            marginLeft: &#39;5.5em&#39;,<br>            transform: `scale(.7)`,<br>            transformOrigin: &#39;bottom right&#39;,<br>          }<br>        }}<br>      /&gt;<br>    &lt;/QueryClientProvider&gt;<br>  );<br>}</pre><p><strong>DevTools Features:</strong></p><ul><li>View all queries and mutations</li><li>See query states (fresh, stale, fetching)</li><li>Inspect query data</li><li>Manually trigger refetch</li><li>Remove queries</li><li>Monitor cache size</li></ul><h3>Performance Tips &amp; Best Practices</h3><h4>1. Structure Query Keys Properly</h4><pre>// ❌ Bad<br>[&#39;posts&#39;]<br>[&#39;user&#39;]<br><br>// ✅ Good - hierarchical<br>[&#39;posts&#39;, &#39;list&#39;]<br>[&#39;posts&#39;, &#39;detail&#39;, id]<br>[&#39;user&#39;, &#39;profile&#39;]<br>[&#39;user&#39;, &#39;settings&#39;]</pre><h4>2. Use Query Key Factories</h4><pre>// queryKeys.js<br>export const queryKeys = {<br>  posts: {<br>    all: [&#39;posts&#39;],<br>    lists: () =&gt; [...queryKeys.posts.all, &#39;list&#39;],<br>    list: (filters) =&gt; [...queryKeys.posts.lists(), filters],<br>    details: () =&gt; [...queryKeys.posts.all, &#39;detail&#39;],<br>    detail: (id) =&gt; [...queryKeys.posts.details(), id],<br>  },<br>  users: {<br>    all: [&#39;users&#39;],<br>    detail: (id) =&gt; [...queryKeys.users.all, id],<br>  }<br>};<br><br>// Usage<br>useQuery({<br>  queryKey: queryKeys.posts.detail(postId),<br>  queryFn: () =&gt; fetchPost(postId)<br>});</pre><h4>3. Set Appropriate Stale Times</h4><pre>// Data that changes frequently<br>useQuery({<br>  queryKey: [&#39;stock-price&#39;],<br>  queryFn: fetchPrice,<br>  staleTime: 1000, // 1 second<br>});<br><br>// Data that rarely changes<br>useQuery({<br>  queryKey: [&#39;user-settings&#39;],<br>  queryFn: fetchSettings,<br>  staleTime: 1000 * 60 * 60, // 1 hour<br>});</pre><h4>4. Prefetch Smart</h4><pre>function ProductList() {<br>  const queryClient = useQueryClient();<br><br>  const { data: products } = useQuery({<br>    queryKey: [&#39;products&#39;],<br>    queryFn: fetchProducts<br>  });<br><br>  // Prefetch first 3 products<br>  useEffect(() =&gt; {<br>    products?.slice(0, 3).forEach(product =&gt; {<br>      queryClient.prefetchQuery({<br>        queryKey: [&#39;product&#39;, product.id],<br>        queryFn: () =&gt; fetchProduct(product.id),<br>      });<br>    });<br>  }, [products, queryClient]);<br><br>  return &lt;ProductGrid products={products} /&gt;;<br>}</pre><p><strong>Resources:</strong></p><ul><li><a href="https://tanstack.com/query/latest">Official Docs</a></li><li><a href="https://tanstack.com/query/latest/docs/react/devtools">DevTools</a></li></ul><h3>Conclusion</h3><p>TanStack Query transforms how you handle server state in React. Instead of managing loading states, errors, and caching manually, you get:</p><p>✅ Less code<br>✅ Better performance<br>✅ Automatic caching<br>✅ Background updates<br>✅ Optimistic UI</p><h3>Quick Reference:</h3><ul><li>useQuery → Fetch data</li><li>useMutation → Update data</li><li>useInfiniteQuery → Infinite scroll</li><li>prefetchQuery → Preload data</li><li>invalidateQueries → Refetch data</li><li>setQueryData → Manual updates</li><li>useQueries → Parallel queries</li></ul><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd01806dc86c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Handling in Express — Simple Guide]]></title>
            <link>https://medium.com/@kom50/error-handling-in-express-simple-guide-2031144609c3?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/2031144609c3</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[express-middleware]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 15:26:57 GMT</pubDate>
            <atom:updated>2025-12-06T15:26:57.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>Error Handling in Express — Simple Guide</h3><h4><strong>Keeping Your Express App Safe and Stable</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VzwbAouE_s07rpZcK6WjPA.png" /><figcaption>Error Handling in Express — Simple Guide</figcaption></figure><h3>The Basics You Need to Know</h3><p>Error handling in Express is about catching errors and sending proper responses instead of crashing your app.</p><h3>Why You Need Error Handling</h3><p>Without error handling, your app crashes when something goes wrong. With it, users get helpful messages, and your app keeps running.</p><h3>1. Express Has Built-In Error Handling</h3><p>Good news: Express comes with a default error handler. You don’t need to write one to get started, but you should for better control.</p><h4>Default Error Handler Does:</h4><ul><li>Catches unhandled errors automatically</li><li>Sends stack trace in development</li><li>Hides stack trace in production (set NODE_ENV=production)</li><li>Returns 500 status code</li><li>Closes the connection if the response has already started</li></ul><h3>2. How Express Catches Errors</h3><h4>Synchronous Errors (Automatic)</h4><p>Express automatically catches synchronous errors:</p><pre>app.get(&#39;/&#39;, (req, res) =&gt; {<br>  throw new Error(&#39;BROKEN&#39;); // Express catches this automatically<br>});<br>// No extra work needed!</pre><p><strong>What happens:</strong></p><ol><li>Error is thrown</li><li>Express catches it</li><li>Passes to error handler</li><li>Response sent to client</li></ol><h4>Asynchronous Errors (Express 4 — Manual)</h4><p>You must pass async errors to next():</p><pre>// Callback-based async code<br>app.get(&#39;/&#39;, (req, res, next) =&gt; {<br>  fs.readFile(&#39;/file-does-not-exist&#39;, (err, data) =&gt; {<br>    if (err) {<br>      next(err); // Pass error to Express<br>    } else {<br>      res.send(data);<br>    }<br>  });<br>});</pre><p>What happens:</p><ol><li>Async operation fails</li><li>Error caught in callback</li><li>next(err) passes it to Express</li><li>Express sends to error handler</li></ol><h4>Asynchronous Errors (Express 5 — Automatic)</h4><p>Express 5 automatically catches Promise rejections:</p><pre>app.get(&#39;/user/:id&#39;, async (req, res) =&gt; {<br>  const user = await getUserById(req.params.id); // Automatic error handling!<br>  res.send(user);<br>});</pre><p>What happens:</p><ol><li>If getUserById rejects or throws</li><li>Express automatically calls next(error)</li><li>Error handler receives it</li><li>No try-catch needed!</li></ol><h3>3. Different Async Error Scenarios</h3><p><strong>Scenario 1</strong>: setTimeout/setInterval (Must Catch Manually)</p><pre>// Async code in setTimeout - must use try-catch<br>app.get(&#39;/&#39;, (req, res, next) =&gt; {<br>  setTimeout(() =&gt; {<br>    try {<br>      throw new Error(&#39;BROKEN&#39;);<br>    } catch (err) {<br>      next(err); // Must manually pass to Express<br>    }<br>  }, 100);<br>});</pre><p><strong>Why</strong>: setTimeout is not a Promise, so Express can&#39;t catch it automatically.</p><p><strong>Scenario 2: </strong>Promises (Use .catch())</p><pre>// Promise-based code<br>app.get(&#39;/&#39;, (req, res, next) =&gt; {<br>  Promise.resolve()<br>    .then(() =&gt; {<br>      throw new Error(&#39;BROKEN&#39;);<br>    })<br>    .catch(next); // Pass errors to Express<br>});</pre><p><strong>What </strong><strong>.catch(next) does:</strong></p><ol><li>Catches any error in the Promise chain</li><li>Pass it as the first argument to next()</li><li>Express handles it</li></ol><p><strong>Scenario 3: </strong>Simplified Async with Callbacks</p><pre>// fs.writeFile example - next as callback<br>app.get(&#39;/&#39;, [<br>  function (req, res, next) {<br>    // next works as callback - gets called with error or null<br>    fs.writeFile(&#39;/inaccessible-path&#39;, &#39;data&#39;, next);<br>  },<br>  function (req, res) {<br>    // Only runs if no error<br>    res.send(&#39;OK&#39;);<br>  }<br>]);</pre><p><strong>How it works:</strong></p><ol><li>fs.writeFile calls next(err) if error occurs</li><li>If no error, calls next() (no arguments)</li><li>Second function runs only if no error</li></ol><p><strong>Scenario 4: </strong>Chaining Handlers</p><pre>// Break async code into sync steps<br>app.get(&#39;/&#39;, [<br>  // Handler 1: Async operation<br>  function (req, res, next) {<br>    fs.readFile(&#39;/maybe-valid-file&#39;, &#39;utf-8&#39;, (err, data) =&gt; {<br>      res.locals.data = data; // Store data<br>      next(err); // Pass error or null<br>    });<br>  },<br>  // Handler 2: Sync processing (auto error handling)<br>  function (req, res) {<br>    res.locals.data = res.locals.data.split(&#39;,&#39;)[1];<br>    res.send(res.locals.data);<br>  }<br>]);</pre><p><strong>Benefits</strong>:</p><ul><li>First handler: async work</li><li>Second handler: sync work (Express catches errors automatically)</li><li>Reduces error handling complexity</li></ul><h3>4. Create an Error Handler</h3><p>This is the code that runs when any error happens:</p><pre>// Error handler has 4 parameters: (err, req, res, next)<br>// Put this at the VERY BOTTOM of your file, after all routes<br>app.use((err, req, res, next) =&gt; {<br>  console.error(err); // Log the error<br>  <br>  res.status(500).json({<br>    message: &#39;Something went wrong!&#39;,<br>    error: err.message<br>  });<br>});</pre><p><strong>Important</strong>: Must have exactly 4 parameters for Express to recognize it as an error handler.</p><p><strong>Note</strong>: Error Handler Must Be Last</p><pre>const bodyParser = require(&#39;body-parser&#39;);<br>const methodOverride = require(&#39;method-override&#39;);<br><br>// Regular middleware first<br>app.use(bodyParser.json());<br>app.use(methodOverride());<br><br>// Routes<br>app.get(&#39;/users&#39;, getUsers);<br>app.post(&#39;/users&#39;, createUser);<br><br>// Error handler LAST!<br>app.use((err, req, res, next) =&gt; {<br>  console.error(err.stack);<br>  res.status(500).send(&#39;Something broke!&#39;);<br>});</pre><p><strong>Why last:</strong> Error handlers only catch errors from middleware/routes defined above them.</p><h3>5. Better Error Handling (Optional Upgrade)</h3><p><strong>Step 1: Create Custom Error</strong></p><pre>// Create a custom error class<br>class AppError extends Error {<br>  constructor(message, statusCode) {<br>    super(message);<br>    this.statusCode = statusCode;<br>  }<br>}<br><br>// Now you can throw errors with status codes<br>app.get(&#39;/user/:id&#39;, async (req, res) =&gt; {<br>  const user = await User.findById(req.params.id);<br>  <br>  if (!user) {<br>    throw new AppError(&#39;User not found&#39;, 404);<br>  }<br>  <br>  res.json(user);<br>});</pre><p><strong>Why</strong>: You can set different status codes (404, 400, 403, etc.)</p><p><strong>Step 2: Better Error Handler</strong></p><pre>app.use((err, req, res, next) =&gt; {<br>  // Get status code from error, default to 500<br>  const statusCode = err.statusCode || 500;<br>  <br>  // Send response<br>  res.status(statusCode).json({<br>    status: &#39;error&#39;,<br>    message: err.message<br>  });<br>});</pre><p><strong>Now</strong>:</p><ul><li>404 errors show “Not found”</li><li>400 errors show “Bad request”</li><li>500 errors show “Server error”</li></ul><h3>6. Handle 404 (Route Not Found)</h3><pre>// Put this AFTER all your routes, BEFORE error handler<br>app.use(&#39;*&#39;, (req, res, next) =&gt; {<br>  const err = new Error(`Can&#39;t find ${req.originalUrl}`);<br>  err.statusCode = 404;<br>  next(err);<br>});</pre><p><strong>What it does</strong>: Catches any route that doesn’t exist</p><h3>7. Production vs Development Errors</h3><p>Show different errors in production vs development:</p><pre>app.use((err, req, res, next) =&gt; {<br>  const statusCode = err.statusCode || 500;<br>  <br>  // Development: Show full error<br>  if (process.env.NODE_ENV === &#39;development&#39;) {<br>    res.status(statusCode).json({<br>      status: &#39;error&#39;,<br>      message: err.message,<br>      stack: err.stack // Shows where error happened<br>    });<br>  } <br>  // Production: Hide details<br>  else {<br>    res.status(statusCode).json({<br>      status: &#39;error&#39;,<br>      message: statusCode === 500 ? &#39;Something went wrong&#39; : err.message<br>    });<br>  }<br>});</pre><p><strong>Why</strong>: Don’t show error details to users in production (security)</p><h3>8. Multiple Error Handlers</h3><p>You can chain multiple error handlers for different purposes:</p><pre>app.use(bodyParser.json());<br>app.use(methodOverride());<br><br>// Your routes...<br><br>// 1. Log errors<br>app.use(logErrors);<br><br>// 2. Handle client errors (AJAX)<br>app.use(clientErrorHandler);<br><br>// 3. Catch-all error handler<br>app.use(errorHandler);</pre><p><strong>Flow</strong>:</p><ol><li>Error occurs</li><li>logErrors logs it, passes to the next</li><li>clientErrorHandler checks if AJAX, handles or passes on</li><li>errorHandler catches anything remaining</li></ol><h3>9. Skipping to Next Route</h3><p>Use next(&#39;route&#39;) to skip remaining handlers in current route:</p><pre>app.get(&#39;/a_route_behind_paywall&#39;,<br>  // First handler - check payment<br>  (req, res, next) =&gt; {<br>    if (!req.user.hasPaid) {<br>      next(&#39;route&#39;); // Skip to next route definition<br>    } else {<br>      next(); // Continue to next handler<br>    }<br>  },<br>  // Second handler - only runs if paid<br>  (req, res, next) =&gt; {<br>    PaidContent.find((err, doc) =&gt; {<br>      if (err) return next(err); // Pass error<br>      res.json(doc);<br>    });<br>  }<br>);<br><br>// This route is called if user hasn&#39;t paid<br>app.get(&#39;/a_route_behind_paywall&#39;, (req, res) =&gt; {<br>  res.status(403).send(&#39;Payment required&#39;);<br>});</pre><p>How it works:</p><ul><li>next(&#39;route&#39;): Skip to next route with the same path</li><li>next(): Continue to next handler in current route</li><li>next(err): Skip to error handler</li></ul><h3>10. Key Rules Summary</h3><p><strong>Rule 1: Error Handler Signature</strong></p><pre>// Must have 4 parameters<br>app.use((err, req, res, next) =&gt; {<br>  // ...<br>});</pre><p><strong>Rule 2: Error Handlers Go Last</strong></p><pre>app.use(middleware);     // Regular middleware<br>app.get(&#39;/route&#39;, handler); // Routes<br>app.use(errorHandler);   // Error handlers LAST</pre><p><strong>Rule 3: Pass Async Errors to next()</strong></p><pre>// Express 4<br>app.get(&#39;/&#39;, (req, res, next) =&gt; {<br>  asyncOperation()<br>    .then(data =&gt; res.send(data))<br>    .catch(next); // Pass errors<br>});<br><br>// Express 5<br>app.get(&#39;/&#39;, async (req, res) =&gt; {<br>  const data = await asyncOperation(); // Automatic<br>  res.send(data);<br>});</pre><p><strong>Rule 4: Use next(err) to Trigger Error Handler</strong></p><pre>if (error) {<br>  next(error); // Goes to error handler<br>}</pre><p><strong>Rule 5: Check Headers Before Responding</strong></p><pre>if (res.headersSent) {<br>  return next(err); // Let default handler deal with it<br>}</pre><h3>11. Common Patterns Quick Reference</h3><p><strong>Status Codes to Use:</strong></p><pre>200 // OK - Success<br>201 // Created - New resource created<br>400 // Bad Request - Invalid data<br>401 // Unauthorized - Need to login<br>403 // Forbidden - No permission<br>404 // Not Found - Resource doesn&#39;t exist<br>500 // Server Error - Something broke</pre><p><strong>Common Patterns:</strong></p><pre>// Not found<br>if (!user) {<br>  throw new AppError(&#39;User not found&#39;, 404);<br>}<br><br>// Missing data<br>if (!email) {<br>  throw new AppError(&#39;Email is required&#39;, 400);<br>}<br><br>// No permission<br>if (!req.user.isAdmin) {<br>  throw new AppError(&#39;Access denied&#39;, 403);<br>}<br><br>// Duplicate entry<br>if (existingUser) {<br>  throw new AppError(&#39;Email already exists&#39;, 409);<br>}</pre><p><strong>Common Suggestions.</strong></p><pre>// Pattern 1: Basic Error Handler<br>app.use((err, req, res, next) =&gt; {<br>  res.status(500).send(err.message);<br>});<br><br>//Pattern 2: Async with Promises <br>app.get(&#39;/route&#39;, (req, res, next) =&gt; {<br>  asyncFunc().then(data =&gt; res.send(data)).catch(next);<br>});<br><br>// Pattern 3: Async with Async/Await (Express 5)<br>app.get(&#39;/route&#39;, async (req, res) =&gt; {<br>  const data = await asyncFunc();<br>  res.send(data);<br>});<br><br>// Pattern 4: Callback Error Passing<br>app.get(&#39;/route&#39;, (req, res, next) =&gt; {<br>  fs.readFile(&#39;file&#39;, (err, data) =&gt; {<br>    if (err) return next(err);<br>    res.send(data);<br>  });<br>});<br><br>// Pattern 5: Multiple Error Handlers<br>app.use(logErrors);<br>app.use(clientErrorHandler);<br>app.use(errorHandler); </pre><h3>Conclusion</h3><p>Handle errors properly so your app doesn’t crash. Express 4 needs next(err) for async issues, while Express 5 handles them automatically. Put your error handler last, use the 4-argument format, and send clear status codes. That’s all you need for simple, clean, and safe error handling in Express.</p><h3>Resources</h3><ul><li><a href="https://expressjs.com/en/guide/error-handling.html">Express Error Handling Docs</a></li><li><a href="https://www.npmjs.com/package/express-async-errors">express-async-errors on npm</a></li></ul><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2031144609c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Error Boundaries in React: A Simple Guide to Stop Your App From Crashing]]></title>
            <link>https://medium.com/@kom50/error-boundaries-in-react-a-simple-guide-to-stop-your-app-from-crashing-1731ea0b59fe?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/1731ea0b59fe</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-error-boundary]]></category>
            <category><![CDATA[error-handling]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Sat, 06 Dec 2025 09:21:13 GMT</pubDate>
            <atom:updated>2025-12-06T09:21:13.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LyxncnNaIdqxj2fCfiSbLQ.png" /><figcaption>Error Boundaries in React</figcaption></figure><p>If you’ve ever shipped a React app and suddenly seen a <strong>blank white screen</strong>, you know how scary it feels. One tiny bug in a single component can bring down your whole application.</p><p>Thankfully, React gives us a powerful tool to prevent this: <strong>Error Boundaries</strong>.</p><p>In this post, you’ll learn what they are, why they matter, and how to use them — all in a simple, beginner-friendly way.</p><h3>What Are Error Boundaries?</h3><p>Error Boundaries are React components with a special superpower: they catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of letting your entire application crash.</p><p>Think of them as try-catch blocks, but for <strong>React components</strong>.</p><h3>What Error Boundaries Don’t Catch</h3><p>They do NOT catch errors from:</p><ul><li>Event handlers (onClick, etc.)</li><li>Async code (timeouts, promises, async/await)</li><li>Server-side rendering</li><li>Errors <em>inside</em> the error boundary itself</li></ul><blockquote><strong>NOTE</strong>: “Why not event handlers? Because React doesn’t need Error Boundaries to recover from errors in event handlers. Unlike rendering errors, they don’t corrupt the component tree.”</blockquote><h3>The Problem They Solve</h3><h4>Before Error Boundaries (React 15 and earlier)</h4><pre>// One error in this component...<br>function BrokenWidget() {<br>  const data = null;<br>  return &lt;div&gt;{data.name}&lt;/div&gt;; // TypeError: Cannot read property &#39;name&#39; of null<br>}<br><br>// ...would crash your ENTIRE app<br>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      &lt;BrokenWidget /&gt; {/* 💥 App crashes here */}<br>      &lt;MainContent /&gt; {/* Never rendered */}<br>      &lt;Footer /&gt; {/* Never rendered */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Result</strong>: White screen of death. Frustrated users. Lost revenue.</p><h4>After Error Boundaries (React 16+)</h4><pre>function App() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Header /&gt;<br>      &lt;ErrorBoundary&gt;<br>        &lt;BrokenWidget /&gt; {/* 💥 Error caught */}<br>      &lt;/ErrorBoundary&gt;<br>      &lt;MainContent /&gt; {/* Still renders! */}<br>      &lt;Footer /&gt; {/* Still renders! */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Result</strong>: Error contained. App keeps running. Users stay happy.</p><h3>Creating Your First Error Boundary</h3><p>Error Boundaries must be class components (for now — we’ll discuss this later). You create one by implementing either or both of these lifecycle methods:</p><ol><li>static getDerivedStateFromError() — Renders fallback UI</li><li>componentDidCatch() — Logs error information</li></ol><h4>Basic Implementation</h4><pre>import React from &#39;react&#39;;<br><br>class ErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { <br>      hasError: false,<br>      error: null,<br>      errorInfo: null<br>    };<br>  }<br><br>  // Update state so the next render shows the fallback UI<br>  static getDerivedStateFromError(error) {<br>    return { hasError: true };<br>  }<br><br>  // Log the error to an error reporting service<br>  componentDidCatch(error, errorInfo) {<br>    console.error(&quot;Error caught by Error Boundary:&quot;, error, errorInfo);<br>    <br>    // Send to Sentry, LogRocket, or your preferred service<br>    // logErrorToMyService(error, errorInfo);<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      // Custom fallback UI<br>      return (<br>        &lt;div className=&quot;error-boundary&quot;&gt;<br>          &lt;h2&gt;🔧 Something went wrong.&lt;/h2&gt;<br>          &lt;p&gt;We&#39;re sorry for the inconvenience.&lt;/p&gt;<br>          &lt;button onClick={() =&gt; this.setState({ hasError: false })}&gt;<br>            Try again<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      );<br>    }<br><br>    return this.props.children;<br>  }<br>}<br><br>export default ErrorBoundary;</pre><h4>Breaking Down the Code</h4><p>The Constructor:</p><pre>this.state = { <br>  hasError: false,  // Has an error occurred?<br>  error: null,      // The error object<br>  errorInfo: null   // Component stack trace<br>};</pre><p><strong>getDerivedStateFromError</strong>:</p><ul><li>Called during the “render” phase</li><li>Must return a value to update state</li><li>Should be pure (no side effects)</li></ul><p><strong>componentDidCatch</strong>:</p><ul><li>Called during the “commit” phase</li><li>Perfect for logging errors</li><li>Can have side effects</li></ul><h3>Real-World Example</h3><p>Let’s build a complete application with Error Boundaries protecting different sections.</p><pre>// App.js<br>import React from &#39;react&#39;;<br>import ErrorBoundary from &#39;./ErrorBoundary&#39;;<br>import UserProfile from &#39;./UserProfile&#39;;<br>import CommentSection from &#39;./CommentSection&#39;;<br>import &#39;./App.css&#39;;<br><br>function App() {<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;🚀 My Application&lt;/h1&gt;<br>      <br>      {/* Each section has its own error boundary */}<br>      &lt;ErrorBoundary&gt;<br>        &lt;UserProfile userId=&quot;123&quot; /&gt;<br>      &lt;/ErrorBoundary&gt;<br>      <br>      &lt;hr /&gt;<br>      <br>      &lt;ErrorBoundary&gt;<br>        &lt;CommentSection postId=&quot;456&quot; /&gt;<br>      &lt;/ErrorBoundary&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><pre>// UserProfile.js - EVEN SIMPLER<br>import React from &#39;react&#39;;<br><br>function UserProfile({ userId }) {<br>  // ✅ This throws during render - Error Boundary catches it!<br>  if (userId === &quot;123&quot;) {<br>    throw new Error(&quot;Invalid user ID&quot;);<br>  }<br>  <br>  return (<br>    &lt;div className=&quot;user-profile&quot;&gt;<br>      &lt;h3&gt;👤 User Profile&lt;/h3&gt;<br>      &lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; John Doe&lt;/p&gt;<br>      &lt;p&gt;&lt;strong&gt;Email:&lt;/strong&gt; john@example.com&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UserProfile;</pre><h3>What Happens?</h3><ol><li><strong>UserProfile</strong> throws an error → Error Boundary catches it → Shows fallback UI</li><li><strong>CommentSection</strong> works fine → Renders normally</li><li>The rest of your app continues working!</li></ol><h3>Best Practices</h3><h4>1. Strategic Placement</h4><p>Don’t wrap every single component. Place Error Boundaries at strategic levels:</p><pre>function App() {<br>  return (<br>    &lt;div&gt;<br>      {/* Route-level error boundary */}<br>      &lt;ErrorBoundary&gt;<br>        &lt;Router&gt;<br>          &lt;Routes&gt;<br>            {/* Page-level error boundary */}<br>            &lt;Route path=&quot;/dashboard&quot; element={<br>              &lt;ErrorBoundary&gt;<br>                &lt;Dashboard /&gt;<br>              &lt;/ErrorBoundary&gt;<br>            } /&gt;<br>            <br>            {/* Widget-level error boundary */}<br>            &lt;Route path=&quot;/profile&quot; element={<br>              &lt;div&gt;<br>                &lt;ErrorBoundary&gt;<br>                  &lt;UserWidget /&gt;<br>                &lt;/ErrorBoundary&gt;<br>                &lt;ErrorBoundary&gt;<br>                  &lt;StatsWidget /&gt;<br>                &lt;/ErrorBoundary&gt;<br>              &lt;/div&gt;<br>            } /&gt;<br>          &lt;/Routes&gt;<br>        &lt;/Router&gt;<br>      &lt;/ErrorBoundary&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Think of it like this:</strong></p><ul><li><strong>Top-level</strong>: Catch catastrophic failures</li><li><strong>Route-level</strong>: Isolate page errors</li><li><strong>Widget-level</strong>: Contain independent component failures</li></ul><h4>2. Meaningful Fallback UIs</h4><pre>// Bad: <br>return &lt;div&gt;Error&lt;/div&gt;<br><br>// Good:<br>return (<br>  &lt;div className=&quot;error-fallback&quot;&gt;<br>    &lt;img src=&quot;/error-illustration.svg&quot; alt=&quot;Error&quot; /&gt;<br>    &lt;h2&gt;Unable to load {this.props.componentName}&lt;/h2&gt;<br>    &lt;p&gt;Please try again or contact support if the problem persists.&lt;/p&gt;<br>    &lt;button onClick={this.handleRetry}&gt;Retry&lt;/button&gt;<br>    &lt;a href=&quot;/support&quot;&gt;Contact Support&lt;/a&gt;<br>  &lt;/div&gt;<br>);</pre><h4>3. Proper Error Logging</h4><pre>componentDidCatch(error, errorInfo) {<br>  // Log comprehensive error information<br>  const errorData = {<br>    message: error.message,<br>    stack: error.stack,<br>    componentStack: errorInfo.componentStack,<br>    <br>    // Context<br>    timestamp: new Date().toISOString(),<br>    url: window.location.href,<br>    userAgent: navigator.userAgent,<br>    <br>    // User info (if available)<br>    userId: this.props.user?.id,<br>    <br>    // App state (if using Redux)<br>    appState: store.getState(),<br>  };<br><br>  // Send to logging service<br>  // logToSentry(errorData);<br>  // or<br>  // logToCustomService(errorData);<br>}</pre><h4>4. Different Fallbacks for Different Errors</h4><pre>render() {<br>  if (this.state.hasError) {<br>    // Network error<br>    if (this.state.error.message.includes(&#39;fetch&#39;)) {<br>      return &lt;NetworkErrorFallback /&gt;;<br>    }<br>    <br>    // Permission error<br>    if (this.state.error.message.includes(&#39;permission&#39;)) {<br>      return &lt;PermissionDeniedFallback /&gt;;<br>    }<br>    <br>    // Default error<br>    return &lt;GenericErrorFallback /&gt;;<br>  }<br><br>  return this.props.children;<br>}</pre><h3>Common Pitfalls</h3><p><strong>❌ Pitfall #1: Event Handler Errors Aren’t Caught</strong></p><pre>function MyComponent() {<br>  const handleClick = () =&gt; {<br>    // This error WON&#39;T be caught by Error Boundary<br>    throw new Error(&#39;Button clicked&#39;);<br>  };<br><br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>}</pre><p><strong>Solution</strong>: Use try-catch:</p><pre>function MyComponent() {<br>  const [error, setError] = useState(null);<br><br>  const handleClick = () =&gt; {<br>    try {<br>      // Your code<br>      throw new Error(&#39;Button clicked&#39;);<br>    } catch (err) {<br>      setError(err);<br>      // Or report to error service<br>    }<br>  };<br><br>  if (error) {<br>    throw error; // Now Error Boundary can catch it<br>  }<br><br>  return &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;;<br>}</pre><p><strong>❌ Pitfall #2: Async Errors Aren’t Caught</strong></p><pre>function MyComponent() {<br>  useEffect(() =&gt; {<br>    // This error WON&#39;T be caught<br>    setTimeout(() =&gt; {<br>      throw new Error(&#39;Async error&#39;);<br>    }, 1000);<br>  }, []);<br><br>  return &lt;div&gt;Component&lt;/div&gt;;<br>}</pre><p><strong>Solution</strong>: Handle async errors explicitly:</p><pre>function MyComponent() {<br>  const [error, setError] = useState(null);<br><br>  useEffect(() =&gt; {<br>    setTimeout(() =&gt; {<br>      try {<br>        throw new Error(&#39;Async error&#39;);<br>      } catch (err) {<br>        setError(err);<br>      }<br>    }, 1000);<br>  }, []);<br><br>  if (error) {<br>    throw error; // Error Boundary catches this<br>  }<br><br>  return &lt;div&gt;Component&lt;/div&gt;;<br>}</pre><p><strong>❌ Pitfall #3: Errors in the Error Boundary Itself</strong></p><pre>// DON&#39;T DO THIS<br>class BadErrorBoundary extends React.Component {<br>  componentDidCatch(error, errorInfo) {<br>    // This could cause an infinite loop!<br>    this.props.onError(); // What if this throws?<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      // This could throw too!<br>      return &lt;ComplexComponent data={undefined} /&gt;;<br>    }<br>    return this.props.children;<br>  }<br>}</pre><p><strong>Solution</strong>: Keep Error Boundary logic simple and safe:</p><pre>class GoodErrorBoundary extends React.Component {<br>  componentDidCatch(error, errorInfo) {<br>    try {<br>      // Safely handle callbacks<br>      this.props.onError?.(error);<br>    } catch (err) {<br>      console.error(&#39;Error in error handler:&#39;, err);<br>    }<br>  }<br><br>  render() {<br>    if (this.state.hasError) {<br>      // Simple, safe fallback<br>      return (<br>        &lt;div&gt;<br>          &lt;h2&gt;Something went wrong&lt;/h2&gt;<br>          &lt;button onClick={() =&gt; window.location.reload()}&gt;<br>            Reload<br>          &lt;/button&gt;<br>        &lt;/div&gt;<br>      );<br>    }<br>    return this.props.children;<br>  }<br>}</pre><h4>Error Boundary with React Router</h4><pre>import { useRouteError } from &#39;react-router-dom&#39;;<br><br>// Error Boundary for React Router v6.4+<br>function RouterErrorBoundary() {<br>  const error = useRouteError();<br><br>  return (<br>    &lt;div className=&quot;route-error&quot;&gt;<br>      &lt;h1&gt;😱 Route Error&lt;/h1&gt;<br>      &lt;p&gt;{error.statusText || error.message}&lt;/p&gt;<br>      &lt;a href=&quot;/&quot;&gt;Go Home&lt;/a&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// In your router configuration<br>const router = createBrowserRouter([<br>  {<br>    path: &quot;/&quot;,<br>    element: &lt;Root /&gt;,<br>    errorElement: &lt;RouterErrorBoundary /&gt;,<br>    children: [<br>      {<br>        path: &quot;dashboard&quot;,<br>        element: &lt;Dashboard /&gt;,<br>        errorElement: &lt;RouterErrorBoundary /&gt;,<br>      },<br>    ],<br>  },<br>]);</pre><h3>Key Takeaways</h3><ul><li>Error Boundaries prevent your entire app from crashing when a single component fails</li><li>They only work for errors during rendering, lifecycle methods, and constructors — not event handlers or async code</li><li>Must be class components (no hooks equivalent yet)</li><li>Place them strategically at the route, page, and widget levels</li><li>Always provide user-friendly fallback UIs with retry options</li><li>Log errors to monitoring services like Sentry or LogRocket</li><li>Keep the error boundary itself simple to avoid errors in error handling</li></ul><h3>Useful Links</h3><ul><li><a href="https://legacy.reactjs.org/docs/error-boundaries.html">https://legacy.reactjs.org/docs/error-boundaries.html</a></li><li><a href="https://www.npmjs.com/package/react-error-boundary">https://www.npmjs.com/package/react-error-boundary</a></li></ul><h3>Conclusion</h3><p>Error Boundaries are one of React’s most underrated features. They transform your app from fragile to fail-safe by catching unexpected crashes before they reach your users. With just a few lines of code and smart placement, you can make your UI dramatically more stable, reliable, and professional.</p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1731ea0b59fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Context API: State Management Without Redux]]></title>
            <link>https://medium.com/@kom50/react-context-api-state-management-without-redux-dd94483b8ed2?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd94483b8ed2</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react-context-api]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 20:17:58 GMT</pubDate>
            <atom:updated>2025-12-01T20:17:58.288Z</atom:updated>
            <content:encoded><![CDATA[<h4>The simplest way to manage global state in React — no libraries required.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I0Kt3j05uEu0Rc-TyzeQTg.png" /><figcaption>React Context API: State Management</figcaption></figure><p>If you’ve been building React apps for a while, you’ve probably experienced the pain of passing props down through multiple component levels. And maybe someone told you, “Just use Redux!” But here’s the thing: you might not need Redux at all.</p><p>Enter the <strong>React Context API </strong>— a built-in solution that’s been hiding in plain sight.</p><p>In this post, I’ll show you how to manage state across your React application without adding Redux to your bundle. No complicated setup, no extra dependencies, just React doing what it does best.</p><p>Let’s dive in.</p><h3>What’s Wrong With Prop Drilling Anyway?</h3><p>Imagine you have a user’s theme preference (light or dark mode) that needs to be accessible in your header, sidebar, and footer components. Without Context, your component tree might look like this:</p><pre>&lt;App theme={theme}&gt;<br>  &lt;Header theme={theme}&gt;<br>    &lt;Navigation theme={theme}&gt;<br>      &lt;UserMenu theme={theme} /&gt;<br>    &lt;/Navigation&gt;<br>  &lt;/Header&gt;<br>&lt;/App&gt;</pre><p>See the problem? Components that don’t even use theme have to pass it down like a game of telephone. This is prop drilling, and it&#39;s messy.</p><h3>What Is the Context API?</h3><p>Think of Context as a wormhole in your component tree. Instead of passing data down step-by-step through props, Context lets you:</p><ul><li>Create a “context” (a data container)</li><li>Provide that data at the top of your component tree</li><li>Consume that data anywhere below, no matter how deep</li></ul><p>It’s like having a global state that any component can tap into — but without the actual global scope issues.</p><h3>Your First Context: A Simple Example</h3><p>Let’s build a theme switcher. Here’s how Context makes it painless:</p><h3>Step 1: Create the Context</h3><pre>import { createContext } from &#39;react&#39;;<br><br>const ThemeContext = createContext();</pre><h3>Step 2: Provide the Context</h3><p>Wrap your app (or part of it) with a Provider:</p><pre>import { useState } from &#39;react&#39;;<br><br>function App() {<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;<br>      &lt;Header /&gt;<br>      &lt;MainContent /&gt;<br>      &lt;Footer /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}</pre><p>The value prop is what you&#39;re sharing. Any component inside this Provider can now access theme and setTheme.</p><h3>Step 3: Consume the Context</h3><p>Anywhere in your component tree, use the useContext hook:</p><pre>import { useContext } from &#39;react&#39;;<br><br>function Header() {<br>  const { theme, setTheme } = useContext(ThemeContext);<br><br>  return (<br>    &lt;header className={theme}&gt;<br>      &lt;button onClick={() =&gt; setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/header&gt;<br>  );<br>}</pre><p>No prop drilling. No middleware. Just clean, direct access to the data you need.</p><h3>React 19 Update: Meet the use API</h3><p>If you’re using React 19, there’s a new way to consume context: the <a href="https://react.dev/blog/2024/12/05/react-19#new-feature-use">use API.</a></p><p>While useContext works perfectly fine, the use API offers a cleaner, more flexible alternative for reading context values.</p><h4>Using use Instead of useContext</h4><p>Here’s the same Header component, but with the use API:</p><pre>import { use } from &#39;react&#39;;<br><br>function Header() {<br>  const { theme, setTheme } = use(ThemeContext);<br><br>  return (<br>    &lt;header className={theme}&gt;<br>      &lt;button onClick={() =&gt; setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)}&gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/header&gt;<br>  );<br>}</pre><p>Simple, right? The API is almost identical.</p><h4>Why Use use for Context?</h4><p>The use API has one key advantage over useContext: it can be called conditionally.</p><pre>import { use } from &#39;react&#39;;<br><br>function UserProfile({ isGuest }) {<br>  // This works with &#39;use&#39; but would break with &#39;useContext&#39;<br>  const theme = isGuest <br>    ? { theme: &#39;light&#39;, setTheme: () =&gt; {} } <br>    : use(ThemeContext);<br><br>  return &lt;div className={theme.theme}&gt;Profile Content&lt;/div&gt;;<br>}</pre><p>With useContext, all hooks must be called unconditionally at the top of your component. The use API is more flexible.</p><h4>Comparison: useContext vs use</h4><pre>// Traditional way (React 18 and earlier)<br>import { useContext } from &#39;react&#39;;<br><br>function MyComponent() {<br>  const theme = useContext(ThemeContext);<br>  return &lt;div className={theme}&gt;Content&lt;/div&gt;;<br>}<br><br>// Modern way (React 19)<br>import { use } from &#39;react&#39;;<br><br>function MyComponent() {<br>  const theme = use(ThemeContext);<br>  return &lt;div className={theme}&gt;Content&lt;/div&gt;;<br>}</pre><p>Both work exactly the same! The use API is just a more flexible alternative.</p><h3>Should You Switch?</h3><p>If you’re already using useContext, there&#39;s no rush to change. But for new code in React 19, use is the recommended approach for context consumption because of its flexibility.</p><p>Quick decision guide:</p><ul><li>✅ Use use in React 19+ projects</li><li>✅ Stick with useContext if you&#39;re on React 18 or earlier</li><li>✅ Both are fine — choose based on your React version</li></ul><h3>Real-World Use Case: User Authentication</h3><p>Here’s where Context really shines. Let’s build an authentication system using React 19’s use API:</p><pre>import { createContext, use, useState } from &#39;react&#39;;<br><br>const AuthContext = createContext();<br><br>export function AuthProvider({ children }) {<br>  const [user, setUser] = useState(null);<br><br>  const login = async (email, password) =&gt; {<br>    // Your login logic here<br>    const userData = await fakeLoginAPI(email, password);<br>    setUser(userData);<br>  };<br><br>  const logout = () =&gt; {<br>    setUser(null);<br>  };<br><br>  return (<br>    &lt;AuthContext.Provider value={{ user, login, logout }}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>}<br><br>// Custom hook for easy access<br>export function useAuth() {<br>  const context = use(AuthContext);<br>  if (!context) {<br>    throw new Error(&#39;useAuth must be used within AuthProvider&#39;);<br>  }<br>  return context;<br>}</pre><p>Now, anywhere in your app:</p><pre>function ProfilePage() {<br>  const { user, logout } = useAuth();<br><br>  if (!user) {<br>    return &lt;LoginPrompt /&gt;;<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome, {user.name}!&lt;/h1&gt;<br>      &lt;button onClick={logout}&gt;Log Out&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Beautiful, isn’t it?</p><h3>When Should You Use Context?</h3><p>Context is perfect for:</p><ul><li><strong>Theme data</strong> (dark mode, light mode, custom themes)</li><li><strong>User authentication</strong> (current user, login/logout functions)</li><li><strong>Language</strong>/<strong>localization</strong> (current language, translation functions)</li><li><strong>UI state</strong> (sidebar open/closed, modal visibility)</li><li><strong>User preferences</strong> (font size, accessibility settings)</li></ul><p>Basically, anything that multiple components need to access, but doesn’t change super frequently.</p><h3>When Should You NOT Use Context?</h3><p>Context isn’t always the answer. Avoid it for:</p><ul><li><strong>Data that changes very often</strong> — Context can cause unnecessary re-renders</li><li><strong>Complex state logic</strong> — If you need time-travel debugging or complex middleware, Redux might be better</li><li><strong>Performance-critical apps</strong> — Context updates trigger re-renders of all consuming components</li></ul><p>For highly dynamic data, consider these alternatives:</p><ul><li><strong>Local component state</strong> — Keep it simple when possible</li><li><strong>URL state</strong> — For filters, pagination, etc.</li><li><strong>External state libraries</strong> — Zustand, Jotai, or Recoil for complex scenarios</li></ul><h3>Best Practices: Making Context Work for You</h3><h4>1. Split Your Contexts</h4><p>Don’t create a single, monolithic context for everything. Split them by concern:</p><pre>&lt;AuthProvider&gt;<br>  &lt;ThemeProvider&gt;<br>    &lt;LanguageProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/LanguageProvider&gt;<br>  &lt;/ThemeProvider&gt;<br>&lt;/AuthProvider&gt;</pre><p>This prevents components from re-rendering when unrelated data changes.</p><h4>2. Create Custom Hooks</h4><p>Always wrap your context consumption in a custom hook (works with both use and useContext):</p><pre>// React 19 version<br>import { use } from &#39;react&#39;;<br><br>export function useTheme() {<br>  const context = use(ThemeContext);<br>  if (!context) {<br>    throw new Error(&#39;useTheme must be used within ThemeProvider&#39;);<br>  }<br>  return context;<br>}<br><br>// React 18 version<br>import { useContext } from &#39;react&#39;;<br><br>export function useTheme() {<br>  const context = useContext(ThemeContext);<br>  if (!context) {<br>    throw new Error(&#39;useTheme must be used within ThemeProvider&#39;);<br>  }<br>  return context;<br>}</pre><p>Benefits:</p><ul><li>Better error messages</li><li>Easier to refactor later</li><li>Cleaner component code</li></ul><h4>3. Memoize Your Context Value</h4><p>Prevent unnecessary re-renders by memoizing the value:</p><pre>import { useMemo } from &#39;react&#39;;<br><br>function AuthProvider({ children }) {<br>  const [user, setUser] = useState(null);<br><br>  const value = useMemo(<br>    () =&gt; ({ user, login, logout }),<br>    [user]<br>  );<br><br>  return (<br>    &lt;AuthContext.Provider value={value}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>}</pre><h4>4. Combine Context with useReducer</h4><p>For more complex state logic, pair Context with useReducer:</p><pre>import { createContext, useReducer, use } from &#39;react&#39;;<br><br>const CartContext = createContext();<br><br>function cartReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;ADD_ITEM&#39;:<br>      return { ...state, items: [...state.items, action.item] };<br>    case &#39;REMOVE_ITEM&#39;:<br>      return { ...state, items: state.items.filter(i =&gt; i.id !== action.id) };<br>    case &#39;CLEAR_CART&#39;:<br>      return { ...state, items: [] };<br>    default:<br>      return state;<br>  }<br>}<br><br>export function CartProvider({ children }) {<br>  const [state, dispatch] = useReducer(cartReducer, { items: [] });<br><br>  return (<br>    &lt;CartContext.Provider value={{ state, dispatch }}&gt;<br>      {children}<br>    &lt;/CartContext.Provider&gt;<br>  );<br>}<br><br>// Custom hook using &#39;use&#39;<br>export function useCart() {<br>  const context = use(CartContext);<br>  if (!context) {<br>    throw new Error(&#39;useCart must be used within CartProvider&#39;);<br>  }<br>  return context;<br>}</pre><p>This gives you Redux-like patterns without Redux.</p><h3>Context vs. Redux: The Real Talk</h3><p><strong>You don’t need Redux if:</strong></p><ul><li>Your app is small to medium-sized</li><li>Your state logic is straightforward</li><li>You don’t need time-travel debugging</li><li>You want less boilerplate</li></ul><p><strong>Consider Redux if:</strong></p><ul><li>You have complex state interactions</li><li>You need robust debugging tools</li><li>Your team is already familiar with Redux</li><li>You’re building a large-scale enterprise app</li></ul><p>For most modern React apps, <strong>Context</strong> + <strong>hooks</strong> is more than enough. Don’t add complexity you don’t need.</p><h3>Common Pitfalls (And How to Avoid Them)</h3><h4>Pitfall #1: Re-render Hell</h4><p>Every time the Context value changes, all consumers re-render. Split contexts and memoize values to minimize this.</p><h4>Pitfall #2: Forgetting to Provide</h4><p>If you useContext outside a Provider, you&#39;ll get undefined. Always check in your custom hook:</p><pre>export function useAuth() {<br>  const context = useContext(AuthContext);<br>  if (context === undefined) {<br>    throw new Error(&#39;useAuth must be used within AuthProvider&#39;);<br>  }<br>  return context;<br>}</pre><h4>Pitfall #3: Overusing Context</h4><p>Not everything needs to be in Context. Ask yourself: “Do multiple, unrelated components need this data?” If no, keep it local.</p><h3>Wrapping Up</h3><p>The React Context API is one of those features that feels like a superpower once you understand it. You get clean, maintainable code without the ceremony of Redux.</p><p>The best part? Context is already in React. No installation, no configuration, no learning a whole new library. Just React being awesome.</p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd94483b8ed2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Performance Optimization: A Simple Guide for Beginners]]></title>
            <link>https://medium.com/@kom50/react-performance-optimization-a-simple-guide-for-beginners-2642fa0ef2b9?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/2642fa0ef2b9</guid>
            <category><![CDATA[react-performance]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 16:25:52 GMT</pubDate>
            <atom:updated>2025-12-01T06:50:55.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkJSpeOqjQhP_DXZOq-NKw.png" /><figcaption>React Performance Optimization</figcaption></figure><h3>Make Your React Apps Super Fast!</h3><p>Hello, friends! Today, we’ll learn how to speed up React apps with simple explanations.</p><h3>The Problem</h3><p>Imagine you have a restaurant. Every time ONE customer orders food, you cook ALL the food again for ALL customers. That’s crazy, right? You waste time and energy!</p><p>React sometimes does the same thing. When one small thing changes, React re-creates everything again. This makes your app slow.</p><p>Let’s fix this!</p><h3>Solution 1: React.memo</h3><h4>What is it?</h4><p><strong>React.memo</strong> is like a smart helper. It remembers your component and says: “Hey, nothing changed here, no need to work again!”</p><p>Simple Example:</p><pre>// Without React.memo (Slow)<br>function MovieCard({ title, year }) {<br>  console.log(&quot;Creating movie card again...&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{title}&lt;/h2&gt;<br>      &lt;p&gt;Year: {year}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// With React.memo (Fast!)<br>const MovieCard = React.memo(function MovieCard({ title, year }) {<br>  console.log(&quot;Creating movie card...&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;{title}&lt;/h2&gt;<br>      &lt;p&gt;Year: {year}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><h4>What happens?</h4><ul><li><strong>Without React.memo</strong>: Component re-creates every time, even if title and year are the same.</li><li><strong>With React.memo</strong>: Component only re-creates when the title or year actually changes.</li></ul><p><strong>Think of it like</strong>: Taking a photo vs using an old photo. If you look the same, why take a new photo?</p><h3>Solution 2: useMemo</h3><h4>What is it?</h4><p><strong>useMemo</strong> saves the result of heavy calculations. It says: “I already calculated this, here is the answer!”</p><p>Simple Example:</p><pre>function ShoppingCart({ items }) {<br>  // Without useMemo (Slow) ❌<br>  const total = items.reduce((sum, item) =&gt; sum + item.price, 0);<br>  <br>  // With useMemo (Fast) ✅<br>  const total = useMemo(() =&gt; {<br>    console.log(&quot;Calculating total...&quot;);<br>    return items.reduce((sum, item) =&gt; sum + item.price, 0);<br>  }, [items]);<br>  <br>  return &lt;div&gt;Total: ${total}&lt;/div&gt;;<br>}</pre><h4>What happens?</h4><ul><li><strong>Without useMemo</strong>: Calculates the total every time the component renders</li><li><strong>With useMemo</strong>: Only calculates when items array changes</li></ul><p><strong>Think of it like</strong>: Doing homework vs copying homework you already did. If the question is the same, use the old answer!</p><h3>Solution 3: useCallback</h3><h4>What is it?</h4><p><strong>useCallback</strong> saves functions. It gives the same function again instead of creating a new one.</p><p>Simple Example:</p><pre>function TodoApp() {<br>  const [todos, setTodos] = useState([]);<br>  <br>  // Without useCallback (Slow) ❌<br>  const addTodo = (text) =&gt; {<br>    setTodos([...todos, text]);<br>  };<br>  <br>  // With useCallback (Fast) ✅<br>  const addTodo = useCallback((text) =&gt; {<br>    setTodos([...todos, text]);<br>  }, [todos]);<br>  <br>  return &lt;AddButton onClick={addTodo} /&gt;;<br>}</pre><h4>What happens?</h4><ul><li><strong>Without useCallback</strong>: Creates a new function every render</li><li><strong>With useCallback</strong>: Returns the same function if dependencies don’t change</li></ul><p><strong>Think of it like</strong>: Your phone number vs changing your number daily. Keep the same number so friends can call you!</p><h3>When to Use These?</h3><h4>Use React.memo when:</h4><ul><li>Component renders many times</li><li>Component receives the same props often</li><li>Component is big and slow</li></ul><h4>Use useMemo when:</h4><ul><li>You do heavy calculations</li><li>You filter large lists</li><li>You process lots of data</li></ul><h4>Use useCallback when:</h4><ul><li>You pass functions to child components</li><li>Child components use React.memo</li><li>Function is used in dependency arrays</li></ul><h3>Important Warning!</h3><p><strong>Don’t use it everywhere!</strong></p><p>These tools are like medicine. Use only when needed. Using too much can make your code complicated and sometimes slower!</p><h4>When NOT to use:</h4><ul><li>Small components</li><li>Simple calculations</li><li>If rendering is already fast</li></ul><h3>Real Example: All Together!</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b29b9b7e6134711966ab434fd5355875/href">https://medium.com/media/b29b9b7e6134711966ab434fd5355875/href</a></iframe><h4>Summary</h4><ol><li><strong>React.memo</strong> = Saves components</li><li><strong>useMemo</strong> = Saves calculation results</li><li><strong>useCallback</strong> = Saves functions</li></ol><p>All three help make your React app faster by avoiding unnecessary work!</p><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2642fa0ef2b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing the Same Conditional Logic Over and Over — Build Reusable Components Instead]]></title>
            <link>https://medium.com/@kom50/stop-writing-the-same-conditional-logic-over-and-over-build-reusable-components-instead-454cd15a607c?source=rss-f50e58802a25------2</link>
            <guid isPermaLink="false">https://medium.com/p/454cd15a607c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[conditional-rendering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[om prakash]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 05:32:14 GMT</pubDate>
            <atom:updated>2025-12-01T06:52:09.540Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Writing the Same Conditional Logic Over and Over — Build Reusable Components Instead</h3><h4>A practical guide to creating declarative, reusable conditional components that will make your React code cleaner and more maintainable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wsY7QFKgg-83qsUoArsZg.png" /></figure><p>You know that feeling when you’re writing the same {isLoading ? &lt;Spinner /&gt; : ...} pattern for the hundredth time?</p><p>Yeah, me too.</p><p>After reviewing hundreds of React codebases, I’ve noticed something: we’re all solving the same problems differently. One component uses ternary operators, another uses if/else statements, and yet another has some wild nested conditionals that make you question your life choices.</p><p>What if I told you there’s a better way?</p><p>Let me show you how to create reusable conditional rendering components that will make your code look like this:</p><pre>&lt;Show when={isLoggedIn} fallback={&lt;Login /&gt;}&gt;<br>  &lt;Dashboard /&gt;<br>&lt;/Show&gt;</pre><p>Instead of this:</p><pre>{isLoading ? (<br>  &lt;Spinner /&gt;<br>) : error ? (<br>  &lt;Error message={error} /&gt;<br>) : !data ? (<br>  &lt;EmptyState /&gt;<br>) : (<br>  &lt;DataDisplay data={data} /&gt;<br>)}</pre><p>Cleaner, right? Let’s dive in.</p><h3>The Problem We’re Solving</h3><p>Here’s a typical React component I found in a production codebase (names changed to protect the innocent):</p><pre>function UserDashboard() {<br>  const { user, isLoading, error } = useUser();<br>  <br>  if (isLoading) {<br>    return &lt;div className=&quot;spinner&quot;&gt;&lt;Spinner /&gt;&lt;/div&gt;;<br>  }<br>  <br>  if (error) {<br>    return &lt;div className=&quot;error&quot;&gt;&lt;ErrorMessage error={error} /&gt;&lt;/div&gt;;<br>  }<br>  <br>  if (!user) {<br>    return &lt;div className=&quot;empty&quot;&gt;&lt;Login /&gt;&lt;/div&gt;;<br>  }<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome, {user.name}&lt;/h1&gt;<br>      {user.isPremium ? (<br>        &lt;PremiumDashboard /&gt;<br>      ) : (<br>        &lt;FreeDashboard /&gt;<br>      )}<br>      {user.notifications.length &gt; 0 &amp;&amp; (<br>        &lt;NotificationBadge count={user.notifications.length} /&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Nothing terrible here, but imagine this pattern repeated across 50+ components. The inconsistency compounds.</p><p>Let’s fix this.</p><h3>1. The &lt;Show&gt; Component</h3><p>This is the simplest and most useful component you’ll build. It handles the most common case: show something when a condition is true.</p><pre>function Show({ when, fallback = null, children }) {<br>  return when ? children : fallback;<br>}</pre><p>That’s it. Three lines of code that will save you hundreds.</p><h4>How to use it:</h4><pre>// Simple visibility<br>&lt;Show when={isLoggedIn}&gt;<br>  &lt;Dashboard /&gt;<br>&lt;/Show&gt;<br><br>// With fallback<br>&lt;Show when={user} fallback={&lt;Login /&gt;}&gt;<br>  &lt;Profile user={user} /&gt;<br>&lt;/Show&gt;<br><br>// No more &amp;&amp; gotchas<br>&lt;Show when={items.length &gt; 0}&gt;<br>  &lt;ItemList items={items} /&gt;<br>&lt;/Show&gt;</pre><blockquote>“<strong>Pro tip</strong>: The when prop accepts any <strong>truthy</strong>/<strong>falsy</strong> value, so you can pass objects, arrays, or booleans directly.”</blockquote><h4>Why this is better:</h4><p>✅ Declarative — reads like plain English<br>✅ Consistent — same pattern everywhere<br>✅ No more 0 rendering on screen — explicit fallback handling<br>✅ Easy to test — simple, predictable behavior</p><h3>2. The &lt;Visible&gt; Component</h3><p>For CSS-Based Conditional Rendering</p><pre>function Visible({ when, keepMounted = false, children }) {<br>  if (!keepMounted &amp;&amp; !when) {<br>    return null;<br>  }<br><br>  return (<br>    &lt;div style={{ display: when ? &#39;block&#39; : &#39;none&#39; }}&gt;<br>      {children}<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Usage<br>&lt;Visible when={showModal}&gt;<br>  &lt;Modal /&gt;<br>&lt;/Visible&gt;<br><br>// Keep in DOM but hide (useful for animations)<br>&lt;Visible when={isExpanded} keepMounted&gt;<br>  &lt;ExpandedContent /&gt;<br>&lt;/Visible&gt;</pre><h3>3. The &lt;If&gt; / &lt;Else&gt; Component</h3><p>More Readable Syntax</p><pre>function If({ condition, children }) {<br>  return condition ? children : null;<br>}<br><br>function Else({ children }) {<br>  return children;<br>}<br><br>// Helper to make If/Else work together<br>function Conditional({ condition, children }) {<br>  const childrenArray = React.Children.toArray(children);<br>  <br>  if (condition) {<br>    return childrenArray.find(child =&gt; child.type === If) || null;<br>  } else {<br>    return childrenArray.find(child =&gt; child.type === Else) || null;<br>  }<br>}<br><br>// Usage<br>&lt;Conditional condition={isLoggedIn}&gt;<br>  &lt;If&gt;<br>    &lt;Dashboard /&gt;<br>  &lt;/If&gt;<br>  &lt;Else&gt;<br>    &lt;Login /&gt;<br>  &lt;/Else&gt;<br>&lt;/Conditional&gt;</pre><p>Better Alternative — Simple Version:</p><pre>function When({ condition, children }) {<br>  return condition ? children : null;<br>}<br><br>function Otherwise({ children }) {<br>  return children;<br>}<br><br>function Choose({ children }) {<br>  let whenChild = null;<br>  let otherwiseChild = null;<br><br>  React.Children.forEach(children, child =&gt; {<br>    if (child.type === When &amp;&amp; !whenChild &amp;&amp; child.props.condition) {<br>      whenChild = child;<br>    } else if (child.type === Otherwise) {<br>      otherwiseChild = child;<br>    }<br>  });<br><br>  return whenChild || otherwiseChild || null;<br>}<br><br>// Usage<br>&lt;Choose&gt;<br>  &lt;When condition={user.role === &#39;admin&#39;}&gt;<br>    &lt;AdminPanel /&gt;<br>  &lt;/When&gt;<br>  &lt;When condition={user.role === &#39;moderator&#39;}&gt;<br>    &lt;ModPanel /&gt;<br>  &lt;/When&gt;<br>  &lt;Otherwise&gt;<br>    &lt;UserPanel /&gt;<br>  &lt;/Otherwise&gt;<br>&lt;/Choose&gt;</pre><h3>4. The &lt;Switch&gt; Component — For Multiple Conditions</h3><p>Remember writing code like this?</p><pre>{status === &#39;idle&#39; &amp;&amp; &lt;Idle /&gt;}<br>{status === &#39;loading&#39; &amp;&amp; &lt;Loading /&gt;}<br>{status === &#39;success&#39; &amp;&amp; &lt;Success /&gt;}<br>{status === &#39;error&#39; &amp;&amp; &lt;Error /&gt;}</pre><p>Or even worse:</p><pre>{status === &#39;idle&#39; ? &lt;Idle /&gt; : <br> status === &#39;loading&#39; ? &lt;Loading /&gt; :<br> status === &#39;success&#39; ? &lt;Success /&gt; :<br> status === &#39;error&#39; ? &lt;Error /&gt; : null}</pre><p>There’s a better way:</p><pre>function Switch({ value, children }) {<br>  let matchedChild = null;<br>  let defaultChild = null;<br><br>  React.Children.forEach(children, child =&gt; {<br>    if (!matchedChild &amp;&amp; React.isValidElement(child)) {<br>      if (child.props.value === value) {<br>        matchedChild = child;<br>      } else if (child.props.default) {<br>        defaultChild = child;<br>      }<br>    }<br>  });<br><br>  return matchedChild || defaultChild || null;<br>}<br><br>function Case({ children }) {<br>  return children;<br>}</pre><p><strong>Usage:</strong></p><pre>&lt;Switch value={userRole}&gt;<br>  &lt;Case value=&quot;admin&quot;&gt;<br>    &lt;AdminDashboard /&gt;<br>  &lt;/Case&gt;<br>  &lt;Case value=&quot;moderator&quot;&gt;<br>    &lt;ModDashboard /&gt;<br>  &lt;/Case&gt;<br>  &lt;Case value=&quot;user&quot;&gt;<br>    &lt;UserDashboard /&gt;<br>  &lt;/Case&gt;<br>  &lt;Case default&gt;<br>    &lt;GuestView /&gt;<br>  &lt;/Case&gt;<br>&lt;/Switch&gt;</pre><h3>5. The &lt;Authenticated&gt; Component — Guard Your Routes</h3><p>Authentication checks are everywhere. Let’s make them consistent:</p><pre>function Authenticated({ <br>  fallback = &lt;LoginPage /&gt;, <br>  loading = &lt;Spinner /&gt;,<br>  children <br>}) {<br>  const { user, isLoading } = useAuth();<br><br>  if (isLoading) return loading;<br>  if (!user) return fallback;<br><br>  // Support render props to access user data<br>  return typeof children === &#39;function&#39; ? children(user) : children;<br>}</pre><p>How you’ll use it:</p><pre>function App() {<br>  return (<br>    &lt;Authenticated fallback={&lt;Login /&gt;} loading={&lt;AppLoading /&gt;}&gt;<br>      {(user) =&gt; (<br>        &lt;&gt;<br>          &lt;Header user={user} /&gt;<br>          &lt;Dashboard userId={user.id} /&gt;<br>        &lt;/&gt;<br>      )}<br>    &lt;/Authenticated&gt;<br>  );<br>}</pre><p>No more useAuth() in every component. No more forgetting to check isLoading. Just wrap and go.</p><h3>6. The &lt;Guard&gt; Component — Permission-Based Rendering</h3><p>Need to hide features based on user permissions? This one’s for you:</p><pre>function Guard({ <br>  requires, <br>  fallback = &lt;AccessDenied /&gt;, <br>  loading = &lt;Spinner /&gt;,<br>  children <br>}) {<br>  const { user, isLoading } = useAuth();<br><br>  if (isLoading) return loading;<br>  if (!user) return fallback;<br><br>  // Single permission<br>  if (typeof requires === &#39;string&#39;) {<br>    return user.permissions?.includes(requires) ? children : fallback;<br>  }<br><br>  // Multiple permissions (user needs ANY of them)<br>  if (Array.isArray(requires)) {<br>    const hasPermission = requires.some(perm =&gt; <br>      user.permissions?.includes(perm)<br>    );<br>    return hasPermission ? children : fallback;<br>  }<br><br>  return children;<br>}</pre><p><strong>Usage</strong></p><pre>&lt;Guard requires=&quot;admin&quot;&gt;<br>  &lt;DeleteButton /&gt;<br>&lt;/Guard&gt;<br><br>&lt;Guard requires={[&#39;editor&#39;, &#39;admin&#39;]} fallback={&lt;UpgradePrompt /&gt;}&gt;<br>  &lt;EditArticleButton /&gt;<br>&lt;/Guard&gt;</pre><h3>7. The &lt;DataState&gt; Component — Because We All Fetch Data</h3><p>If you’re fetching data (and who isn’t?), you need this component in your life.</p><p>Here’s the pattern we’re always writing:</p><pre>if (isLoading) return &lt;Spinner /&gt;;<br>if (error) return &lt;Error /&gt;;<br>if (!data) return &lt;Empty /&gt;;<br>return &lt;Display data={data} /&gt;;</pre><p>Let’s turn that into a component:</p><pre>function DataState({ <br>  data, <br>  isLoading, <br>  error, <br>  loadingComponent = &lt;DefaultSpinner /&gt;,<br>  errorComponent,<br>  emptyComponent = &lt;EmptyState /&gt;,<br>  children <br>}) {<br>  if (isLoading) return loadingComponent;<br>  <br>  if (error) {<br>    return errorComponent || &lt;ErrorDisplay error={error} /&gt;;<br>  }<br>  <br>  if (!data || (Array.isArray(data) &amp;&amp; data.length === 0)) {<br>    return emptyComponent;<br>  }<br>  <br>  // Support render props for accessing data<br>  return typeof children === &#39;function&#39; ? children(data) : children;<br>}</pre><p><strong>Usage:</strong></p><pre>function BlogPosts() {<br>  const { posts, isLoading, error } = usePosts();<br>  <br>  return (<br>    &lt;DataState<br>      data={posts}<br>      isLoading={isLoading}<br>      error={error}<br>      loadingComponent={&lt;PostsSkeleton /&gt;}<br>      errorComponent={&lt;ErrorMessage error={error} /&gt;}<br>      emptyComponent={&lt;NoPosts /&gt;}<br>    &gt;<br>      {(posts) =&gt; &lt;PostList posts={posts} /&gt;}<br>    &lt;/DataState&gt;<br>  );<br>}</pre><h3>8. The &lt;ConditionalWrapper&gt; Component — The Secret Weapon</h3><p>Sometimes you need to conditionally wrap children with a component (like a link or tooltip):</p><pre>function ConditionalWrapper({ condition, wrapper, children }) {<br>  return condition ? wrapper(children) : children;<br>}</pre><p><strong>Usage:</strong></p><pre>// Make images clickable only when there&#39;s a link<br>&lt;ConditionalWrapper<br>  condition={hasLink}<br>  wrapper={(children) =&gt; &lt;a href={url}&gt;{children}&lt;/a&gt;}<br>&gt;<br>  &lt;img src={imageSrc} alt={alt} /&gt;<br>&lt;/ConditionalWrapper&gt;<br><br>// Add tooltip only for disabled buttons<br>&lt;ConditionalWrapper<br>  condition={isDisabled}<br>  wrapper={(children) =&gt; (<br>    &lt;Tooltip content=&quot;You need premium to access this&quot;&gt;<br>      {children}<br>    &lt;/Tooltip&gt;<br>  )}<br>&gt;<br>  &lt;Button disabled={isDisabled}&gt;Premium Feature&lt;/Button&gt;<br>&lt;/ConditionalWrapper&gt;</pre><p>No more duplicating the child component in both branches!</p><h4>Your Starter Kit — Copy, Paste, Ship</h4><p>Here’s a complete Conditional.jsx file you can drop into any project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd9bb89ed9dcdc577e881be696466d12/href">https://medium.com/media/cd9bb89ed9dcdc577e881be696466d12/href</a></iframe><h4>TypeScript? I Got You.</h4><p>Here’s the fully typed version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2da6e88d51d343050ee0554abaf57e6b/href">https://medium.com/media/2da6e88d51d343050ee0554abaf57e6b/href</a></iframe><h4>Best Practices I’ve Learned the Hard Way</h4><h4>✅ DO:</h4><pre>// Keep components simple and focused<br>&lt;Show when={isLoggedIn}&gt;<br>  &lt;Dashboard /&gt;<br>&lt;/Show&gt;<br><br>// Use render props for data access<br>&lt;DataState data={users}&gt;<br>  {(users) =&gt; &lt;UserList users={users} /&gt;}<br>&lt;/DataState&gt;<br><br>// Provide meaningful fallbacks<br>&lt;Show when={user} fallback={&lt;LoginPrompt /&gt;}&gt;<br>  &lt;UserProfile /&gt;<br>&lt;/Show&gt;</pre><h4><strong>❌ DON&#39;T:</strong></h4><pre>// Don&#39;t over-complicate<br>&lt;Show when={isLoggedIn}&gt;<br>  &lt;Show when={isPremium}&gt;<br>    &lt;Show when={hasAccess}&gt;<br>      &lt;Content /&gt; {/* Too nested! */}<br>    &lt;/Show&gt;<br>  &lt;/Show&gt;<br>&lt;/Show&gt;<br><br>// Don&#39;t use when regular conditionals are clearer<br>&lt;Show when={true}&gt;  {/* Just render it! */}<br>  &lt;Component /&gt;<br>&lt;/Show&gt;</pre><h4>Conclusion</h4><p>Creating reusable conditional rendering components:</p><p>✅ Makes code more declarative and readable<br>✅ Reduces duplication across your app<br>✅ Provides consistent patterns for your team<br>✅ Makes refactoring easier<br>✅ Improves testability</p><p>Start with these three:</p><ol><li>&lt;Show&gt; - for simple conditionals</li><li>&lt;DataState&gt; - for API data</li><li>&lt;Switch&gt;/&lt;Case&gt; - for multiple conditions</li></ol><p>Thanks for reading!</p><p>If you found this useful, please clap 👏, share this, and leave a comment below.</p><p>You can also follow me on <a href="https://github.com/kom50"><strong>GitHub</strong></a> and <a href="https://www.linkedin.com/in/om-prakash-sah"><strong>LinkedIn</strong></a><strong> </strong>for more updates.</p><p><strong>Happy coding!</strong> 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=454cd15a607c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>