<?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 Bhargav Gandhi on Medium]]></title>
        <description><![CDATA[Stories by Bhargav Gandhi on Medium]]></description>
        <link>https://medium.com/@bhargavgandhi?source=rss-3d81c0ff80ca------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*r2pstKl2oVpYcLih.</url>
            <title>Stories by Bhargav Gandhi on Medium</title>
            <link>https://medium.com/@bhargavgandhi?source=rss-3d81c0ff80ca------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:08:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bhargavgandhi/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[Advanced React patterns and performance: what actually matters]]></title>
            <link>https://medium.com/@bhargavgandhi/advanced-react-patterns-and-performance-what-actually-matters-e5b09920a215?source=rss-3d81c0ff80ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5b09920a215</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Bhargav Gandhi]]></dc:creator>
            <pubDate>Sat, 21 Mar 2026 04:34:46 GMT</pubDate>
            <atom:updated>2026-03-21T04:34:46.943Z</atom:updated>
            <content:encoded><![CDATA[<p>Most React tutorials stop at useState and useEffect. That&#39;s fine for getting started, but at some point you&#39;re staring at a profiler trace showing 400ms renders on a component that wraps a button, and the tutorial isn&#39;t going to save you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qbP3KaDzAsiS-qXl5W7i_g.png" /></figure><p>This post covers the patterns that separate workable React code from React code that holds up at scale. Not theory — working decisions, with the trade-offs included.</p><h3>1. Memoization: use it less than you think</h3><p>React.memo, useMemo, and useCallback exist to prevent unnecessary re-renders. The mistake most developers make is treating them as free performance wins. They aren&#39;t.</p><p>Every memoized value adds a dependency comparison on every render. If your component renders cheaply, that comparison costs more than the re-render you’re preventing. Memoization is worth it when components receive stable props but re-render because a parent re-renders frequently, when calculations are genuinely expensive (sorting or filtering large datasets, deriving complex state), or when callbacks are passed to deeply nested children that use referential equality checks. It’s not worth it for primitive props (React compares those by value anyway), components that render infrequently regardless, or simple JSX trees that React can reconcile in under a millisecond.</p><p>Here’s the classic mistake:</p><pre>// Adds comparison overhead with no real benefit<br>const Button = React.memo(({ label, onClick }: { label: string; onClick: () =&gt; void }) =&gt; (<br>  &lt;button onClick={onClick}&gt;{label}&lt;/button&gt;<br>));</pre><pre>function Parent() {<br>  const handleClick = useCallback(() =&gt; {<br>    console.log(&#39;clicked&#39;);<br>  }, []);</pre><pre>  return &lt;Button label=&quot;Submit&quot; onClick={handleClick} /&gt;;<br>}</pre><p>The button re-renders in microseconds. React.memo here is cargo cult optimization.</p><p>Here’s a case where it earns its keep:</p><pre>// A table row inside a frequently-updating parent<br>const DataRow = React.memo(({ row }: { row: RowData }) =&gt; {<br>  return (<br>    &lt;tr&gt;<br>      &lt;td&gt;{row.name}&lt;/td&gt;<br>      &lt;td&gt;{row.value}&lt;/td&gt;<br>      &lt;td&gt;&lt;StatusBadge status={row.status} /&gt;&lt;/td&gt;<br>    &lt;/tr&gt;<br>  );<br>}, (prevProps, nextProps) =&gt; {<br>  // Custom comparison — only re-render if the row data actually changed<br>  return prevProps.row.id === nextProps.row.id &amp;&amp; prevProps.row.updatedAt === nextProps.row.updatedAt;<br>});</pre><p>The custom comparator lets you skip deep equality checks when you know exactly which fields matter.</p><p>Reach for the profiler before you reach for memo. Optimizing unmeasured code is guessing.</p><h3>2. State placement is the real performance lever</h3><p>Most unnecessary re-renders aren’t a memoization problem. They’re a state placement problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*-T3c5oFOdvtQ_B1B6c_mow.png" /></figure><p>State that lives high in the tree re-renders everything below it. If you put your modal’s isOpen flag in your root layout component, every modal toggle re-renders your entire app.</p><pre>// isOpen lives in the parent — Sidebar and MainContent re-render on every toggle<br>function Dashboard() {<br>  const [isModalOpen, setIsModalOpen] = useState(false);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;Sidebar /&gt;<br>      &lt;MainContent /&gt;<br>      &lt;button onClick={() =&gt; setIsModalOpen(true)}&gt;Open&lt;/button&gt;<br>      {isModalOpen &amp;&amp; &lt;Modal onClose={() =&gt; setIsModalOpen(false)} /&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>// State lives in the component that actually needs it<br>function ModalTrigger() {<br>  const [isOpen, setIsOpen] = useState(false);</pre><pre>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; setIsOpen(true)}&gt;Open&lt;/button&gt;<br>      {isOpen &amp;&amp; &lt;Modal onClose={() =&gt; setIsOpen(false)} /&gt;}<br>    &lt;/&gt;<br>  );<br>}</pre><pre>function Dashboard() {<br>  return (<br>    &lt;div&gt;<br>      &lt;Sidebar /&gt;<br>      &lt;MainContent /&gt;<br>      &lt;ModalTrigger /&gt; {/* only this subtree re-renders on toggle */}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Same behavior, much smaller re-render surface. When state does need to go up, lift it only as far as the lowest common ancestor of the components that need it — no higher.</p><h3>3. Context is not a state manager</h3><p>React.Context is useful for passing stable values through the component tree without prop drilling — theme, locale, the current user. It isn&#39;t designed for frequently-changing state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHuvMlwKCdFIjEwREN8Wjg.png" /></figure><p>When a context value changes, every component consuming that context re-renders, even if it only uses a subset of the value.</p><pre>// Every consumer re-renders on ANY change to this object,<br>// even if the component only reads `theme`<br>const AppContext = createContext&lt;{<br>  theme: string;<br>  user: User;<br>  notifications: Notification[];<br>  sidebarOpen: boolean;<br>}&gt;(null!);</pre><p>The fix is to split context by update frequency:</p><pre>// Stable values — theme and user change rarely<br>const ThemeContext = createContext&lt;{ theme: string }&gt;(null!);<br>const UserContext = createContext&lt;{ user: User }&gt;(null!);</pre><pre>// Volatile values — isolated so only notification consumers re-render<br>const NotificationContext = createContext&lt;{<br>  notifications: Notification[];<br>  addNotification: (n: Notification) =&gt; void;<br>}&gt;(null!);</pre><p>For anything that updates frequently — form state, UI state, real-time data — use a purpose-built solution: Zustand, Jotai, or Redux Toolkit. Context wasn’t built for that job.</p><h3>4. Derived state belongs in useMemo, not useState</h3><p>One of the most common sources of bugs and stale state is storing derived values in state:</p><pre>// filteredItems must be kept in sync with items and query manually<br>function SearchableList({ items }: { items: Item[] }) {<br>  const [query, setQuery] = useState(&#39;&#39;);<br>  const [filteredItems, setFilteredItems] = useState(items);</pre><pre>  useEffect(() =&gt; {<br>    setFilteredItems(items.filter(item =&gt; item.name.includes(query)));<br>  }, [items, query]);</pre><pre>  return &lt;List items={filteredItems} /&gt;;<br>}</pre><p>This triggers two renders for every filter: one when query changes, one when the effect fires and sets filteredItems. It also opens the door to stale state bugs.</p><pre>// Derive it during render, memoize if the list is large<br>function SearchableList({ items }: { items: Item[] }) {<br>  const [query, setQuery] = useState(&#39;&#39;);</pre><pre>  const filteredItems = useMemo(<br>    () =&gt; items.filter(item =&gt; item.name.toLowerCase().includes(query.toLowerCase())),<br>    [items, query]<br>  );</pre><pre>  return &lt;List items={filteredItems} /&gt;;<br>}</pre><p>One render per change, no sync logic, no stale state risk. The useMemo wrapper is only worth adding if items is large — for small arrays, the inline filter is fine without it.</p><h3>5. Code splitting with React.lazy and Suspense</h3><p>The fastest code is code that doesn’t load. React.lazy defers loading a component&#39;s bundle until it&#39;s actually rendered.</p><pre>import { lazy, Suspense } from &#39;react&#39;;</pre><pre>// The chart library only loads when ChartView is actually rendered<br>const ChartView = lazy(() =&gt; import(&#39;./ChartView&#39;));</pre><pre>function Dashboard() {<br>  const [tab, setTab] = useState&lt;&#39;table&#39; | &#39;chart&#39;&gt;(&#39;table&#39;);</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;TabBar current={tab} onChange={setTab} /&gt;</pre><pre>      {tab === &#39;table&#39; &amp;&amp; &lt;DataTable /&gt;}</pre><pre>      {tab === &#39;chart&#39; &amp;&amp; (<br>        &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>          &lt;ChartView /&gt;<br>        &lt;/Suspense&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The chart bundle — Recharts, D3, or whatever you’re using — won’t be requested until the user switches to that tab. For users who never do, those bytes are never downloaded.</p><p>You can nest Suspense boundaries to control loading granularity. A boundary closer to the lazy component gives you a more targeted fallback, so an unrelated part of the UI doesn&#39;t go into a loading state because one chart is fetching.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7WTOIUx-Ofp88zBOUZUVdQ.png" /></figure><h3>6. useEffect: the smaller, the better</h3><p>useEffect is where a lot of performance problems hide, mostly because it encourages doing more than you need to.</p><p>Skip effects for synchronous derivations. If you can compute something during render, do it there — the derived state section above is the canonical example.</p><p>Cleanup is not optional. Any effect that sets up a subscription, timer, or event listener needs to return a cleanup function:</p><pre>// Will keep firing after unmount<br>useEffect(() =&gt; {<br>  const interval = setInterval(fetchLatestData, 5000);<br>}, []);</pre><pre>// Safe<br>useEffect(() =&gt; {<br>  const interval = setInterval(fetchLatestData, 5000);<br>  return () =&gt; clearInterval(interval);<br>}, []);</pre><p>Separate effects by concern. One effect doing three unrelated things is harder to reason about and harder to clean up correctly:</p><pre>// Two unrelated concerns tangled together<br>useEffect(() =&gt; {<br>  document.title = `${user.name} — Dashboard`;</pre><pre>  const socket = openSocket(user.id);<br>  socket.on(&#39;update&#39;, handleUpdate);</pre><pre>  return () =&gt; {<br>    socket.disconnect();<br>  };<br>}, [user.id, user.name]);</pre><pre>// One concern per effect<br>useEffect(() =&gt; {<br>  document.title = `${user.name} — Dashboard`;<br>}, [user.name]);</pre><pre>useEffect(() =&gt; {<br>  const socket = openSocket(user.id);<br>  socket.on(&#39;update&#39;, handleUpdate);<br>  return () =&gt; socket.disconnect();<br>}, [user.id]);</pre><p>The second version lets each effect have its own dependency array, its own cleanup, and its own reason to exist.</p><h3>7. Virtualize long lists</h3><p>Rendering 1,000 DOM nodes because a list has 1,000 items looks fine in development and tanks production. If you’re rendering a long, scrollable list, only the visible items need to exist in the DOM.</p><p>react-window handles this well:</p><pre>import { FixedSizeList } from &#39;react-window&#39;;</pre><pre>function VirtualizedTable({ rows }: { rows: Row[] }) {<br>  const Row = ({ index, style }: { index: number; style: React.CSSProperties }) =&gt; (<br>    &lt;div style={style}&gt;<br>      &lt;DataRow row={rows[index]} /&gt;<br>    &lt;/div&gt;<br>  );</pre><pre>  return (<br>    &lt;FixedSizeList<br>      height={600}<br>      itemCount={rows.length}<br>      itemSize={52}<br>      width=&quot;100%&quot;<br>    &gt;<br>      {Row}<br>    &lt;/FixedSizeList&gt;<br>  );<br>}</pre><p>At any point, only the visible rows plus a small overscan buffer exist in the DOM. Scroll performance stays constant whether the list has 100 items or 100,000.</p><p>For dynamic item heights, use VariableSizeList. For grids, react-window includes FixedSizeGrid and VariableSizeGrid.</p><h3>8. Measure before you optimize</h3><p>React DevTools includes a Profiler that records what rendered, why it rendered, and how long it took. Use it before touching any of the above.</p><p>Three questions worth answering from every profile: what is rendering (look for components rendering frequently that you didn’t expect), why it’s rendering (the profiler distinguishes prop changes, state changes, and context updates), and how long it’s taking (renders over ~16ms are where you drop below 60fps).</p><pre>import { Profiler } from &#39;react&#39;;</pre><pre>function onRenderCallback(<br>  id: string,<br>  phase: &#39;mount&#39; | &#39;update&#39;,<br>  actualDuration: number,<br>) {<br>  if (actualDuration &gt; 16) {<br>    console.warn(`Slow render in ${id}: ${actualDuration.toFixed(1)}ms (${phase})`);<br>  }<br>}</pre><pre>function App() {<br>  return (<br>    &lt;Profiler id=&quot;Dashboard&quot; onRender={onRenderCallback}&gt;<br>      &lt;Dashboard /&gt;<br>    &lt;/Profiler&gt;<br>  );<br>}</pre><p>This logs any render over 16ms in development — useful for catching regressions before they ship, without waiting for a user to report sluggishness.</p><h3>The short version</h3><p>React performance problems almost always trace back to the same causes: state too high in the tree, derived values stored as state, context updating too often, and rendering more than needs to be rendered. Memoization helps, but it rarely fixes the root issue.</p><p>Keep state close to where it’s used. Compute, don’t store. Measure before you optimize. If you haven’t opened the React Profiler yet, that’s the first step.</p><p>Source: <a href="https://www.bhargavgandhi.com/blog/advanced-react-patterns-performance">Advanced React Patterns and Performances</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5b09920a215" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[First Post on Medium]]></title>
            <link>https://medium.com/@bhargavgandhi/first-post-on-medium-972ab8221a78?source=rss-3d81c0ff80ca------2</link>
            <guid isPermaLink="false">https://medium.com/p/972ab8221a78</guid>
            <category><![CDATA[html5]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[first-post]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Bhargav Gandhi]]></dc:creator>
            <pubDate>Thu, 08 Dec 2016 17:26:15 GMT</pubDate>
            <atom:updated>2016-12-08T17:26:15.640Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi Folks!</p><p>This is my first post on Medium and Hi to everyone out there. To little to know about me, I’m a Front End Developer and with some supplementary skills to name a few such as novice in Back-End technology, Social Media and Video editing, proficient in Search Engine Optimization tactics and teaching.</p><p>Enjoy this Codepen CSS animation for Medium Logo in Blue :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fbhargavgandhi%2Fembed%2Fpreview%2FrWKdxz%3Fheight%3D600%26amp%3Bslug-hash%3DrWKdxz%26amp%3Bdefault-tabs%3Dcss%2Cresult%26amp%3Bhost%3Dhttp%253A%252F%252Fcodepen.io%26amp%3Bembed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fbhargavgandhi%2Ffull%2FrWKdxz%2F&amp;image=http%3A%2F%2Fcodepen.io%2Fbhargavgandhi%2Fpen%2FrWKdxz%2Fimage%2Flarge.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4d7b2c103e036e53e47f9da86e7d1c6/href">https://medium.com/media/e4d7b2c103e036e53e47f9da86e7d1c6/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=972ab8221a78" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>