<?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 Vikash Yadav on Medium]]></title>
        <description><![CDATA[Stories by Vikash Yadav on Medium]]></description>
        <link>https://medium.com/@vikash_yadav_41088?source=rss-5c24637cd9bc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YTzdvI7q_ZdKL_J-_0xxnw.png</url>
            <title>Stories by Vikash Yadav on Medium</title>
            <link>https://medium.com/@vikash_yadav_41088?source=rss-5c24637cd9bc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 01:00:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikash_yadav_41088/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[React Update Priorities: Why Some Updates Are More Important Than Others]]></title>
            <link>https://medium.com/the-code-frontier/react-update-priorities-why-some-updates-are-more-important-than-others-5c2ea42c2453?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c2ea42c2453</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Tue, 06 Oct 2026 02:49:32 GMT</pubDate>
            <atom:updated>2026-10-06T02:50:06.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o_X6aRXn07QCuK_vrWAenA.png" /><figcaption>Image generated by the author using ChatGPT (DALL·E) to illustrate React’s update priorities, scheduling, and transition model.</figcaption></figure><p>There was a time while learning React internal workings, I started thinking about state updates in a very simple way:</p><pre>setState(...)</pre><p>State changes.</p><p>React re-renders.</p><p>The UI updates.</p><p>That mental model works for small applications not for a big enterprise application. But once you start looking at what React is actually doing, another question appears:</p><p><strong>What if several things need to update at the same time?</strong></p><p>Imagine a page where the user is typing into a search box while React is also filtering a list containing thousands of items.</p><p>The user expects the text they’re typing to appear immediately.</p><p>The filtered list, on the other hand, can take a little longer.</p><p>If React treated both pieces of work exactly the same way, an expensive render could make the input feel slow.</p><p>So React needs a way to say:</p><blockquote><em>“This update is directly related to what the user is doing right now. Deal with it first.”</em></blockquote><p>And:</p><blockquote><em>“This update matters too, but it doesn’t need to block the user.”</em></blockquote><p>This is where <strong>update priorities, scheduling, transitions, and concurrent rendering</strong> start to make sense.</p><h3>Not Every Update Has the Same Urgency</h3><p>Consider a search interface:</p><pre>function SearchPage() {<br>  const [query, setQuery] = useState(&#39;&#39;);<br>  const [results, setResults] = useState([]);<br>  <br>  function handleChange(e) {<br>    setQuery(e.target.value);<br>    const filtered = expensiveFilter(e.target.value);<br>    setResults(filtered);<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        value={query}<br>        onChange={handleChange}<br>      /&gt;<br>      &lt;ResultsList results={results} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>There are two things happening here.</p><p>First:</p><pre>setQuery(e.target.value);</pre><p>The user is typing.</p><p>They expect the input to respond immediately.</p><p>Second:</p><pre>setResults(filtered);</pre><p>React needs to update a potentially expensive part of the UI.</p><p>That work is important, but it doesn’t necessarily need to block the input.</p><p>This gives us two different kinds of work:</p><pre>User interaction<br>      |<br>      v<br>Update input<br>      |<br>      |  urgent<br>      v<br>Keep typing responsive<br><br>Expensive filtering<br>      |<br>      v<br>Update results<br>      |<br>      |  can be interrupted<br>      v<br>Render when possible</pre><p>This is the basic idea behind React’s modern scheduling model.</p><p>React can prioritize work instead of treating every update as equally urgent. The public APIs that let developers express this include startTransition, useTransition, and useDeferredValue.</p><h3>But Doesn’t React Already Batch Updates?</h3><p>Yes.</p><p>And this distinction is important.</p><p>In the previous article, we looked at <strong>batching</strong>.</p><p>Batching answers a question like:</p><blockquote><em>“Can React process these multiple updates together instead of rendering after each one?”</em></blockquote><p>Prioritization asks a different question:</p><blockquote><em>“If React has different pieces of work to process, which work should get attention first?”</em></blockquote><p>For example:</p><pre>Batching<br>-------<br>Update A<br>Update B<br>Update C<br>      |<br>      v<br>Process together</pre><p>Prioritization:</p><pre>Update A → urgent<br>Update B → non-urgent<br>Update C → urgent<br>        |<br>        v<br>React can prioritize the urgent work</pre><p>So batching and prioritization are related, but they solve different problems.</p><p><strong>Batching reduces unnecessary work.</strong></p><p><strong>Prioritization helps React decide which work should happen first.</strong></p><h3>What Does “Priority” Actually Mean in React?</h3><p>This is where React’s internal implementation becomes interesting.</p><p>React doesn’t simply maintain a list like:</p><pre>1. Do this first<br>2. Do this second<br>3. Do this third</pre><p>Internally, React represents pending work using a system called <strong>lanes</strong>.</p><p>You can think of a lane as a way of categorizing pending work so React can determine which updates can be processed together and which work should be handled first.</p><p>You don’t normally interact with lanes directly.</p><p>They’re an internal implementation detail.</p><p>But conceptually, you can think of React’s update system like this:</p><pre>State update<br>     |<br>     v<br>React creates/schedules work<br>     |<br>     v<br>Work gets associated with a priority<br>     |<br>     v<br>React chooses what work to process<br>     |<br>     v<br>Render<br>     |<br>     v<br>Commit</pre><p>This is one of the reasons React’s update system is more sophisticated than simply:</p><pre>setState()<br>   ↓<br>render()</pre><p>The actual process involves scheduling work and deciding how that work should be processed.</p><h3>The Problem With Expensive Rendering</h3><p>Let’s make the search example a little more realistic.</p><p>Suppose you have:</p><pre>function SearchPage() {<br>  const [query, setQuery] = useState(&#39;&#39;);<br>  const [results, setResults] = useState([]);<br>  <br>  function handleChange(e) {<br>    const value = e.target.value;<br>    setQuery(value);<br>    setResults(expensiveFilter(value));<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        value={query}<br>        onChange={handleChange}<br>      /&gt;<br>      &lt;LargeResultsList results={results} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now imagine LargeResultsList takes a noticeable amount of time to render.</p><p>The user types:</p><pre>r<br>re<br>rea<br>reac<br>react</pre><p>Each keystroke can cause work that eventually leads to rendering the large results list.</p><p>If that rendering work becomes expensive enough, the input can start feeling sluggish.</p><p>The problem isn’t that React shouldn’t update the results.</p><p>The results still need to update.</p><p>The problem is that <strong>the results don’t need to prevent the user from continuing to type.</strong></p><p>That’s exactly the kind of situation transitions are designed to help with.</p><h3>Enter startTransition</h3><p>React provides:</p><pre>startTransition()</pre><p>to mark state updates as <strong>non-urgent</strong>.</p><p>For example:</p><pre>import { startTransition, useState } from &#39;react&#39;;<br><br>function SearchPage() {<br>  const [query, setQuery] = useState(&#39;&#39;);<br>  const [results, setResults] = useState([]);<br>  function handleChange(e) {<br>    const value = e.target.value;<br>    setQuery(value);<br>    startTransition(() =&gt; {<br>      setResults(expensiveFilter(value));<br>    });<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        value={query}<br>        onChange={handleChange}<br>      /&gt;<br>      &lt;ResultsList results={results} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now we’re telling React something important:</p><pre>setQuery(value);</pre><p>is urgent.</p><p>While:</p><pre>startTransition(() =&gt; {<br>  setResults(...);<br>});</pre><p>is non-urgent work.</p><p>React’s documentation describes Transition updates as non-blocking and interruptible by other updates.</p><p>That doesn’t mean React completely ignores the transition.</p><p>It still needs to finish eventually.</p><p>We’re simply giving React more freedom to prioritize other work when necessary.</p><h3>startTransition Does Not Delay Your Function</h3><p>There is a subtle point here that is easy to misunderstand.</p><p>Consider:</p><pre>console.log(&#39;A&#39;);<br><br>startTransition(() =&gt; {<br>  console.log(&#39;B&#39;);<br>  setCount(count + 1);<br>});<br>console.log(&#39;C&#39;);</pre><p>You don’t get:</p><pre>A<br>C<br>B</pre><p>You get:</p><pre>A<br>B<br>C</pre><p>The callback passed to startTransition runs immediately.</p><p>What changes is how React treats the state updates that happen inside that callback.</p><p>Conceptually:</p><pre>startTransition(...)<br>       |<br>       v<br>Run callback immediately<br>       |<br>       v<br>State update happens<br>       |<br>       v<br>React marks it as Transition work<br>       |<br>       v<br>React can schedule it as non-urgent</pre><p>This distinction matters because startTransition isn&#39;t a JavaScript scheduling mechanism like:</p><pre>setTimeout(...)</pre><p>It doesn’t postpone the execution of your function. It tells React how to treat the updates scheduled inside it.</p><h3>What Does “Interruptible” Mean?</h3><p>This is one of the most useful parts of the model.</p><p>Suppose React is rendering a large chart because of a transition:</p><pre>Transition render<br>-----------------<br><br>Chart<br>Chart<br>Chart<br>Chart<br>Chart<br>...</pre><p>While React is doing that work, the user types something into an input.</p><p>Now React has new urgent work.</p><p>Instead of insisting:</p><blockquote><em>“I started rendering the chart, so I must finish everything before doing anything else.”</em></blockquote><p>React’s concurrent rendering model gives it the ability to interrupt the lower-priority rendering work and handle more urgent work first.</p><p>Conceptually:</p><pre>Start transition<br>       |<br>       v<br>Render expensive UI<br>       |<br>       |<br>       |   User types<br>       v<br>Urgent update arrives<br>       |<br>       v<br>Handle input<br>       |<br>       v<br>Continue/restart transition work</pre><p>React’s documentation explicitly describes Transition updates as interruptible: another state update can interrupt an ongoing Transition render, after which React can restart the rendering work.</p><p>This is one of the ideas that makes <strong>concurrent rendering</strong> useful.</p><h3>Concurrent Rendering Doesn’t Mean Two Renders at Once</h3><p>The word “concurrent” can be confusing.</p><p>It doesn’t mean React is literally rendering two components simultaneously on two CPU threads.</p><p>A better mental model is:</p><blockquote><em>React can work on rendering without assuming that the entire render must finish in one uninterrupted block before it can respond to other work.</em></blockquote><p>For example:</p><pre>Before concurrent rendering<br><br>Start render<br>     |<br>     v<br>████████████████████<br>     |<br>     v<br>Finish<br>     |<br>     v<br>Commit</pre><p>With interruptible work:</p><pre>Start render<br>     |<br>     v<br>██████████<br>     |<br>     | urgent update arrives<br>     v<br>Handle urgent work<br>     |<br>     v<br>Continue/restart transition work<br>     |<br>     v<br>Commit</pre><p>The browser still has to execute JavaScript on its main thread in the usual way.</p><p>The important change is that React’s rendering work can be treated as interruptible rather than one giant, indivisible operation.</p><h3>useTransition</h3><p>There is also a Hook version:</p><pre>const [isPending, startTransition] = useTransition();</pre><p>This gives you two things:</p><pre>isPending<br>startTransition</pre><p>For example:</p><pre>function Tabs() {<br>  const [tab, setTab] = useState(&#39;about&#39;);<br><br>  const [isPending, startTransition] = useTransition();<br>  function selectTab(nextTab) {<br>    startTransition(() =&gt; {<br>      setTab(nextTab);<br>    });<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;button onClick={() =&gt; selectTab(&#39;about&#39;)}&gt;<br>        About<br>      &lt;/button&gt;<br>      &lt;button onClick={() =&gt; selectTab(&#39;posts&#39;)}&gt;<br>        Posts<br>      &lt;/button&gt;<br>      {isPending &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>      &lt;TabContent tab={tab} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>The important difference is that useTransition gives you the isPending value.</p><p>That allows the UI to communicate that the transition hasn’t finished yet.</p><p>React’s documentation also uses this pattern for tabs and navigation, where the current interface can remain responsive while the next view is being prepared.</p><h3>Why Not Put Every Update Inside startTransition?</h3><p>This is where the idea of priority becomes practical.</p><p>You shouldn’t think:</p><blockquote><em>“Transitions make React faster, so I’ll wrap everything in </em><em>startTransition.&quot;</em></blockquote><p>That’s not what they’re for.</p><p>Consider a text input:</p><pre>&lt;input<br>  value={text}<br>  onChange={handleChange}<br>/&gt;</pre><p>The value controlling the input needs to update immediately as the user types.</p><p>React specifically warns that Transition updates should not be used to control text inputs. Instead, you can keep the input state urgent and transition the expensive work that depends on it.</p><p>So this is the wrong mental model:</p><pre>Everything<br>   |<br>   v<br>startTransition()</pre><p>A better model is:</p><pre>User interaction<br>       |<br>       +----&gt; Immediate UI update<br>       |<br>       +----&gt; Expensive derived UI<br>                    |<br>                    v<br>              Transition</pre><h3>A Better Search Example</h3><p>We can now structure our search example properly:</p><pre>function SearchPage() {<br>  const [query, setQuery] = useState(&#39;&#39;);<br>  const [results, setResults] = useState([]);<br><br>  const [isPending, startTransition] = useTransition();<br>  function handleChange(e) {<br>    const value = e.target.value;<br>    // Urgent<br>    setQuery(value);<br>    // Non-urgent<br>    startTransition(() =&gt; {<br>      setResults(expensiveFilter(value));<br>    });<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        value={query}<br>        onChange={handleChange}<br>      /&gt;<br>      {isPending &amp;&amp; &lt;p&gt;Updating results...&lt;/p&gt;}<br>      &lt;ResultsList results={results} /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Now React has more information about what matters.</p><pre>User types<br>    |<br>    v<br>setQuery()<br>    |<br>    v<br>Update input immediately<br><br>    |<br>    v<br>expensiveFilter()<br>    |<br>    v<br>Transition update<br>    |<br>    v<br>Can be interrupted if needed</pre><p>That’s the real value of these APIs.</p><p>You’re not manually controlling React’s scheduler.</p><p>You’re giving React information about the <strong>intent of the update</strong>.</p><h3>What About useDeferredValue?</h3><p>There is another API that solves a closely related problem:</p><pre>useDeferredValue()</pre><p>The difference is mostly about where you want to express the intent.</p><p>With startTransition, you control the state update:</p><pre>startTransition(() =&gt; {<br>  setResults(newResults);<br>});</pre><p>With useDeferredValue, you already have a value and want a non-critical part of the UI to use a deferred version of it.</p><p>For example:</p><pre>function SearchPage({ query }) {<br>  const deferredQuery = useDeferredValue(query);<br><br>  return (<br>    &lt;SearchResults query={deferredQuery} /&gt;<br>  );<br>}</pre><p>The input can continue using the latest query, while the expensive results can use deferredQuery.</p><p>React’s documentation describes useDeferredValue as a way to defer updating a non-critical part of the UI so other updates can happen first.</p><p>A simple way to remember the difference:</p><pre>startTransition<br>&quot;I know which update is non-urgent.&quot;<br><br>useDeferredValue<br>&quot;I already have this value, but this part of the UI<br>doesn&#39;t need the newest version immediately.&quot;</pre><h3>Priority Doesn’t Mean “This Update Is Faster”</h3><p>This is another important distinction.</p><p>Suppose you have:</p><pre>startTransition(() =&gt; {<br>  setResults(data);<br>});</pre><p>It doesn’t make:</p><pre>setResults(data)</pre><p>execute faster.</p><p>The filtering itself might still take 500ms.</p><p>React isn’t magically making the computation cheaper.</p><p>Instead, React gets the ability to keep more important work responsive while that non-urgent work is being processed.</p><p>So:</p><pre>Priority<br>   ≠<br>Faster computation</pre><p>It’s closer to:</p><pre>Priority<br>   =<br>Better control over which work should block the user</pre><p>If your component performs an unnecessarily expensive calculation, you may still need to optimize that calculation.</p><p>Transitions don’t replace normal performance optimization.</p><h3>Where Scheduling Fits Into Everything We’ve Learned</h3><p>At this point, we can connect the previous articles together.</p><p>We’ve already looked at what happens when state changes.</p><p>Now we can extend that mental model.</p><pre>User interaction<br>       |<br>       v<br>setState()<br>       |<br>       v<br>Update gets scheduled<br>       |<br>       v<br>React determines the work to process<br>       |<br>       v<br>Priority / lanes<br>       |<br>       v<br>Render phase<br>       |<br>       +---- can be interrupted for lower-priority work<br>       |<br>       v<br>Reconciliation<br>       |<br>       v<br>Commit phase<br>       |<br>       v<br>DOM updated</pre><p>And batching fits into the same picture:</p><pre>Multiple updates<br>       |<br>       v<br>Batching<br>       |<br>       v<br>Less unnecessary rendering work<br>       |<br>       v<br>Scheduling / prioritization<br>       |<br>       v<br>Render<br>       |<br>       v<br>Commit</pre><p>This is why React’s update system can’t really be understood by looking at setState() alone.</p><p>The setter is only the beginning of the process.</p><h3>One More Thing: React Can Change Its Mind</h3><p>This is probably the biggest shift in mental model.</p><p>With a simple synchronous rendering model, you might imagine:</p><pre>State update<br>    ↓<br>Render<br>    ↓<br>Commit</pre><p>Once scheduling and concurrent rendering enter the picture, the process is more flexible.</p><p>Conceptually:</p><pre>Update<br>  |<br>  v<br>Schedule work<br>  |<br>  v<br>Start rendering<br>  |<br>  +------ another urgent update arrives<br>  |                    |<br>  |                    v<br>  |              Handle urgent work<br>  |                    |<br>  +&lt;-------------------+<br>  |<br>  v<br>Continue/restart work<br>  |<br>  v<br>Commit</pre><p>This is why React’s render phase needs to be treated as interruptible and restartable.</p><p>It also connects back to something we discussed earlier in the series:</p><p><strong>rendering and committing are different phases.</strong></p><p>React can spend time figuring out what the UI should look like before it actually applies the final changes to the DOM.</p><p>That separation becomes especially important when React has more than one piece of work competing for attention.</p><h3>A Common Misunderstanding About startTransition</h3><p>You might see this:</p><pre>startTransition(() =&gt; {<br>  setCount(count + 1);<br>});</pre><p>and think:</p><blockquote><em>“React will update </em><em>count later.&quot;</em></blockquote><p>That’s not quite the right mental model.</p><p>A Transition doesn’t mean:</p><pre>Do nothing now.<br>Wait 1 second.<br>Then update.</pre><p>It means:</p><pre>This update is non-urgent.<br><br>If more important work arrives,<br>React can prioritize that work instead.</pre><p>There is no fixed delay.</p><p>There is no guarantee that the update will happen after some particular amount of time.</p><p>The goal is <strong>responsiveness</strong>, not delayed execution.</p><h3>What Happens If the User Changes Their Mind?</h3><p>Imagine clicking a tab:</p><pre>About → Posts</pre><p>The Posts page is expensive to render.</p><p>While React is working on it, the user clicks:</p><pre>About</pre><p>again.</p><p>With interruptible Transition work, React doesn’t have to stubbornly finish the previous expensive render before responding to the new interaction.</p><p>The newer, more urgent interaction can take priority.</p><p>This is one reason React’s documentation describes Transitions as interruptible.</p><p>This matters much more in applications with:</p><ul><li>large lists</li><li>complex dashboards</li><li>charts</li><li>expensive filtering</li><li>navigation between heavy screens</li><li>Suspense-enabled data loading</li></ul><p>The larger the amount of rendering work, the more valuable it becomes to keep user interactions responsive.</p><h3>Transitions and Suspense</h3><p>There’s another place where this becomes particularly useful.</p><p>Suppose clicking a button changes the current page:</p><pre>setPage(&#39;/profile&#39;);</pre><p>and the new page suspends while data is loading.</p><p>Without treating the navigation as a Transition, React may show a Suspense fallback in situations where replacing already-visible content would feel jarring.</p><p>You can instead write:</p><pre>startTransition(() =&gt; {<br>  setPage(&#39;/profile&#39;);<br>});</pre><p>This tells React that the navigation is non-urgent.</p><p>React can then keep already revealed content visible while the new content is being prepared, avoiding some unwanted fallback replacement during the transition.</p><p>This is one of the places where scheduling stops being an abstract performance concept and starts affecting how the application actually feels.</p><h3>So, Does React Have a Simple “Priority Number”?</h3><p>Not really.</p><p>It’s tempting to imagine something like:</p><pre>Urgent       = priority 1<br>Normal       = priority 2<br>Transition   = priority 3</pre><p>But React’s internal scheduling model is more nuanced than a simple numbered list.</p><p>The important takeaway for application developers isn’t memorizing every lane or internal constant.</p><p>It’s understanding the principle:</p><blockquote><strong><em>React can associate updates with different kinds of work and use that information when deciding what to process.</em></strong></blockquote><p>The lane model is part of how React represents and manages this work internally.</p><p>The public APIs such as startTransition and useTransition are the tools we normally use to communicate our intent.</p><h3>When Should You Actually Use startTransition?</h3><p>A good question to ask is:</p><blockquote><strong><em>Does this update need to block the user interaction?</em></strong></blockquote><p>If yes, it probably shouldn’t be a Transition.</p><p>For example:</p><pre>Typing into an input<br>Clicking an important button<br>Updating immediate visual feedback</pre><p>These usually need to feel immediate.</p><p>On the other hand:</p><pre>Rendering a large result list<br>Switching between expensive views<br>Updating a complex chart<br>Navigating to a heavy screen</pre><p>may be good candidates for a Transition when the update doesn’t need to block interaction.</p><p>It’s not about blindly labeling updates as “fast” or “slow.”</p><p>It’s about <strong>what the user needs immediately</strong>.</p><h3>The Mental Model I Keep Coming Back To</h3><p>After going through batching, scheduling, and transitions, I think about React updates in four questions:</p><h3>1. What changed?</h3><pre>State / props / context</pre><h3>2. Can React group the work?</h3><pre>Batching</pre><h3>3. Which work matters most right now?</h3><pre>Scheduling / priorities</pre><h3>4. Can lower-priority work wait if something more important happens?</h3><pre>Concurrent rendering / transitions</pre><p>Put together:</p><pre>State update<br>     |<br>     v<br>Can updates be batched?<br>     |<br>     v<br>What kind of work is this?<br>     |<br>     v<br>How should React prioritize it?<br>     |<br>     v<br>Render<br>     |<br>     |---- interrupt/restart if necessary<br>     |<br>     v<br>Commit</pre><p>That is a much more useful mental model than:</p><pre>setState()<br>   ↓<br>component runs again</pre><h3>One Important Limitation</h3><p>There’s one detail worth knowing if you start experimenting with startTransition.</p><p>If you have asynchronous work, updates after an await may need another startTransition to be treated as Transition updates.</p><p>For example:</p><pre>startTransition(async () =&gt; {<br>  const data = await fetchData();<br>  <br>  startTransition(() =&gt; {<br>    setData(data);<br>  });<br>});</pre><p>This is a current limitation documented by React because the Transition context isn’t automatically preserved across that async boundary[<strong>Resolved in React 19</strong>].</p><p>You don’t need to memorize this immediately.</p><p>Just remember that:</p><pre>startTransition()<br>        |<br>        v<br>synchronous state updates<br>        |<br>        v<br>marked as Transition</pre><p>An await introduces an async boundary, so the state update after it may need to be marked again.[Need to do in React 18 but works fine in React 19]</p><h3>Key Takeaways</h3><p>If I had to reduce the entire article to a few ideas, they would be these:</p><ul><li><strong>Not every state update has the same urgency.</strong></li><li>Batching and prioritization solve different problems.</li><li><strong>Batching</strong> helps React reduce unnecessary rendering work.</li><li><strong>Prioritization</strong> helps React decide which work should receive attention first.</li><li>React internally uses a <strong>lane-based model</strong> to represent pending work and its priorities.</li><li>startTransition lets you mark state updates as <strong>non-urgent</strong>.</li><li>useTransition gives you the same transition capability plus an isPending value.</li><li>Transition work can be <strong>interrupted by more urgent updates</strong>.</li><li>Concurrent rendering doesn’t mean React renders on multiple threads; it means React can make rendering work interruptible and schedule it more flexibly.</li><li>Don’t use Transitions for state that directly controls a text input.</li><li>useDeferredValue is useful when you want a non-critical part of the UI to consume a deferred version of an existing value.</li><li>Transitions are about <strong>responsiveness</strong>, not making expensive computations magically faster.</li></ul><p>The biggest shift is this:</p><blockquote><em>React doesn’t just ask, “What needs to render?”</em></blockquote><blockquote><em>It can also ask, “What needs to happen first?”</em></blockquote><p>And that question becomes increasingly important as an application grows.</p><h3>React Internals Series</h3><p>So far, we’ve gone from basic rendering behavior to the update pipeline:</p><p><strong>Part 1:</strong> Does useEffect Trigger Re-renders? A Common React Misconception<br><strong>Part 2:</strong> What Actually Causes a React Component to Re-render?<br><strong>Part 3:</strong> React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?<br><strong>Part 4:</strong> Why React Needs Keys — And Why index as a Key Can Break More Than You Think<br><strong>Part 5:</strong> Understanding React Reconciliation: How React Decides What to Update<br><strong>Part 6:</strong> Why Doesn&#39;t useRef Trigger Re-renders?<br><strong>Part 7:</strong> Where Does React Actually Store State?<br><strong>Part 8:</strong> What Actually Happens When You Call setState?<br><strong>Part 9:</strong> Why Does React Batch State Updates?<br><strong>Part 10:</strong> React Update Priorities: Why Some Updates Are More Important Than Others</p><h3>What’s Next?</h3><p>We’ve now added another important piece to the React update model.</p><p>We started with:</p><pre>setState()</pre><p>Then we explored:</p><pre>Update Queue<br>    ↓<br>Batching<br>    ↓<br>Scheduling<br>    ↓<br>Priorities<br>    ↓<br>Transitions</pre><p>But there is still a bigger question.</p><p>If React can interrupt rendering, prioritize updates, and schedule work differently…</p><p><strong>How does React actually perform that work without blocking the browser?</strong></p><p>What happens when rendering takes too long?</p><p>How does React break work into smaller pieces?</p><p>Where does the Scheduler fit into all of this?</p><p>And how does the <strong>Fiber architecture</strong> make interruptible rendering possible?</p><p>That’s where we’re going next.</p><h3>React Fiber: The Architecture Behind Modern React Rendering</h3><p>We’ll look at what Fiber actually is, why React moved away from the older recursive rendering approach, how Fiber represents components as units of work, and how it enables React to pause, resume, prioritize, and restart rendering work.</p><p>Once Fiber starts making sense, many of the things we’ve discussed so far — <strong>reconciliation, scheduling, priorities, transitions, and concurrent rendering</strong> — start fitting into one larger picture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c2ea42c2453" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-frontier/react-update-priorities-why-some-updates-are-more-important-than-others-5c2ea42c2453">React Update Priorities: Why Some Updates Are More Important Than Others</a> was originally published in <a href="https://medium.com/the-code-frontier">The Code Frontier</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Does React Batch State Updates?]]></title>
            <link>https://medium.com/the-code-frontier/why-does-react-batch-state-updates-5252688489cd?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5252688489cd</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 05:43:02 GMT</pubDate>
            <atom:updated>2026-09-05T05:46:21.151Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Automatic Batching, Multiple setState Calls, and What React Actually Does</h3><p><em>Part 9 of the React Internals Series</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtQ8YzdUYBmZcDse_B7Ipg.png" /><figcaption>Image generated by the author using ChatGPT (DALL·E) to illustrate React’s state batching and rendering process.</figcaption></figure><p>There was a time when I wanted to know that how many times my React component is rendering.</p><p>I had a simple component with three useState hook:</p><pre>function Dashboard() {<br>    const [user, setUser] = useState(null);<br>    const [loading, setLoading] = useState(false);<br>    const [error, setError] = useState(null);<br>    // ...<br>}</pre><p>And I created a click event handler in which I would update all the hooks meaning I called all three hook’s setState function into that handler:</p><pre>setLoading(true);<br>setError(null);<br>setUser(data);</pre><p>Then I thought which was not clear that time so I was thinking like:</p><blockquote><em>“That’s three state updates, so React must render three times.”</em></blockquote><p>But that’s not necessarily what happens.</p><p>React can take those updates and process them together.</p><p>That’s <strong>batching</strong>.</p><p>And once I started looking into it, I realized that batching is one of those React features we benefit from constantly without necessarily thinking about what’s happening underneath.</p><p>So in this article, I want to answer a few simple questions:</p><ul><li>What exactly is batching?</li><li>Why does React batch state updates?</li><li>What changed with React 18?</li><li>Why can multiple setState calls result in a single render?</li><li>What happens when updates come from promises, timers, or event handlers?</li><li>Can we force React to update immediately?</li></ul><p>Let’s start with the simplest example.</p><h3>Three State Updates Don’t Necessarily Mean Three Renders</h3><p>Consider:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>    const [name, setName] = useState(&quot;&quot;);<br>    const [loading, setLoading] = useState(false);<br><br>    const handleClick = () =&gt; {<br>        setCount(count + 1);<br>        setName(&quot;Vikash&quot;);<br>        setLoading(true);<br>    };<br>    return (<br>        // ...<br>    );<br>}</pre><p>There are three calls to state setters.</p><p>It’s tempting to imagine:</p><pre>setCount()<br>   ↓<br>Render<br>   ↓<br>setName()<br>   ↓<br>Render<br>setLoading()<br>   ↓<br>Render</pre><p>But React can instead do this:</p><pre>setCount()<br>setName()<br>setLoading()<br>       |<br>       ▼<br>   Batch Updates<br>       |<br>       ▼<br>   One Render</pre><p>That’s the basic idea behind batching.</p><p>React collects multiple updates and processes them together rather than immediately rendering after every single update.</p><h3>Why Does React Do This?</h3><p>The obvious question is:</p><blockquote><em>Why not just render after every update?</em></blockquote><p>Because rendering after every individual update would often mean doing unnecessary work.</p><p>Imagine this:</p><pre>setFirstName(&quot;Vikash&quot;);<br>setLastName(&quot;Yadav&quot;);<br>setAge(26);</pre><p>If every update immediately caused a complete rendering cycle, React could potentially do:</p><pre>Update firstName<br>      ↓<br>   Render<br><br>Update lastName<br>      ↓<br>   Render<br><br>Update age<br>      ↓<br>   Render<br></pre><p>But the UI doesn’t necessarily need to pass through all three intermediate states.</p><p>The user ultimately needs to see:</p><pre>firstName = &quot;Vikash&quot;<br>lastName = &quot;Yadav&quot;<br>age = 26</pre><p>So React can process the updates together:</p><pre>Update 1<br>Update 2<br>Update 3<br>    |<br>    ▼<br>Process together<br>    |<br>    ▼<br>Render</pre><p>This reduces unnecessary rendering work.</p><p>And this becomes even more useful as applications get larger.</p><h3>Batching Isn’t the Same as Combining State</h3><p>This distinction is important.</p><p>Suppose you have:</p><pre>const [count, setCount] = useState(0);<br>const [name, setName] = useState(&quot;&quot;);</pre><p>And you write:</p><pre>setCount(1);<br>setName(&quot;Vikash&quot;);</pre><p>React isn’t turning those into one state value.</p><p>You still have two separate pieces of state.</p><p>What React is batching is the <strong>processing of the updates and resulting rendering work</strong>.</p><p>Conceptually:</p><pre>State Update A ─┐<br>                ├──&gt; One scheduled render<br>State Update B ─┘</pre><p>The state itself remains separate.</p><h3>What Happens Inside React?</h3><p>Let’s connect this with the previous article.</p><p>We already saw that calling:</p><pre>setCount(count + 1);</pre><p>creates an update.</p><p>That update is associated with the Hook’s update queue.</p><p>Now imagine several updates happening before React processes them.</p><p>Conceptually:</p><pre>Fiber<br> |<br> └── useState<br>       |<br>       ├── current state<br>       |<br>       └── update queue<br>              |<br>              ├── Update A<br>              ├── Update B<br>              └── Update C</pre><p>React can process those pending updates together during the next render.</p><p>So batching doesn’t mean React ignores the individual updates.</p><p>It means React doesn’t necessarily perform a separate rendering cycle for every update.</p><h3>Let’s Look at a More Interesting Example</h3><p>Consider:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br><br>    const handleClick = () =&gt; {<br>        setCount(prev =&gt; prev + 1);<br>        setCount(prev =&gt; prev + 1);<br>        setCount(prev =&gt; prev + 1);<br>    };<br>    return &lt;h2&gt;{count}&lt;/h2&gt;;<br>}</pre><p>There are three state updates.</p><p>Because they’re functional updates, React can process them sequentially:</p><pre>Initial state<br>     0<br>     ↓<br>Update 1<br>     1<br>     ↓<br>Update 2<br>     2<br>     ↓<br>Update 3<br>     3</pre><p>The component can then render with:</p><pre>count = 3</pre><p>The important part is that React doesn’t need three separate renders just because there were three updates.</p><p>It can process the updates and render the resulting state.</p><p>This is one of the reasons the update queue we discussed in Part 8 is so important.</p><h3>Batching and the Event Handler</h3><p>For a long time, one of the easiest ways to observe batching was inside a React event handler.</p><p>For example:</p><pre>function App() {<br>    const [count, setCount] = useState(0);<br>    const [name, setName] = useState(&quot;&quot;);<br><br>    const handleClick = () =&gt; {<br>        setCount(1);<br>        setName(&quot;Vikash&quot;);<br>    };<br>    console.log(&quot;render&quot;);<br>    return (<br>        &lt;button onClick={handleClick}&gt;<br>            Update<br>        &lt;/button&gt;<br>    );<br>}</pre><p>Both state updates happen during the same event.</p><p>React can batch them into the same render.</p><p>Conceptually:</p><pre>Click<br> |<br> ├── setCount()<br> |<br> └── setName()<br>       |<br>       ▼<br>    Render</pre><p>This behavior has been part of React for a long time.</p><p>But React 18 made batching broader.</p><p>And that’s where things get more interesting.</p><h3>What Changed in React 18?</h3><p>Before React 18, automatic batching was more limited.</p><p>Updates inside React event handlers were batched, but updates occurring in some asynchronous contexts weren’t automatically treated the same way.</p><p>For example:</p><pre>setTimeout(() =&gt; {<br>    setCount(c =&gt; c + 1);<br>    setLoading(false);<br>}, 1000);</pre><p>In older React versions, these updates could result in separate renders.</p><p>React 18 expanded automatic batching so that updates from more sources can be batched when using the modern createRoot API.</p><p>That includes updates originating from places such as:</p><pre>React events<br>Promises<br>setTimeout<br>native event handlers</pre><p>The practical result is simple:</p><blockquote><em>More state updates can be processed together.</em></blockquote><h3>A React 18 Example</h3><p>Consider:</p><pre>function App() {<br>    const [count, setCount] = useState(0);<br>    const [loading, setLoading] = useState(false);<br><br>    const handleClick = () =&gt; {<br>        setTimeout(() =&gt; {<br>            setCount(c =&gt; c + 1);<br>            setLoading(false);<br>        }, 1000);<br>    };<br>    console.log(&quot;render&quot;);<br>    return (<br>        &lt;button onClick={handleClick}&gt;<br>            Update<br>        &lt;/button&gt;<br>    );<br>}</pre><p>With React 18’s modern root API:</p><pre>createRoot(document.getElementById(&quot;root&quot;)).render(<br>    &lt;App /&gt;<br>);</pre><p>React can batch those updates from the timeout.</p><p>So instead of thinking:</p><pre>setCount()<br>   ↓<br>Render<br><br>setLoading()<br>   ↓<br>Render</pre><p>think:</p><pre>setCount()<br>setLoading()<br>      |<br>      ▼<br>One render</pre><p>This is what <strong>automatic batching</strong> means in practical terms.</p><h3>Why Did React 18 Expand Batching?</h3><p>Because modern applications don’t only update state from click handlers.</p><p>Real applications constantly deal with:</p><ul><li>API responses</li><li>timers</li><li>subscriptions</li><li>promises</li><li>browser events</li><li>async workflows</li></ul><p>Imagine an API request finishes:</p><pre>fetch(&quot;/api/user&quot;)<br>    .then(response =&gt; response.json())<br>    .then(user =&gt; {<br>        setUser(user);<br>        setLoading(false);<br>        setError(null);<br>    });</pre><p>All three updates are related to the same piece of work.</p><p>It makes sense for React to process them together.</p><p>Otherwise, React could repeatedly render intermediate states that the user never actually needs to see.</p><p>React 18’s broader batching makes this behavior more consistent.</p><h3>Batching Doesn’t Mean React Delays Everything Forever</h3><p>This is another misconception worth clearing up.</p><p>Batching doesn’t mean:</p><blockquote><em>“React waits as long as possible and eventually renders.”</em></blockquote><p>React still needs to keep the UI responsive.</p><p>Suppose a user clicks a button.</p><p>React can’t simply decide:</p><blockquote><em>“I’ll process this sometime later today.”</em></blockquote><p>Updates have priorities and scheduling behavior.</p><p>React decides when work should be performed based on the type of update and the current rendering situation.</p><p>Batching is about <strong>grouping related updates</strong>, not randomly delaying UI updates.</p><h3>What About console.log?</h3><p>Let’s connect this to something we’ve already discussed.</p><p>Consider:</p><pre>const handleClick = () =&gt; {<br>    setCount(count + 1);<br>    setLoading(false);<br><br>    console.log(count);<br>};</pre><p>You can still see the old count.</p><p>Why?</p><p>Because batching doesn’t change the fact that you’re inside the current render’s execution.</p><p>The current render has:</p><pre>count = 0</pre><p>You request:</p><pre>count → 1</pre><p>React schedules that update.</p><p>But the count variable inside the current function execution is still:</p><pre>0</pre><p>The next render gets the updated state.</p><p>So:</p><pre>Current render<br>count = 0<br>      |<br>      ├── setCount(1)<br>      |<br>      └── console.log(count)<br>                 |<br>                 └── 0</pre><p>Then:</p><pre>Next render<br>count = 1</pre><p>Batching doesn’t change this mental model.</p><h3>What If I Need the Latest State?</h3><p>This is where functional updates become useful again.</p><p>Instead of:</p><pre>setCount(count + 1);</pre><p>you can write:</p><pre>setCount(prev =&gt; prev + 1);</pre><p>Now React can calculate the next state from the state it is actually processing.</p><p>For example:</p><pre>setCount(prev =&gt; prev + 1);<br>setCount(prev =&gt; prev + 1);<br>setCount(prev =&gt; prev + 1);</pre><p>Conceptually:</p><pre>0<br>↓<br>prev = 0 → 1<br>↓<br>prev = 1 → 2<br>↓<br>prev = 2 → 3</pre><p>This is especially useful when several updates depend on the previous state.</p><h3>Can We Opt Out of Batching?</h3><p>Sometimes you might genuinely need React to flush updates immediately.</p><p>React provides:</p><pre>flushSync</pre><p>from react-dom:</p><pre>import { flushSync } from &quot;react-dom&quot;;<br><br>flushSync(() =&gt; {<br>    setCount(1);<br>});</pre><p>This tells React to flush the update synchronously.</p><p>But this isn’t something you should reach for just because batching feels unfamiliar.</p><p>It exists for specific situations where you need the DOM to be updated immediately before continuing.</p><p>Using synchronous flushing unnecessarily can hurt performance.</p><p>So the default should generally be:</p><blockquote><em>Let React batch the updates.</em></blockquote><h3>A Small Experiment</h3><p>If you want to understand batching rather than simply reading about it, try this yourself.</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br><br>    console.log(&quot;render&quot;);<br><br>    const handleClick = () =&gt; {<br>        setCount(c =&gt; c + 1);<br>        setCount(c =&gt; c + 1);<br>        setCount(c =&gt; c + 1);<br>    };<br><br>    return (<br>        &lt;&gt;<br>            &lt;h2&gt;{count}&lt;/h2&gt;<br>            &lt;button onClick={handleClick}&gt;<br>                Increment<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><p>Don’t just look at the final number.</p><p>Watch the console.</p><p>You’ll see the component render, then click the button and observe how React processes the updates.</p><p>This kind of small experiment has helped me understand React much more than simply reading definitions.</p><p>When something in React feels confusing, I usually find it more useful to reduce it to a 10-line component and observe what actually happens.</p><h3>Batching vs Rendering</h3><p>There’s another distinction worth keeping in your mental model.</p><p><strong>Batching</strong> answers:</p><blockquote><em>“Can React process these updates together?”</em></blockquote><p><strong>Rendering</strong> answers:</p><blockquote><em>“What should the UI look like after processing those updates?”</em></blockquote><p><strong>Reconciliation</strong> answers:</p><blockquote><em>“What changed between the previous UI tree and the new one?”</em></blockquote><p><strong>Commit</strong> answers:</p><blockquote><em>“What changes need to be applied to the actual DOM?”</em></blockquote><p>So the overall picture becomes:</p><pre>Multiple State Updates<br>          |<br>          ▼<br>      Batching<br>          |<br>          ▼<br>   Process Update Queue<br>          |<br>          ▼<br>      Render Phase<br>          |<br>          ▼<br>    Reconciliation<br>          |<br>          ▼<br>     Commit Phase<br>          |<br>          ▼<br>       DOM Update</pre><p>Notice how this fits directly into everything we’ve covered so far.</p><h3>Does Batching Always Mean One Render?</h3><p>This is where I would avoid turning the concept into another rule to memorize.</p><p>Don’t think:</p><blockquote><em>“Three state updates always equal one render.”</em></blockquote><p>That’s too simplistic.</p><p>React’s rendering behavior depends on the updates, scheduling, component tree, priorities, and other factors.</p><p>Also, React can render a component for reasons other than the particular state update you’re looking at.</p><p>The useful mental model is:</p><blockquote><strong><em>React can batch multiple related updates so that they don’t each require a separate rendering cycle.</em></strong></blockquote><p>That’s the important part.</p><p>Not a fixed equation like:</p><pre>3 updates = 1 render</pre><h3>Why Batching Matters More as Applications Grow</h3><p>In a small counter application, batching might not feel important.</p><p>But imagine a real dashboard.</p><p>One user action might change:</p><pre>selectedUser<br>loading<br>filters<br>notifications<br>URL state</pre><p>Without efficient update handling, these changes could create a lot of unnecessary work.</p><p>With batching, React has more opportunities to process related updates together.</p><p>That doesn’t magically make an application fast.</p><p>Good component boundaries, efficient rendering, memoization where appropriate, sensible state structure, and avoiding unnecessary work still matter.</p><p>But batching gives React a better starting point.</p><h3>The Mental Model I Use Now</h3><p>I no longer think about state updates like this:</p><pre>setState()<br>   ↓<br>state changes<br>   ↓<br>render</pre><p>I think about them more like this:</p><pre>setState()<br>    |<br>    ▼<br>Create an update<br>    |<br>    ▼<br>Put it into the update queue<br>    |<br>    ▼<br>React schedules the work<br>    |<br>    ▼<br>Related updates may be batched<br>    |<br>    ▼<br>React processes the queue<br>    |<br>    ▼<br>Render<br>    |<br>    ▼<br>Reconciliation<br>    |<br>    ▼<br>Commit</pre><p>This model explains a lot more.</p><p>It explains why state doesn’t change immediately.</p><p>It explains why multiple updates can result in fewer renders.</p><p>It explains why functional updates matter.</p><p>And it explains why React 18’s automatic batching was useful.</p><h3>Key Takeaways</h3><p><strong>Multiple state updates don’t necessarily mean multiple renders.</strong></p><p>React can batch updates together.</p><p><strong>Batching exists primarily to avoid unnecessary work.</strong></p><p>React can process several updates before producing the next UI.</p><p><strong>React 18 expanded automatic batching.</strong></p><p>With the modern root API, updates from more asynchronous contexts can be batched automatically.</p><p><strong>Batching doesn’t mean state variables mutate immediately.</strong></p><p>The current render still sees its existing state.</p><p><strong>Functional updates are important when updates depend on previous state.</strong></p><pre>setCount(prev =&gt; prev + 1);</pre><p>allows React to process each update from the latest state available in the queue.</p><p><strong>Don’t assume a fixed relationship between updates and renders.</strong></p><p>React’s rendering behavior is more nuanced than “N updates equals N renders” or “N updates always equals one render.”</p><p><strong>flushSync exists when synchronous flushing is genuinely required.</strong></p><p>It’s an escape hatch, not something you normally need in application code.</p><h3>Final Thoughts</h3><p>Batching is one of those React features that is easy to use without ever thinking about it.</p><p>You write:</p><pre>setUser(user);<br>setLoading(false);<br>setError(null);</pre><p>and the application just works.</p><p>But underneath that simple code, React is deciding how to process those updates without doing more rendering work than necessary.</p><p>That was the part I found most interesting when I started looking deeper into it.</p><p>The goal isn’t simply:</p><blockquote><em>“Render whenever something changes.”</em></blockquote><p>React has a much bigger problem to solve:</p><blockquote><strong><em>“How can I process all this work while keeping the UI responsive?”</em></strong></blockquote><p>Batching is one of the answers.</p><p>And now the bigger React picture starts to become clearer.</p><p>We started with a state update.</p><p>We followed it into an update queue.</p><p>We saw how React schedules the work.</p><p>Then we looked at rendering, reconciliation, and committing the result.</p><p>And now we’ve seen how React can group multiple updates before going through that process.</p><p>That’s a pretty important piece of React’s rendering model.</p><h3>React Internals Series</h3><p>If you’re following this series, here’s the journey so far:</p><p><strong>Part 1 — </strong><a href="https://medium.com/@vikash_yadav_41088/does-useeffect-trigger-re-renders-a-common-react-misconception-784706ee21ce?source=your_stories_outbox---writer_outbox_published-------------------------------------------">Does useEffect Trigger Re-renders? A Common React Misconception</a></p><p><strong>Part 2 — </strong><a href="https://medium.com/works-on-my-machine/what-actually-causes-a-react-component-to-re-render-66976be65f33?source=your_stories_outbox---writer_outbox_published-------------------------------------------">What Actually Causes a React Component to Re-render?</a></p><p><strong>Part 3 — </strong><a href="https://medium.com/works-on-my-machine/react-render-phase-vs-commit-phase-what-really-happens-behind-the-scenes-9ff1a8d13b1d?source=your_stories_outbox---writer_outbox_published-------------------------------------------">React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?</a></p><p><strong>Part 4 — </strong><a href="https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e?source=your_stories_outbox---writer_outbox_published-------------------------------------------">Why React Needs Keys — And Why index as a Key Can Break More Than You Think</a></p><p><strong>Part 5 — </strong><a href="https://medium.com/works-on-my-machine/understanding-react-reconciliation-how-react-decides-what-to-update-ec93067fcada?source=your_stories_outbox---writer_outbox_published-------------------------------------------">Understanding React Reconciliation: How React Decides What to Update</a></p><p><strong>Part 6 — </strong><a href="https://medium.com/works-on-my-machine/why-doesnt-useref-trigger-re-renders-cacc2d60fd57?source=your_stories_outbox---writer_outbox_published-------------------------------------------">Why Doesn’t useRef Trigger Re-renders?</a></p><p><strong>Part 7 — </strong><a href="https://medium.com/the-code-frontier/where-does-react-actually-store-state-948a1e3f0822?source=your_stories_outbox---writer_outbox_published-------------------------------------------">Where Does React Actually Store State?</a></p><p><strong>Part 8 — </strong><a href="https://medium.com/the-code-frontier/what-actually-happens-when-you-call-setstate-d9f53ddca447?source=your_stories_outbox---writer_outbox_published-------------------------------------------">What Actually Happens When You Call setState?</a></p><p><strong>Part 9 — Why Does React Batch State Updates?</strong> <em>(Current article)</em></p><h3>What’s Next?</h3><p>We’ve now covered a pretty important part of React’s update pipeline.</p><p>But there is another question that naturally comes up:</p><blockquote><strong><em>If React can batch updates and schedule work, does every state update have the same priority?</em></strong></blockquote><p>The answer is no.</p><p>Some updates need to happen immediately because the user is interacting with the UI.</p><p>Other work can wait.</p><p>And this is where React’s modern scheduling model becomes much more interesting.</p><p>In the next article, we’ll explore:</p><h3>React Update Priorities: Why Some Updates Are More Important Than Others</h3><p>We’ll look at how React thinks about urgent and non-urgent work, how startTransition fits into the picture, and why React doesn&#39;t treat every state update exactly the same way.</p><p>That’s where the ideas of <strong>scheduling, priorities, concurrent rendering, and transitions</strong> start connecting together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5252688489cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-frontier/why-does-react-batch-state-updates-5252688489cd">Why Does React Batch State Updates?</a> was originally published in <a href="https://medium.com/the-code-frontier">The Code Frontier</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Actually Happens When You Call setState?]]></title>
            <link>https://medium.com/the-code-frontier/what-actually-happens-when-you-call-setstate-d9f53ddca447?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9f53ddca447</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[setstate]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Thu, 20 Aug 2026 04:08:22 GMT</pubDate>
            <atom:updated>2026-08-20T15:07:16.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding React’s Update Queue, Scheduling, and Rendering Pipeline</h3><p><em>Part 8 of the React Internals Series</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TwkIy1FArT6ioIO75Mgxkw.png" /></figure><p><em>Image generated by the author using ChatGPT (DALL·E) to illustrate React’s state update lifecycle.</em></p><p>A few months ago, I was reviewing a PR(pull request) late in the evening when I noticed something that looked perfectly reasonable and fine:</p><pre>setCount(count + 1);<br><br>console.log(count);</pre><p>The developer was expecting that browser console will show the updated value.</p><p>Instead, it printed the old one.</p><p>At some point, almost every React developer encounters this and asks:</p><blockquote><em>“Why didn’t React update the state immediately?”</em></blockquote><p>It’s a fair and good question.</p><p>After all, we called setCount.</p><p>The name itself sounds like:</p><blockquote><em>“Set the count right now.”</em></blockquote><p>But that’s not actually what React does.</p><p>And once you understand what happens after calling setState, many React behaviors suddenly become much easier to explain:</p><ul><li>Why state updates appear asynchronous</li><li>Why multiple updates can be batched together</li><li>Why React sometimes skips work</li><li>Why functional updates exist</li><li>Why logging state immediately after setState often surprises people</li></ul><p>In this article, we’ll follow a state update from the moment you click a button all the way through React’s update queue, scheduling system, rendering process, reconciliation, and commit phase.</p><p>Because the reality is:</p><blockquote><strong><em>Calling </em></strong><strong><em>setState doesn&#39;t immediately change state. It requests a future state change.</em></strong></blockquote><p>And that distinction matters more than most developers realize.</p><h3>The Misleading Name</h3><p>Let’s start with a simple example.</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br><br>    const handleClick = () =&gt; {<br>        setCount(count + 1);<br>        console.log(count);<br>    };<br><br>    return (<br>        &lt;button onClick={handleClick}&gt;<br>            {count}<br>        &lt;/button&gt;<br>    );<br>}</pre><p>Many developers expect:</p><pre>1</pre><p>after the first click.</p><p>But React logs in console:</p><pre>0</pre><p>Why?</p><p>Because React hasn’t re-rendered yet.</p><p>At that moment, React has only received a request.</p><p>The update has not been processed.</p><p>The component hasn’t rendered again.</p><p>The DOM hasn’t been updated.</p><p>The current render is still working with the old value.</p><p>This is the first mental model shift:</p><blockquote><em>setState does not immediately mutate the state variable you&#39;re currently reading.</em></blockquote><p>Instead, it schedules work for React to perform.</p><h3>What Actually Gets Stored?</h3><p>When you call:</p><pre>setCount(count + 1);</pre><p>many developers imagine React doing something like:</p><pre>count = count + 1</pre><p>internally.</p><p>That isn’t what happens.</p><p>Instead, React creates an update object and places it into an internal queue associated with that Hook.</p><p>Conceptually:</p><pre>Current State<br>      |<br>      ▼<br>count = 0<br>      |<br>      ▼<br>User Clicks<br>      |<br>      ▼<br>setCount(1)<br>      |<br>      ▼<br>Update Queue<br>[ Update: 1 ]</pre><p>Nothing has changed yet.</p><p>React has simply recorded:</p><blockquote><em>“The next time I process updates, count should become 1.”</em></blockquote><h3>Why Use a Queue at All?</h3><p>This becomes easier to understand if we imagine multiple updates arriving close together.</p><p>Consider:</p><pre>const handleClick = () =&gt; {<br>    setCount(count + 1);<br>    setCount(count + 1);<br>    setCount(count + 1);<br>};</pre><p>A beginner might expect:</p><pre>count = 3</pre><p>after a single click.</p><p>But the result is:</p><pre>count = 1</pre><p>Why?</p><p>Because all three updates were created from the same render.</p><p>That render saw:</p><pre>count = 0</pre><p>So React receives:</p><pre>setCount(1)<br>setCount(1)<br>setCount(1)</pre><p>Conceptually, the queue becomes:</p><pre>[1]<br>[1]<br>[1]</pre><p>When React processes them, the final state is still:</p><pre>1</pre><p>Not:</p><pre>3</pre><p>Meaning if these series look like this</p><pre>setCount(1)<br>setCount(6)<br>setCount(4)</pre><p>Then, Guess what will you see in console?</p><p>Again basic thing, same state is called three times so queue will be like this</p><pre>[1]<br>[6]<br>[4]</pre><p>Now, React will process and make changes based on the final state value.</p><p>That’s all, by this way result will be <strong>4</strong>.</p><p>This is one of the reasons React provides functional updates.</p><h3>The Functional Update Version</h3><p>Now look at this:</p><pre>const handleClick = () =&gt; {<br>    setCount(prev =&gt; prev + 1);<br>    setCount(prev =&gt; prev + 1);<br>    setCount(prev =&gt; prev + 1);<br>};</pre><p>This behaves differently.</p><p>React stores something conceptually closer to:</p><pre>prev =&gt; prev + 1<br>prev =&gt; prev + 1<br>prev =&gt; prev + 1</pre><p>Now React can process them sequentially:</p><pre>0 → 1<br>1 → 2<br>2 → 3</pre><p>Final result:</p><pre>count = 3</pre><p>This is why functional updates exist.</p><p>They don’t capture a value from the current render.</p><p>They describe how to calculate the next state from whatever state React is processing.</p><h3>So What Happens After the Queue Receives an Update?</h3><p>Let’s follow the full lifecycle.</p><p>Suppose the user clicks:</p><pre>setCount(count + 1);</pre><p>The simplified flow looks like this:</p><pre>User Click<br>     |<br>     ▼<br>Create Update<br>     |<br>     ▼<br>Place Update Into Queue<br>     |<br>     ▼<br>Notify React Scheduler<br>     |<br>     ▼<br>Schedule Render<br>     |<br>     ▼<br>Render Phase<br>     |<br>     ▼<br>Reconciliation<br>     |<br>     ▼<br>Commit Phase<br>     |<br>     ▼<br>DOM Updated</pre><p>This flow connects nearly every concept we’ve covered in the series so far.</p><h3>Step 1: React Creates an Update</h3><p>When you call:</p><pre>setCount(1);</pre><p>React doesn’t immediately re-render.</p><p>Instead, React creates an update record.</p><p>Think of it as a note that says:</p><pre>Apply this update later.</pre><p>That update is attached to the Hook’s internal state structure.</p><p>Remember our previous article?</p><p>We learned that Hook information is stored alongside the component’s Fiber.</p><p>The update queue lives there too.</p><p>Conceptually:</p><pre>Fiber<br>   |<br>   └── useState<br>           |<br>           ├── Current State<br>           └── Update Queue</pre><h3>Step 2: React Schedules Work</h3><p>Once the update exists, React needs to decide:</p><blockquote><em>“When should I process this?”</em></blockquote><p>This is where React’s scheduler enters the picture.</p><p>React does not always process updates immediately.</p><p>Instead, React tries to balance responsiveness and efficiency.</p><p>Imagine a user rapidly typing:</p><pre>A<br>AB<br>ABC<br>ABCD<br>ABCDE</pre><p>If React fully rendered after every keystroke without any optimization, applications would feel much slower.</p><p>Instead, React can group work together and process updates intelligently.</p><p>That’s one reason React’s architecture evolved toward scheduling rather than immediate updates.</p><h3>Step 3: Render Phase Begins</h3><p>Eventually React decides:</p><blockquote><em>“It’s time to process pending updates.”</em></blockquote><p>Now React starts a new render.</p><p>Remember from earlier articles:</p><p>A render means React executes the component function again.</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br><br>    return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>React runs this function again.</p><p>But this time something important happens.</p><p>Before React returns the state value, it processes any queued updates.</p><p>Conceptually:</p><pre>Previous State = 0</pre><pre>Queue:<br>[ +1 ]</pre><pre>Process Queue</pre><pre>Result:<br>1</pre><p>Now the Hook returns:</p><pre>count = 1</pre><p>to the component.</p><p>That’s why the component sees the updated value during the next render.</p><h3>Step 4: React Produces a New UI Tree</h3><p>Once the component runs again, React creates a new tree of React elements.</p><p>Conceptually:</p><pre>Previous Render<br>&lt;h1&gt;0&lt;/h1&gt;<br><br>New Render<br>&lt;h1&gt;1&lt;/h1&gt;</pre><p>At this point React still hasn’t touched the browser DOM.</p><p>It has only generated a new description of what the UI should look like.</p><h3>Step 5: Reconciliation</h3><p>This is where our previous article comes back.</p><p>React compares:</p><pre>Old Tree</pre><p>with:</p><pre>New Tree</pre><p>and asks:</p><blockquote><em>“What actually changed?”</em></blockquote><p>For our example:</p><pre>Before:<br>&lt;h1&gt;0&lt;/h1&gt;</pre><pre>After:<br>&lt;h1&gt;1&lt;/h1&gt;</pre><p>Only the text content changed.</p><p>React records that difference.</p><p><strong>This comparison process is reconciliation.</strong></p><h3>Step 6: Commit Phase</h3><p>Once React knows what changed, it enters the Commit Phase.</p><p>Now React updates the real DOM.</p><pre>DOM Before<br>&lt;h1&gt;0&lt;/h1&gt;<br><br>DOM After<br>&lt;h1&gt;1&lt;/h1&gt;</pre><p>The user finally sees the update.</p><p>This is the moment most people think happened when they called setState.</p><p>In reality, several steps occurred first.</p><h3>Why Doesn’t React Just Update Immediately?</h3><p>This is one of the most important questions.</p><p>Imagine a component receiving several updates:</p><pre>setCount(c =&gt; c + 1);<br>setLoading(false);<br>setUser(data);</pre><p>If React immediately rendered after each one:</p><pre>Render 1<br>Render 2<br>Render 3</pre><p>that would create unnecessary work.</p><p>Instead React can batch updates together.</p><p>Conceptually:</p><pre>Update<br>Update<br>Update</pre><pre>      |<br>      ▼</pre><pre>Single Render</pre><p>This often improves performance significantly.</p><p>That’s why React prefers scheduling over immediate execution.</p><h3>A Real Example From Everyday Development</h3><p>A few weeks ago, I was debugging a search component.</p><p>Every keypress updated:</p><pre>query<br>results<br>loading</pre><p>Initially I assumed React was rendering separately for every state change.</p><p>After profiling the component, I realized React was batching much of the work together.</p><p>What looked like multiple updates in my code often became fewer renders than I expected.</p><p>That experience reinforced an important lesson:</p><blockquote><em>React’s job isn’t merely to apply updates. It’s to apply them efficiently.</em></blockquote><h3>What Happens If Multiple Components Update?</h3><p>This is where Fiber becomes particularly powerful.</p><p>Imagine:</p><pre>App<br> ├── Header<br> ├── Sidebar<br> └── Dashboard</pre><p>Suppose several updates occur.</p><p>React doesn’t need to blindly rebuild everything.</p><p>The Fiber tree helps React track:</p><ul><li>which components have pending work</li><li>where updates occurred</li><li>which parts of the tree need attention</li></ul><p>This allows React to process updates more intelligently than a simple “re-render the whole app” approach.</p><h3>Why Logging State Immediately After setState Feels Wrong</h3><p>Let’s revisit the example from the beginning.</p><pre>setCount(count + 1);<br>console.log(count);</pre><p>The console prints:</p><pre>0</pre><p>because you’re still inside the current render’s execution context.</p><p>React hasn’t processed the queue yet.</p><p>The next render hasn’t happened.</p><p>The state update is waiting to be applied.</p><p>A better mental model is:</p><pre>Current Render<br>count = 0<br><br>Request Update<br>Future Render<br>count = 1</pre><p>Once you think about it this way, the behavior becomes much easier to reason about.</p><h3>The Connection Between Everything We’ve Learned</h3><p>At this point, the articles in this series start connecting together.</p><p>State is stored with Hook data.</p><p>Hook data is associated with a Fiber.</p><p>Calling setState creates updates.</p><p>Updates enter a queue.</p><p>The scheduler decides when to process them.</p><p>The Render Phase executes components again.</p><p>Reconciliation compares trees.</p><p>The Commit Phase updates the DOM.</p><p>What once looked like separate React concepts are actually pieces of the same pipeline.</p><h3>The Mental Model</h3><p>If I had to summarize the entire article into one sentence, it would be this:</p><blockquote><strong><em>Calling </em></strong><strong><em>setState doesn&#39;t immediately change state. It asks React to schedule an update, process it during a future render, compare the resulting UI, and then commit the necessary changes to the DOM.</em></strong></blockquote><p>That mental model is much closer to what React is actually doing.</p><p>And once you understand it, many “weird” React behaviors stop feeling weird.</p><h3>Key Takeaways</h3><p><strong>setState doesn&#39;t immediately mutate state.</strong></p><p>It creates an update that React processes later.</p><p><strong>Updates are stored in a queue.</strong></p><p>React can process multiple updates together.</p><p><strong>Functional updates solve stale state problems.</strong></p><p>They work from the latest available state instead of a value captured from a previous render.</p><p><strong>React schedules work.</strong></p><p>Updates aren’t always processed instantly.</p><p><strong>Rendering and DOM updates are different things.</strong></p><p>A render produces a new UI description. The Commit Phase updates the browser.</p><p><strong>The update queue lives alongside Hook state.</strong></p><p>Both are associated with the component’s Fiber.</p><h3>Final Thoughts</h3><p>When I first started learning React, I treated setState as a command.</p><p>Something like:</p><blockquote><em>“Change this value right now.”</em></blockquote><p>Over time, I realized it’s closer to a request.</p><p>You’re not directly changing state.</p><p>You’re asking React to process an update.</p><p>That may sound like a small distinction.</p><p>But it’s the reason concepts like batching, scheduling, reconciliation, and concurrent rendering are even possible.</p><p>And once you see setState that way, React&#39;s behavior becomes much more predictable.</p><h3>What’s Next?</h3><p>We’ve followed a state update through React’s update queue, scheduler, render phase, reconciliation process, and commit phase.</p><p>But one big question still remains:</p><h3>Why Does React Batch State Updates?</h3><p>If React receives multiple updates, how does it decide whether they should trigger one render or many?</p><p>Why did React 18 introduce automatic batching?</p><p>And what actually changes when batching occurs?</p><p>In the next article, we’ll explore how batching works, why it exists, and how it helps React stay responsive even as applications grow more complex.</p><p>Because understanding batching is the final piece needed to fully understand why React updates behave the way they do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f53ddca447" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-frontier/what-actually-happens-when-you-call-setstate-d9f53ddca447">What Actually Happens When You Call setState?</a> was originally published in <a href="https://medium.com/the-code-frontier">The Code Frontier</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where Does React Actually Store State?]]></title>
            <link>https://medium.com/the-code-frontier/where-does-react-actually-store-state-948a1e3f0822?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/948a1e3f0822</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[fiber]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook-usestate]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 09:09:02 GMT</pubDate>
            <atom:updated>2026-08-11T12:11:20.000Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Hooks, Fiber, and Why React Doesn’t Forget Your State</h3><p><em>Part 7 of the React Internals Series</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QlJ4DLE8061mXRMnOvqIDQ.png" /></figure><p>There is a question that took me a surprisingly long time to answer properly.</p><p>We write a component like this:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br><br>    return (<br>        &lt;&gt;<br>            &lt;h2&gt;{count}&lt;/h2&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>                Increment<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><p>We click the button by observing the UI.</p><p>count becomes 1.</p><p>Click again.</p><p>It becomes 2.</p><p>And so on.</p><p>But here’s the strange part.</p><p>Every time React renders the component, <strong>the component function runs again.</strong></p><p>So if this function runs again:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>   // ...<br>}</pre><p>why doesn’t count go back to 0? because as we know if anything initialised in a Js function, those things will be same as initial if I call the same function again.(which is re-render in react).</p><p>Where is React actually keeping the value? Are those values present as Global value/variable or something else?</p><p>This question came back to me one evening while I was going through some React internals.</p><p>I had already understood that state updates cause renders, that React has a Render Phase and Commit Phase, and that refs behave differently from state.</p><p>But there was still a missing piece in the mental model:</p><blockquote><strong><em>If the component function is executed again, where does the state live between those executions?</em></strong></blockquote><p>Once you understand that, Hooks start making a lot more sense.</p><p>And it also explains something that initially feels like a completely unrelated React rule:</p><blockquote><strong><em>Why can’t we call Hooks conditionally?</em></strong></blockquote><p>Let’s connect those two things.</p><h3>First, Let’s Prove That the Component Actually Runs Again</h3><p>Before talking about Fiber or React internals, let’s remove one common misunderstanding.</p><p>Consider this:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>    console.log(&quot;Counter rendered&quot;);<br><br>    return (<br>        &lt;&gt;<br>            &lt;h2&gt;{count}&lt;/h2&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>                Increment<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><p>Open the browser console.</p><p>You will see:</p><pre>Counter rendered</pre><p>Click the button.</p><p>You’ll see it again.</p><p>Click again.</p><p>Again.</p><p>The component function is being executed repeatedly.</p><p>This is important.</p><p>React isn’t taking the original function and somehow changing the count variable inside it.</p><p>Instead, React calls the component again and provides the appropriate state value when the Hook is evaluated.</p><p>So the question becomes:</p><blockquote><em>If </em><em>count is just a local variable inside a function call, where does React get the previous value from?</em></blockquote><h3>The Wrong Mental Model</h3><p>It’s tempting to imagine something like this:</p><pre>Component<br>   |<br>   └── count = 0<br><br>Click<br>   |<br>   └── count = 1<br></pre><p>And then imagine React somehow keeping that local variable alive.</p><p>That’s not what happens.</p><p>A function’s local variables don’t survive after that particular function execution finishes.</p><p>For example:</p><pre>function test() {<br>    let value = 10;<br>}</pre><p>Once test() finishes, that local value isn&#39;t sitting somewhere waiting for the next call.</p><p>React doesn’t change this fundamental behavior of JavaScript.</p><p>Instead, React keeps the state <strong>outside the component function</strong>.</p><p>That’s the important part.</p><h3>So Where Is the State?</h3><p>The short version is:</p><blockquote><strong><em>React stores Hook-related information on the component’s internal Fiber node.</em></strong></blockquote><p>If you’ve been following this series, you’ve already seen the word <strong>Fiber</strong>.</p><p>We talked about it briefly when discussing useRef.</p><p>Now we can make that mental model more concrete.</p><p>Think of a Fiber as React’s internal record for a component.</p><p>A simplified representation might look something like:</p><pre>Counter Component<br>       |<br>       ▼<br>     Fiber<br>       |<br>       ├── props<br>       ├── parent<br>       ├── child<br>       ├── DOM information<br>       └── Hook information<br>              |<br>              ├── useState<br>              ├── useEffect<br>              ├── useRef<br>              └── ...</pre><p>The actual Fiber structure is considerably more complicated.</p><p>But for understanding Hooks, this is enough.</p><p>The important idea is:</p><blockquote><strong><em>Your component function doesn’t own the persistent state. React’s internal representation of that component does.</em></strong></blockquote><h3>A Component Has an Identity</h3><p>This leads to another important concept.</p><p>React needs to know:</p><blockquote><em>“Which component instance is this?”</em></blockquote><p>Suppose you have:</p><pre>&lt;App /&gt;</pre><p>and inside it:</p><pre>&lt;Counter /&gt;</pre><p>React creates an internal Fiber for that component.</p><p>Conceptually:</p><pre>Counter<br>   |<br>   ▼<br>Fiber<br>   |<br>   └── Hooks</pre><p>When Counter renders again, React doesn&#39;t think:</p><blockquote><em>“Here’s a completely unrelated Counter.”</em></blockquote><p>It knows that this render corresponds to the existing component instance.</p><p>That allows React to retrieve the state associated with that component.</p><p>So when you write:</p><pre>const [count, setCount] = useState(0);</pre><p>the 0 isn&#39;t simply assigned every time.</p><p>On the initial render, React uses it as the initial state.</p><p>On subsequent renders, React retrieves the existing state.</p><p>That’s why this:</p><pre>useState(0)</pre><p>doesn’t mean:</p><blockquote><em>“Set count to zero every time the component renders.”</em></blockquote><p>It means something closer to:</p><blockquote><em>“If this Hook doesn’t already have state, initialize it with zero. Otherwise, give me the state React already has.”</em></blockquote><p>That’s a much better mental model.</p><h3>The Interesting Part: Hooks Have an Order</h3><p>Now we’re getting to the reason behind one of React’s most famous rules:</p><blockquote><strong><em>Only call Hooks at the top level.</em></strong></blockquote><p>You’ve probably seen this rule countless times.</p><p>Don’t do this:</p><pre>if (isLoggedIn) {<br>    useEffect(() =&gt; {<br>        // ...<br>    }, []);<br>}</pre><p>Don’t do this:</p><pre>if (condition) {<br>    const [count, setCount] = useState(0);<br>}</pre><p>And don’t do this:</p><pre>function doSomething() {<br>    useState(0);<br>}</pre><p>But why?</p><p>Why does React care so much about where the Hook appears?</p><p>The answer becomes much easier once you understand how React keeps track of Hooks.</p><h3>Hooks Are Associated by Position</h3><p>Consider this component:</p><pre>function UserProfile() {<br>    const [name, setName] = useState(&quot;Vikash&quot;);<br>    const [age, setAge] = useState(25);<br><br>    useEffect(() =&gt; {<br>        console.log(name);<br>    }, [name]);<br><br>    return &lt;div&gt;{name}&lt;/div&gt;;<br>}</pre><p>Conceptually, React can think of the Hooks in this order:</p><pre>Hook 1 → useState(&quot;Vikash&quot;)<br>Hook 2 → useState(25)<br>Hook 3 → useEffect(...)</pre><p>React’s current implementation represents the Hook list as a linked structure associated with the Fiber.</p><p>You don’t need to memorize the data structure.</p><p>The important idea is that React walks through the Hooks <strong>in the same order every render</strong>.</p><p>First Hook.</p><p>Second Hook.</p><p>Third Hook.</p><p>And so on.</p><h3>Now Imagine We Change the Order</h3><p>Suppose you do this:</p><pre>function UserProfile({ showAge }) {<br>    const [name, setName] = useState(&quot;Vikash&quot;);<br><br>    if (showAge) {<br>        const [age, setAge] = useState(25);<br>    }<br>    const [isAdmin, setIsAdmin] = useState(false);<br>    return &lt;div&gt;{name}&lt;/div&gt;;<br>}</pre><p>Imagine the first render happens with:</p><pre>showAge = true</pre><p>React sees:</p><pre>Hook 1 → name<br>Hook 2 → age<br>Hook 3 → isAdmin</pre><p>Everything seems fine.</p><p>But then showAge becomes false.</p><p>Now React encounters:</p><pre>Hook 1 → name<br>Hook 2 → isAdmin</pre><p>The second Hook is no longer the same Hook it was before.</p><p>React’s internal bookkeeping is now out of alignment.</p><p>React expected the second Hook to represent age.</p><p>Instead, you’re asking it to represent isAdmin.</p><p>That’s the deeper reason behind the Rules of Hooks.</p><p>It’s not an arbitrary restriction.</p><p>It’s because React relies on <strong>consistent Hook ordering</strong> to match each Hook call with its stored data.</p><h3>This Is Why Hook Order Matters</h3><p>Here’s a simplified visualization.</p><h3>First render</h3><pre>Fiber<br> |<br> └── Hook list<br><br>      Hook 1<br>        |<br>        ├── name = &quot;Vikash&quot;<br>        |<br>        ▼<br>      Hook 2<br>        |<br>        ├── age = 25<br>        |<br>        ▼<br>      Hook 3<br>        |<br>        ├── isAdmin = false</pre><p>On the next render, React expects to encounter those Hooks in the same order:</p><pre>Hook 1 → name<br>Hook 2 → age<br>Hook 3 → isAdmin</pre><p>The component can render with different values.</p><p>Props can change.</p><p>State can change.</p><p>Conditions can change.</p><p>But the <strong>Hook sequence must remain stable</strong>.</p><p>That stability is what lets React match the current render with the information stored from previous renders.</p><h3>What Happens During a Render?</h3><p>Let’s connect this with the Render Phase we discussed earlier.</p><p>Suppose we have:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br><br>    return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>Initially:</p><pre>Component mounts<br>       |<br>       ▼<br>React creates Fiber<br>       |<br>       ▼<br>React creates Hook state<br>       |<br>       ▼<br>count = 0<br>       |<br>       ▼<br>Component returns &lt;h1&gt;0&lt;/h1&gt;</pre><p>Now we click:</p><pre>setCount(1);</pre><p>The simplified flow becomes:</p><pre>setCount(1)<br>     |<br>     ▼<br>React schedules update<br>     |<br>     ▼<br>Component renders again<br>     |<br>     ▼<br>React finds existing Hook<br>     |<br>     ▼<br>Hook state is now 1<br>     |<br>     ▼<br>Component returns &lt;h1&gt;1&lt;/h1&gt;<br>     |<br>     ▼<br>Reconciliation<br>     |<br>     ▼<br>Commit<br>     |<br>     ▼<br>DOM displays 1</pre><p>Notice something important.</p><p>The component doesn’t somehow remember count because JavaScript remembered the local variable.</p><p>React remembered it.</p><h3>What About Multiple Hooks?</h3><p>This is where the Hook list becomes particularly useful.</p><p>Consider:</p><pre>function Dashboard() {<br>    const [user, setUser] = useState(null);<br>    const [loading, setLoading] = useState(true);<br><br>    const inputRef = useRef(null);<br><br>    useEffect(() =&gt; {<br>        // fetch data<br>    }, []);<br><br>    return (<br>        // ...<br>    );<br>}</pre><p>Conceptually:</p><pre>Fiber<br>  |<br>  ▼<br>Hook 1<br>useState<br>user<br>  |<br>  ▼<br>Hook 2<br>useState<br>loading<br>  |<br>  ▼<br>Hook 3<br>useRef<br>inputRef<br>  |<br>  ▼<br>Hook 4<br>useEffect<br>effect information</pre><p>React can walk through this structure as the component executes.</p><p>The first Hook call corresponds to the first stored Hook.</p><p>The second corresponds to the second.</p><p>The third corresponds to the third.</p><p>And so on.</p><p>That’s why the order matters so much.</p><h3>But What About useRef?</h3><p>This also connects directly to our previous article.</p><p>We discussed that useRef persists between renders but doesn&#39;t trigger them.</p><p>Now we can see why.</p><p>React stores the ref information alongside the other Hook information.</p><p>But the ref itself is essentially a stable object:</p><pre>{<br>    current: ...<br>}</pre><p>React gives your component access to that object again on subsequent renders.</p><p>When you write:</p><pre>ref.current = &quot;something&quot;;</pre><p>you’re mutating the object.</p><p>You aren’t asking React to schedule an update.</p><p>So the ref survives.</p><p>But React doesn’t render because of that mutation.</p><p>This is a nice example of how several concepts from this series connect together.</p><h3>Let’s Try a Small Experiment</h3><p>Here’s a useful experiment you can run yourself.</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>    const renderCount = useRef(0);<br><br>    renderCount.current++;<br><br>    console.log({<br>        count,<br>        renders: renderCount.current<br>    });<br><br>    return (<br>        &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>            {count}<br>        &lt;/button&gt;<br>    );<br>}</pre><p>Click the button a few times.</p><p>You’ll see something like:</p><pre>{ count: 0, renders: 1 }<br>{ count: 1, renders: 2 }<br>{ count: 2, renders: 3 }<br>{ count: 3, renders: 4 }</pre><p>Now look at what happened.</p><p>count came from state.</p><p>renderCount.current came from a ref.</p><p>Both values survived across renders.</p><p>But only the state update caused another render.</p><p>That’s because persistence and scheduling are separate concepts.</p><p>This distinction is worth remembering.</p><h3>Persistence Does Not Mean Re-render</h3><p>This is probably the biggest takeaway from this article.</p><p>A value can survive between renders without causing renders.</p><p>For example:</p><pre>useRef<br>   |<br>   └── persists<br>       |<br>       └── does not schedule render</pre><p>While:</p><pre>useState<br>   |<br>   ├── persists<br>   |<br>   └── updates schedule render</pre><p>React doesn’t have one generic concept called “stored value.”</p><p>Different Hooks have different responsibilities.</p><p>And React keeps the information needed for those Hooks as part of the component’s internal state.</p><h3>One More Thing: What Happens When a Component Unmounts?</h3><p>This is an important part of the mental model.</p><p>Suppose your component disappears:</p><pre>{showCounter &amp;&amp; &lt;Counter /&gt;}</pre><p>If:</p><pre>showCounter = true</pre><p>React has a mounted Counter component with its associated Fiber and Hook state.</p><p>Now:</p><pre>showCounter = false</pre><p>The component is removed.</p><p>Its previous state isn’t something you should expect React to preserve indefinitely.</p><p>If the component later mounts again as a new instance, its state starts from the initial value again.</p><p>For example:</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>   // ...<br>}</pre><p>Unmount it.</p><p>Mount it again.</p><p>You shouldn’t expect the previous count to magically return.</p><p>This reinforces an important distinction:</p><blockquote><em>React preserves state across </em><strong><em>renders of the same component identity</em></strong><em>.</em></blockquote><p>It isn’t a global database for every component that has ever existed.</p><h3>The Connection With Keys</h3><p>And now we can connect this to one of our earlier articles.</p><p>Remember when we discussed keys?</p><p>Keys help React determine the identity of elements when reconciling lists.</p><p>That identity matters because React needs to know:</p><blockquote><em>“Is this the same component as before?”</em></blockquote><p>If React considers it the same component, its state can be preserved.</p><p>If React considers it a different component, the previous state may no longer belong to it.</p><p>This is one reason keys are much more important than simply removing a warning from the console.</p><p>Keys, component identity, Fibers, and state preservation are all connected.</p><h3>What React Is Really Doing</h3><p>At this point, I like to simplify the whole process into one mental picture.</p><p>Your component function is the <strong>description</strong>.</p><p>The Fiber is part of React’s <strong>memory of that component</strong>.</p><p>The Hooks are pieces of information associated with that memory.</p><p>So when React renders:</p><pre>Component Function<br>       |<br>       ▼<br>&quot;Give me the UI for this component<br>with its current state.&quot;<br>       |<br>       ▼<br>React looks at the component&#39;s<br>existing internal Hook data<br>       |<br>       ▼<br>Hook values are provided<br>       |<br>       ▼<br>Component returns React elements<br>       |<br>       ▼<br>Reconciliation<br>       |<br>       ▼<br>Commit</pre><p>The function itself doesn’t remember.</p><p><strong>React remembers.</strong></p><p>That’s the mental model I wish I had when I first started learning Hooks.</p><h3>Common Misconception: “useState Stores the Value in the Component”</h3><p>You’ll often hear something like:</p><blockquote><em>“The component stores its state.”</em></blockquote><p>It’s understandable shorthand, but technically it’s not a great mental model.</p><p>Your JavaScript function doesn’t have some hidden persistent variable called count.</p><p>React maintains the state associated with the component instance and its Hook.</p><p>That’s why this works:</p><pre>const [count, setCount] = useState(0);</pre><p>even though the component function runs repeatedly.</p><p>The function asks React for the state associated with that Hook.</p><p>React gives it back.</p><h3>Interview Corner</h3><p>Here’s a question you might get in a React interview:</p><blockquote><strong><em>If a functional component is just a function, how does React preserve state between renders?</em></strong></blockquote><p>A weak answer would be:</p><blockquote><em>“Because </em><em>useState remembers it.&quot;</em></blockquote><p>That’s just repeating the question.</p><p>A better answer is:</p><blockquote><em>“React associates Hook state with the component’s internal Fiber representation. During subsequent renders, React traverses the Hook structure in a consistent order and retrieves the state associated with each Hook. That’s why state can persist even though the component function itself executes again.”</em></blockquote><p>If you can explain that without memorizing the exact wording, you understand the concept.</p><h3>The Mental Model</h3><p>Here’s the version I want you to remember.</p><p>Don’t think:</p><pre>Component function<br>      |<br>      └── owns state</pre><p>Think:</p><pre>Component function<br>      |<br>      | executes<br>      ▼<br>React<br>      |<br>      ▼<br>Fiber<br>      |<br>      ▼<br>Hook data<br>      |<br>      ├── State<br>      ├── Ref<br>      ├── Effect<br>      └── Other Hook information</pre><p>Every render is another execution of the function.</p><p>But the function is connected to React’s existing internal representation.</p><p>That’s how React can say:</p><blockquote><em>“I know this is the same component, and I know where its previous Hook information is.”</em></blockquote><h3>Key Takeaways</h3><p>React state can feel like magic until you separate the responsibilities.</p><p>Here are the important pieces:</p><p><strong>The component function runs again.</strong></p><p>A re-render means React calls the component function again. Local variables from the previous function execution aren’t preserved automatically.</p><p><strong>React keeps the persistent information.</strong></p><p>Hook state is associated with the component’s internal Fiber representation.</p><p><strong>Hooks have an order.</strong></p><p>React relies on the order of Hook calls to associate each Hook call with its corresponding stored Hook data.</p><p><strong>That’s why Hooks can’t be conditional.</strong></p><p>Changing the Hook order can cause React to associate the wrong state or effect information with a Hook call.</p><p><strong>useState and </strong><strong>useRef are both persistent.</strong></p><p>But their update behavior is different.</p><p>State updates participate in React’s rendering process.</p><p>Changing ref.current doesn&#39;t schedule a render.</p><p><strong>Component identity matters.</strong></p><p>React preserves state across renders when it considers the component to be the same component. Keys can influence identity during reconciliation.</p><h3>Final Thoughts</h3><p>When I first learned React Hooks, I treated the Rules of Hooks as one more thing I had to memorize.</p><p>“Don’t put Hooks inside conditions.”</p><p>“Don’t put Hooks inside loops.”</p><p>“Don’t call Hooks from regular functions.”</p><p>At the time, they felt like arbitrary rules.</p><p>After understanding how React associates Hooks with a component’s internal data, they stopped feeling arbitrary.</p><p>The rule exists because React needs a reliable way to answer a very simple question:</p><blockquote><strong><em>“Which piece of stored information belongs to this Hook call?”</em></strong></blockquote><p>The answer is largely based on consistent Hook ordering.</p><p>And suddenly, the rule makes sense.</p><p>The same thing happened with state.</p><p>I used to think:</p><blockquote><em>“React somehow remembers my state.”</em></blockquote><p>That’s true, but incomplete.</p><p>A better mental model is:</p><blockquote><strong><em>The component function executes. React maintains the persistent information associated with that component and its Hooks. During the next render, React connects the new execution back to that existing information.</em></strong></blockquote><p>Once you understand that, Hooks stop looking like special JavaScript variables.</p><p>They’re an interface into React’s own memory and rendering system.</p><p>And that’s a much more useful way to think about them.</p><h3>React Internals Series</h3><p>If you’re following the series from the beginning, here’s the journey so far:</p><p><strong>Part 1 — Does </strong><strong>useEffect Trigger Re-renders? A Common React Misconception</strong></p><p><a href="https://medium.com/@vikash_yadav_41088/does-useeffect-trigger-a-re-render-a-common-react-misconception-784706ee21ce">https://medium.com/@vikash_yadav_41088/does-useeffect-trigger-a-re-render-a-common-react-misconception-784706ee21ce</a></p><p><strong>Part 2 — What Actually Causes a React Component to Re-render?</strong></p><p><a href="https://medium.com/works-on-my-machine/what-actually-causes-a-react-component-to-re-render-66976be65f33">https://medium.com/works-on-my-machine/what-actually-causes-a-react-component-to-re-render-66976be65f33</a></p><p><strong>Part 3 — React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?</strong></p><p><a href="https://medium.com/works-on-my-machine/react-render-phase-vs-commit-phase-what-really-happens-behind-the-scenes-9ff1a8d13b1d">https://medium.com/works-on-my-machine/react-render-phase-vs-commit-phase-what-really-happens-behind-the-scenes-9ff1a8d13b1d</a></p><p><strong>Part 4 — Why React Needs Keys — And Why </strong><strong>index as a Key Can Break More Than You Think</strong></p><p><a href="https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e">https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e</a></p><p><strong>Part 5 — Understanding React Reconciliation: How React Decides What to Update</strong></p><p><a href="https://medium.com/works-on-my-machine/understanding-react-reconciliation-how-react-decides-what-to-update-ec93067fcada">https://medium.com/works-on-my-machine/understanding-react-reconciliation-how-react-decides-what-to-update-ec93067fcada</a></p><p><strong>Part 6 — Why Doesn’t </strong><strong>useRef Trigger Re-renders? The Mental Model Every React Developer Should Know</strong></p><p>[<a href="https://medium.com/works-on-my-machine/why-doesnt-useref-trigger-re-renders-cacc2d60fd57">https://medium.com/works-on-my-machine/why-doesnt-useref-trigger-re-renders-cacc2d60fd57</a>]</p><p><strong>Part 7 — Where Does React Actually Store State?</strong> <em>(Current article)</em></p><h3>What’s Next?</h3><p>We’ve now answered a pretty fundamental question:</p><blockquote><strong><em>If the component function runs again, how does React remember its state?</em></strong></blockquote><p>The next question naturally takes us one step deeper.</p><p>We’ve talked about the Hook list.</p><p>We’ve talked about Fiber.</p><p>We’ve talked about React matching Hooks by order.</p><p>But what exactly happens when you call:</p><pre>setCount(count + 1);</pre><p>What is actually placed into the update queue?</p><p>Why doesn’t React immediately change the state?</p><p>How does React decide which update to process?</p><p>And what happens when you call setState multiple times before React renders?</p><p>In the next article, we’ll explore:</p><h3>What Actually Happens When You Call setState?</h3><p>We’ll follow a state update from the moment you click a button all the way through React’s update queue, scheduling, render, reconciliation, and commit process.</p><p>That’s where the pieces we’ve covered so far — <strong>state, Hooks, Fiber, scheduling, rendering, and reconciliation</strong> — start coming together into one complete picture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948a1e3f0822" width="1" height="1" alt=""><hr><p><a href="https://medium.com/the-code-frontier/where-does-react-actually-store-state-948a1e3f0822">Where Does React Actually Store State?</a> was originally published in <a href="https://medium.com/the-code-frontier">The Code Frontier</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Doesn’t useRef Trigger Re-renders?]]></title>
            <link>https://medium.com/works-on-my-machine/why-doesnt-useref-trigger-re-renders-cacc2d60fd57?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/cacc2d60fd57</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 05:17:49 GMT</pubDate>
            <atom:updated>2026-07-30T10:53:08.607Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Mental Model Every React Developer Should Know</h3><p><em>Part 6 of the React Internals Series</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQHI8UNEKkR8dYJpB7hO9g.png" /></figure><blockquote><em>“If </em><em>useState causes a re-render and </em><em>useRef also stores data between renders, why doesn&#39;t changing </em><em>ref.currentupdate the UI?&quot;</em></blockquote><p>It’s one of those questions that seems simple until you actually try to answer it.</p><p>A couple of months ago, on a Friday evening, I was reviewing a pull request from one of my teammates. The feature itself wasn’t complicated — it was a search component with a few filters and a couple of buttons.</p><p>While reading through the code, one line immediately caught my attention.</p><pre>searchRef.current = inputValue;</pre><p>A few lines later, there was another comment.</p><blockquote>“The UI isn’t updating after changing the ref. Not sure why.”</blockquote><p>At first, it looked like a small bug.</p><p>But then I realized it wasn’t really a bug.</p><p>It was a misunderstanding of how React thinks.</p><p>And honestly, I remembered making the exact same mistake when I first started learning hooks.</p><p>I knew that useState remembered values between renders.</p><p>I also knew that useRef remembered values between renders.</p><p>Both were hooks.</p><p>Both survived re-renders.</p><p>Both seemed capable of storing data.</p><p>So naturally, one question kept coming back.</p><blockquote><strong><em>If both hooks store values, why does updating one re-render the component while updating the other does absolutely nothing?</em></strong></blockquote><p>The answer isn’t about memorizing another React API.</p><p>It’s about understanding <strong>why React was designed this way</strong>.</p><p>Once that clicks, you’ll stop wondering when to use useState or useRef.</p><p>You’ll simply know.</p><h3>Before We Continue…</h3><p>I’d like you to make a prediction.</p><p>Don’t worry about getting it right.</p><p>Just go with your intuition.</p><p>Look at this component.</p><pre>function Counter() {<br>    const countRef = useRef(0);<br>    console.log(&quot;Component Rendered&quot;);<br><br>    return (<br>        &lt;&gt;<br>            &lt;h2&gt;{countRef.current}&lt;/h2&gt;<br>            &lt;button<br>                onClick={() =&gt; {<br>                    countRef.current++;<br>                    console.log(countRef.current);<br>                }}<br>            &gt;<br>                Increment<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><p>Before reading further, ask yourself:</p><blockquote><strong><em>What do you expect to happen after clicking the button five times?</em></strong></blockquote><p>Most developers I’ve asked usually answer something like this:</p><blockquote><em>“The number should become 5.”</em></blockquote><p>It sounds reasonable.</p><p>After all, we’re increasing the value.</p><p>The value lives inside the component.</p><p>React should notice it…</p><p>…right?</p><p>Let’s find out.</p><h3>Let’s Prove It</h3><p>Imagine we render the component.</p><p>The browser shows:</p><pre>0</pre><p>Now click the button.</p><p>Nothing changes.</p><p>Click it again.</p><p>Still nothing.</p><p>Click it five more times.</p><p>The screen stubbornly continues showing:</p><pre>0</pre><p>At this point, many developers think something is broken.</p><p>It isn’t.</p><p>Now open the browser console.</p><p>You’ll notice something interesting.</p><p>Every click updates the ref correctly.</p><pre>1<br>2<br>3<br>4<br>5</pre><p>So now we have an interesting situation.</p><p>The value is changing.</p><p>The UI isn’t.</p><p>That immediately tells us something important.</p><blockquote><strong><em>Changing a value and asking React to render again are two completely different things.</em></strong></blockquote><p>That distinction is the entire purpose of today’s article.</p><h3>Let’s Change One Line</h3><p>Now replace useRef with useState.</p><pre>function Counter() {<br>    const [count, setCount] = useState(0);<br>    console.log(&quot;Component Rendered&quot;);<br>    return (<br>        &lt;&gt;<br>            &lt;h2&gt;{count}&lt;/h2&gt;<br>            &lt;button<br>                onClick={() =&gt; {<br>                    setCount(count + 1);<br>                    console.log(count+1);<br>                }}<br>            &gt;<br>                Increment<br>            &lt;/button&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><p>Run it again.</p><p>Click once.</p><p>The number changes.</p><pre>1</pre><p>Click again.</p><pre>2</pre><p>Everything behaves exactly as we’d expect.</p><p>Even the console tells a different story.(You may see twice ‘Component Rendered’ in console in development mode due React strict mode.</p><pre>Component Rendered<br>1<br>Component Rendered<br>2<br>Component Rendered<br>3<br>...</pre><p>Now compare the two examples.</p><p>Both stored a number.</p><p>Both updated that number.</p><p>Only one told React to render again.</p><p>That isn’t an accident.</p><p>React intentionally treats these hooks differently.</p><p>The question is…</p><p><strong>Why?</strong></p><h3>The Mistake Most of Us Make</h3><p>When I was first learning React, I used to think like this.</p><pre>Value Changed<br>↓<br>React Should Render</pre><p>It felt obvious.</p><p>If something changes, React should update the screen.</p><p>But React doesn’t actually think that way.</p><p>Instead, React asks a much more important question.</p><blockquote><strong><em>“Does this change affect what the user should see?”</em></strong></blockquote><p>That tiny difference completely changes how you think about hooks.</p><p>Some values directly affect the UI.</p><p>Others don’t.</p><p>React only spends time rendering when it believes the UI might need to change.</p><p>Rendering isn’t free.</p><p>Even though React is incredibly fast, rendering still means:</p><ul><li>Calling your component again.</li><li>Running your JavaScript again.</li><li>Creating a new React element tree.</li><li>Running reconciliation.</li><li>Comparing elements.</li><li>Possibly updating the DOM.</li></ul><p>Imagine React re-rendered every single time <strong>any variable</strong> changed.</p><p>Typing into an input…</p><p>Moving the mouse…</p><p>Updating a timer…</p><p>Reading the scroll position…</p><p>Everything would continuously trigger new renders.</p><p>That would be wasteful.</p><p>Instead, React lets <strong>you</strong> decide.</p><p>When you call setState(), you&#39;re essentially telling React:</p><blockquote><strong><em>“The UI depends on this value. Please render again.”</em></strong></blockquote><p>When you update a ref, you’re saying something very different.</p><blockquote><strong><em>“I’m storing a value, but the UI doesn’t necessarily need to know about it right now.”</em></strong></blockquote><p>That distinction is one of the smartest design decisions in React.</p><h3>A Different Way to Think About Hooks</h3><p>Most tutorials explain hooks by describing what they do.</p><p>I think it’s more helpful to think about <strong>what responsibility each hook has</strong>.</p><p>For me, the mental model finally clicked when I stopped comparing APIs and started comparing responsibilities.</p><h3>useState has one responsibility.</h3><blockquote><em>Store information </em><strong><em>that affects what the user sees</em></strong><em>.</em></blockquote><h3>useRef has a different responsibility.</h3><blockquote><em>Store information </em><strong><em>that React doesn’t need to track for rendering</em></strong><em>.</em></blockquote><p>Notice that neither definition talks about implementation.</p><p>They talk about intent.</p><p>That’s how React sees these hooks.</p><h3>Imagine React Could Talk</h3><p>Whenever I explain this topic to junior developers on my team, I like to personify React for a moment.</p><p>Imagine React is sitting next to you while your application runs.</p><p>You call:</p><pre>setCount(5);</pre><p>React immediately responds:</p><blockquote><em>“Interesting.</em></blockquote><blockquote><em>You changed some state.</em></blockquote><blockquote><em>Since state describes the UI, I’d better render this component again and see what needs to change.”</em></blockquote><p>Now imagine you do this instead.</p><pre>countRef.current = 5;</pre><p>React looks at it and says:</p><blockquote><em>“I noticed you changed a value.</em></blockquote><blockquote><em>But you never told me this value affects the UI.</em></blockquote><blockquote><em>I’m going to leave the component exactly as it is.”</em></blockquote><p>Suddenly, the behavior stops feeling random.</p><p>React isn’t ignoring your ref.</p><p>It’s respecting the contract you chose.</p><h3>A Small Experiment You Should Try</h3><p>Open React DevTools.</p><p>If you haven’t used it much, today is a good day to start.</p><p>Create this component.</p><pre>function Demo() {<br>    const ref = useRef(0);<br>    console.log(&quot;Rendered&quot;);<br>    return (<br>        &lt;button<br>            onClick={() =&gt; {<br>                ref.current++;<br>                console.log(ref.current);<br>            }}<br>        &gt;<br>            Click<br>        &lt;/button&gt;<br>    );<br>}</pre><p>Now click the button several times.</p><p>Watch two things carefully.</p><p>First, the console.</p><p>You’ll see:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>Now look at React DevTools.</p><p>Notice something that’s easy to miss.</p><p>The component doesn’t render again.</p><p>React never schedules another render because, from its perspective, nothing happened that required recalculating the UI.</p><p>That observation alone explains more about useRef than memorizing its definition ever could.</p><h3>The Real Question Isn’t “Why Doesn’t useRef Re-render?&quot;</h3><p>After spending time understanding React’s internals, I realized I’d been asking the wrong question all along.</p><p>Instead of asking:</p><blockquote><em>“Why doesn’t </em><em>useRef trigger a re-render?&quot;</em></blockquote><p>A better question is:</p><blockquote><strong><em>“Why should React re-render just because I changed a value?”</em></strong></blockquote><p>That shift in thinking changes everything.</p><p>React isn’t trying to render as often as possible.</p><p>It’s trying to render <strong>only when necessary</strong>.</p><p>And that’s where we’ll go next.</p><p>Because understanding <em>why React knows to re-render for state but not for refs</em> takes us one layer deeper — into how React stores hooks internally, how updates are scheduled, and why useState and useRef follow completely different paths inside React.</p><h3>So… What Happens After You Call setState()?</h3><p>Let’s go back to something we already know.</p><pre>const [count, setCount] = useState(0);<br><br>setCount(1);</pre><p>The moment setCount() is called, React doesn&#39;t immediately render the component.</p><p>Instead, it begins an internal process.</p><p>A simplified version looks like this.</p><pre>   setState()<br>      │</pre><pre>      ▼</pre><pre>Create an Update</pre><pre>      │</pre><pre>      ▼</pre><pre>Tell React&#39;s Scheduler</pre><pre>      │</pre><pre>      ▼</pre><pre>Schedule a Render</pre><pre>      │</pre><pre>      ▼</pre><pre>Render Phase</pre><pre>      │</pre><pre>      ▼</pre><pre>Reconciliation</pre><pre>      │</pre><pre>      ▼</pre><pre>Commit Phase</pre><pre>      │</pre><pre>      ▼</pre><pre>Update the DOM</pre><p>There are a lot of details inside this pipeline, but notice something important.</p><p>The very first thing setState() does is tell React:</p><blockquote><em>“Hey, something important changed.”</em></blockquote><p>Once React hears that, it starts preparing another render.</p><p>Now compare that with a ref.</p><pre>ref.current++;</pre><p>What happens?</p><p>Almost nothing.</p><p>There is no update object.</p><p>No scheduler.</p><p>No render request.</p><p>No reconciliation.</p><p>No commit phase.</p><p>React simply lets JavaScript change the value.</p><p>That’s it.</p><h3>React Isn’t Watching Every Variable</h3><p>This was probably the biggest misconception I had when I started learning React.</p><p>I assumed React somehow “watched” every value inside a component.</p><p>Almost like this:</p><pre>Count changed</pre><pre>↓</pre><pre>React notices</pre><pre>↓</pre><pre>Render</pre><p>That’s not what happens.</p><p>React doesn’t continuously observe every variable in your component.</p><p>Imagine if it did.</p><pre>let name = &quot;Vikash&quot;;<br>name = &quot;Rahul&quot;;</pre><p>Should React render now?</p><p>What about this?</p><pre>const user = {};<br>user.name = &quot;Rahul&quot;;</pre><p>Should React render again?</p><p>What about this?</p><pre>const numbers = [];<br>numbers.push(10);</pre><p>Should React update the screen?</p><p>If React tried to watch every mutation in JavaScript, it would become incredibly slow.</p><p>Instead, React takes a much simpler approach.</p><p>It says:</p><blockquote><strong><em>“I won’t guess which values matter.”</em></strong></blockquote><blockquote><strong><em>“You tell me.”</em></strong></blockquote><p>And that’s exactly what setState() does.</p><p>It’s a signal.</p><p>Not just an assignment.</p><h3>The Small Difference That Changes Everything</h3><p>Let’s compare these two lines.</p><pre>setCount(10);</pre><p>and</p><pre>countRef.current = 10;</pre><p>At first glance, they both seem to update a value.</p><p>Internally, however, they’re completely different operations.</p><p>When you call:</p><pre>setCount(10);</pre><p>you’re not simply changing a variable.</p><p>You’re sending a message to React.</p><p>That message says:</p><blockquote><em>“The UI may need to change.”</em></blockquote><p>When you write:</p><pre>countRef.current = 10;</pre><p>you’re only modifying a plain JavaScript object.</p><p>React isn’t part of that operation.</p><p>It doesn’t receive a notification.</p><p>Nothing enters React’s update queue.</p><p>From React’s perspective, nothing happened.</p><h3>Wait… Isn’t useRef Also Stored by React?</h3><p>Yes.</p><p>And this surprises many developers.</p><p>A common assumption is:</p><blockquote><em>“useRef doesn&#39;t cause renders because React doesn&#39;t store it.&quot;</em></blockquote><p>That’s actually incorrect.</p><p>React <strong>does</strong> store refs.</p><p>Just like state.</p><p>In fact, both useState and useRef live inside the component&#39;s <strong>Fiber node</strong>.</p><p>If Fiber is a new term, don’t worry.</p><p>You don’t need to know every implementation detail today.</p><p>For now, think of Fiber as React’s internal record for every component.</p><p>A very simplified picture looks like this.</p><pre>  Component</pre><pre>      │</pre><pre>      ▼</pre><pre>Fiber</pre><pre> ├── State Hooks</pre><pre> ├── Ref Hooks</pre><pre> ├── Effect Hooks</pre><pre> ├── Props</pre><pre> └── Other Internal Data</pre><p>Every time your component renders, React doesn’t recreate everything from scratch.</p><p>Instead, it revisits this Fiber object.</p><p>That’s where it finds:</p><ul><li>your current state</li><li>your refs</li><li>pending effects</li><li>hook order</li><li>update queues</li></ul><p>So yes —</p><p>React absolutely knows your ref exists.</p><p>It simply treats it differently.</p><h3>Then Why Does React Ignore Ref Updates?</h3><p>This is the real design decision.</p><p>Imagine React rendered every time this happened.</p><pre>inputRef.current.focus();</pre><p>Render.</p><p>Now imagine this.</p><pre>scrollPosition.current = window.scrollY;</pre><p>Render.</p><p>Now imagine a timer.</p><pre>intervalRef.current = id;</pre><p>Render.</p><p>Now imagine storing the previous value.</p><pre>previousValue.current = value;</pre><p>Render.</p><p>None of these values affect what the user sees.</p><p>If React rendered after every one of these updates, your application would spend time recalculating the UI for absolutely no reason.</p><p>Instead, React says:</p><blockquote><em>“Mutable values are your responsibility.”</em></blockquote><p>That’s exactly what refs are.</p><p>A place where you can keep mutable information without asking React to redraw the interface.</p><h3>Let’s Look at the Ref Object</h3><p>One thing many developers don’t realize is that useRef() returns an ordinary JavaScript object.</p><p>Something very close to this:</p><pre>const ref = {<br>    current: 0<br>};</pre><p>That’s basically it.</p><p>When you do this:</p><pre>ref.current++;</pre><p>you’re doing exactly what JavaScript has always allowed.</p><p>You’re mutating an object’s property.</p><p>React isn’t intercepting that mutation.</p><p>There’s no hidden magic.</p><p>No Proxy.</p><p>No Observer.</p><p>No scheduler.</p><p>Just a plain object.</p><p>Understanding this removed a lot of mystery for me.</p><h3>What React Is Thinking</h3><p>Let’s imagine React sitting beside us again.</p><p>You write:</p><pre>setCount(count + 1);</pre><p>React replies:</p><blockquote><em>You called one of my update functions.</em></blockquote><blockquote><em>I’ll create an update.</em></blockquote><blockquote><em>I’ll schedule another render.</em></blockquote><blockquote><em>Then I’ll compare the old UI with the new one.</em></blockquote><p>Now you write:</p><pre>countRef.current++;</pre><p>React replies:</p><blockquote><em>I see you’re changing your own object.</em></blockquote><blockquote><em>That’s completely fine.</em></blockquote><blockquote><em>But you didn’t ask me to render.</em></blockquote><blockquote><em>I’ll let JavaScript handle it.</em></blockquote><p>Notice something.</p><p>React isn’t ignoring the update.</p><p>React is respecting your choice.</p><p>You chose a hook whose contract is:</p><blockquote><strong><em>Store this value, but don’t schedule rendering because of it.</em></strong></blockquote><p>That’s exactly what React does.</p><h3>A Quick DevTools Experiment</h3><p>Let’s verify everything we’ve discussed.</p><p>Create this component.</p><pre>function Demo() {<br>    const renders = useRef(0);<br>    renders.current++;<br>    console.log(renders.current);<br>    return &lt;h1&gt;Hello React&lt;/h1&gt;;<br>}</pre><p>Now refresh the page.</p><p>You might see:</p><pre>1</pre><p>Click somewhere else in your app so the component renders again.(Do a setup like that to call this render this component)</p><p>Now you’ll see:</p><pre>2</pre><p>Then:</p><pre>3</pre><p>Notice what’s happening.</p><p>The ref remembers its value.</p><p>Even though the component function runs again, the ref isn’t recreated.</p><p>That’s because React retrieves the same ref object from the Fiber.</p><p>This demonstrates two important facts at once:</p><ul><li>refs persist between renders</li><li>changing a ref doesn’t create a render</li></ul><p>Those two ideas often get mixed together.</p><p>They’re actually independent.</p><h3>The Difference Isn’t Storage</h3><p>If there’s one misconception I’d like you to leave behind after reading this article, it’s this one.</p><p>Many developers think:</p><blockquote><em>State causes renders because React stores it.</em></blockquote><p>That’s not the real reason.</p><p>React stores refs too.</p><p>The real difference is this:</p><p>State updates enter React’s scheduling system.</p><p>Ref updates don’t.</p><p>That one sentence explains almost every behavioral difference between useState and useRef.</p><h3>A Mental Picture That Helped Me</h3><p>Nowadays, I imagine React keeping two different notebooks.</p><p>The first notebook contains things React needs to pay attention to.</p><pre>State</pre><pre>↓</pre><pre>Important</pre><pre>↓</pre><pre>Render when changed</pre><p>The second notebook contains things that belong to me.</p><pre>Refs</pre><pre>↓</pre><pre>Useful Information</pre><pre>↓</pre><pre>No Render Required</pre><p>Both notebooks survive between renders.</p><p>The difference is that React only watches one of them for UI updates.</p><p>Once I started thinking this way, choosing between useState and useRef became much more intuitive.</p><h3>So… When Should You Use useRef?</h3><p>Understanding <em>why</em> useRef doesn&#39;t trigger re-renders is useful.</p><p>Knowing <strong>when to reach for it</strong> is what makes you a better React developer.</p><p>One thing I’ve noticed over the years is that developers often choose between useState and useRef based on habit.</p><p>Instead, I now ask myself one simple question before creating either hook.</p><blockquote><strong><em>“If this value changes, should the user see a different UI?”</em></strong></blockquote><p>If the answer is <strong>yes</strong>, it belongs in state.</p><p>If the answer is <strong>no</strong>, a ref is probably a better choice.</p><p>That single question has saved me from a surprising number of unnecessary re-renders.</p><p>Let’s look at some real examples.</p><h3>Real Project Example 1 — Focusing an Input</h3><p>Imagine you’re building a login form.</p><p>When the page opens, you want the email input to receive focus automatically.</p><pre>function Login() {<br>    const inputRef = useRef(null);<br><br>    useEffect(() =&gt; {<br>        inputRef.current.focus();<br>    }, []);<br>    return &lt;input ref={inputRef} /&gt;;<br>}</pre><p>Notice something.</p><p>When the input receives focus…</p><p>Does the UI itself change?</p><p>No.</p><p>The browser simply places the cursor inside the input.</p><p>React doesn’t need to render anything again.</p><p>A ref is the perfect tool here.</p><h3>Real Project Example 2 — Storing a Timer</h3><p>I remember debugging a countdown component one evening where every button click accidentally created another interval.</p><p>The fix wasn’t complicated.</p><p>We simply stored the interval ID inside a ref.</p><pre>const timerRef = useRef(null);<br><br>function startTimer() {<br>    timerRef.current = setInterval(() =&gt; {<br>        console.log(&quot;Running...&quot;);<br>    }, 1000);<br>}<br><br>function stopTimer() {<br>    clearInterval(timerRef.current);<br>}</pre><p>Ask yourself:</p><p>Should storing an interval ID change what users see?</p><p>Not really.</p><p>It’s just information your component needs later.</p><p>Again, a perfect use case for useRef.</p><h3>Real Project Example 3 — Remembering the Previous Value</h3><p>Sometimes you want to compare the current value with the previous one.</p><p>For example:</p><pre>const previousCount = useRef();<br><br>useEffect(() =&gt; {<br>    previousCount.current = count;<br>}, [count]);</pre><p>Now you always have access to:</p><ul><li>Current count</li><li>Previous count</li></ul><p>Without causing additional renders.</p><h3>Real Project Example 4 — Tracking Scroll Position</h3><p>Suppose you’re building an infinite scrolling page.</p><pre>const scrollPosition = useRef(0);</pre><pre>window.addEventListener(&quot;scroll&quot;, () =&gt; {<br>    scrollPosition.current = window.scrollY;<br>});</pre><p>During scrolling, this value changes dozens of times every second.</p><p>Imagine React re-rendered the component every single time.</p><p>Scrolling would quickly become sluggish.</p><p>Because it’s stored in a ref, React stays out of the way.</p><h3>The Biggest Mistake I See in React Code Reviews</h3><p>This is something I’ve come across more than once.</p><pre>const username = useRef(&quot;&quot;);<br><br>return &lt;h2&gt;{username.current}&lt;/h2&gt;;</pre><p>Later…</p><pre>username.current = &quot;Vikash&quot;;</pre><p>Then someone asks:</p><blockquote><em>“Why isn’t my heading updating?”</em></blockquote><p>The answer should make sense now.</p><p>React only updates the UI after a render.</p><p>Changing a ref never schedules one.</p><p>If the UI depends on the value…</p><p>It shouldn’t be a ref in the first place.</p><p>It should be state.</p><h3>Another Common Mistake</h3><p>Sometimes developers use state simply because they need to remember a value.</p><p>For example:</p><pre>const [timeoutId, setTimeoutId] = useState(null);</pre><p>But the timeout ID is never displayed anywhere.</p><p>Every update now causes another render that serves no purpose.</p><p>This is a perfect example of something that belongs in a ref.</p><pre>const timeoutRef = useRef(null);</pre><p>Sometimes improving performance isn’t about adding React.memo.</p><p>It’s about choosing the correct hook.</p><h3>useState vs useRef</h3><p>Here’s the comparison I keep in my head while building components.</p><p>QuestionuseState useRef</p><p>Does React remember the value? Yes Yes</p><p>Does changing it schedule a render? Yes No</p><p>Should it affect the UI? Yes Usually No</p><p>Good for forms and displayed data? Yes No</p><p>Good for DOM nodes? No Yes</p><p>Good for timers, intervals, mutable values? Usually No Yes</p><p>Whenever I’m unsure, I don’t think about the hook.</p><p>I think about the responsibility.</p><h3>A Small Exercise</h3><p>Imagine you’re building a video player.</p><p>Which hook would you choose for these values?</p><ul><li>Current playback time</li><li>Whether the play button says <strong>Play</strong> or <strong>Pause</strong></li><li>The video element itself</li><li>Interval ID</li><li>Current volume shown on screen</li></ul><p>Think for a moment before reading further.</p><p>Here’s how I’d approach it.</p><p>ValueHookPlayback time displayed on screenuseStatePlay/Pause labeluseStateVideo DOM elementuseRefInterval IDuseRefVolume displayed in UIuseState</p><p>Notice the pattern.</p><p>If users can see it…</p><p>State.</p><p>If it’s simply something your code needs…</p><p>Ref.</p><h3>Interview Corner</h3><p>This question appears surprisingly often.</p><blockquote><strong><em>Why doesn’t updating </em></strong><strong><em>ref.current trigger a re-render?</em></strong></blockquote><p>A good answer isn’t:</p><blockquote><em>“Because React doesn’t track refs.”</em></blockquote><p>A stronger answer is:</p><blockquote><em>“useRef returns a mutable object whose value React stores between renders. Updating </em><em>ref.current mutates that object directly, but unlike </em><em>setState, it doesn&#39;t create an update or enter React&#39;s scheduling system. Since React never schedules another render, reconciliation and the commit phase never run. That&#39;s why the UI doesn&#39;t update.</em></blockquote><p>That answer demonstrates understanding instead of memorization.</p><h3>The Mental Model I Want You to Remember</h3><p>Imagine you’re working with a whiteboard.</p><p>One side belongs to React.</p><p>The other belongs to you.</p><pre>+-------------------------------------------+<br>|           React&#39;s Whiteboard              |<br>|-------------------------------------------|<br>| State                                     |<br>| Props                                     |<br>| Context                                   |<br>|                                           |<br>| &quot;If these change, I&#39;ll render again.&quot;     |<br>+-------------------------------------------+</pre><pre>+-------------------------------------------+<br>|            Your Whiteboard                |<br>|-------------------------------------------|<br>| ref.current                               |<br>| Timer IDs                                 |<br>| DOM Nodes                                 |<br>| Previous Values                           |<br>| Mutable Objects                           |<br>|                                           |<br>| &quot;I&#39;ll store these, but I won&#39;t render.&quot;   |<br>+-------------------------------------------+</pre><p>Both whiteboards survive between renders.</p><p>The difference is simple.</p><p>React only watches one of them.</p><p>Whenever you forget which hook to use, come back to this picture.</p><h3>Let’s Connect This with Everything We’ve Learned</h3><p>If you’ve followed this series from the beginning, you can probably see how all these concepts fit together now.</p><p>A typical React update looks like this:</p><pre>User clicks a button<br>        │<br>        ▼<br>setState()<br>        │<br>        ▼<br>React Scheduler<br>        │<br>        ▼<br>Render Phase<br>        │<br>        ▼<br>New React Element Tree<br>        │<br>        ▼<br>Reconciliation<br>        │<br>        ▼<br>Commit Phase<br>        │<br>        ▼<br>DOM Updates</pre><p>Now compare that with a ref update.</p><pre>ref.current = value<br>        │<br>        ▼<br>JavaScript updates the object<br>        │<br>        ▼<br>React Scheduler is never notified<br>        │<br>        ▼<br>No Render<br>        │<br>        ▼<br>No Reconciliation<br>        │<br>        ▼<br>No Commit Phase</pre><p>That one diagram connects almost every article we’ve written so far.</p><h3>Key Takeaways</h3><ul><li>Both useState and useRef persist values between renders.</li><li>React stores both hooks internally.</li><li>Calling setState() schedules a render because React assumes the UI may have changed.</li><li>Updating ref.current simply mutates a JavaScript object.</li><li>Since no update is scheduled, React doesn’t render the component again.</li><li>Use state for values that affect what users see.</li><li>Use refs for values your component needs but the UI doesn’t directly depend on.</li></ul><h3>Final Thoughts</h3><p>When I first started using React, I treated useRef as a lighter version of useState.</p><p>The names were different, but in my mind they solved almost the same problem.</p><p>After spending more time understanding React’s rendering model, I realized that wasn’t the right way to think about them.</p><p>useState isn&#39;t just a place to store data.</p><p>It’s React’s way of saying:</p><blockquote><em>“This piece of information is part of my UI. Let me know whenever it changes.”</em></blockquote><p>useRef isn&#39;t a simpler state.</p><p>It’s your own storage space inside a component — one that React intentionally leaves alone.</p><p>Once I started thinking in terms of responsibilities instead of APIs, choosing between them became almost automatic.</p><p>Now, whenever I create a new piece of data in a component, I ask myself one question.</p><blockquote><strong><em>“If this value changes, should the user notice?”</em></strong></blockquote><p>If the answer is yes, I reach for useState.</p><p>If the answer is no, I usually reach for useRef.</p><p>That single question has probably prevented more bugs than any React trick I’ve learned over the years.</p><h3>React Internals Series</h3><p>If this article helped you better understand how React thinks, you might enjoy the rest of the series. Each article builds on the previous one, so reading them in order gives you a strong mental model of React’s rendering pipeline.</p><p><strong>Part 1 — </strong><a href="https://medium.com/@vikash_yadav_41088/does-useeffect-trigger-re-renders-a-common-react-misconception-784706ee21ce?sharedUserId=vikash_yadav_41088"><strong>Does </strong></a><a href="https://medium.com/@vikash_yadav_41088/does-useeffect-trigger-re-renders-a-common-react-misconception-784706ee21ce?sharedUserId=vikash_yadav_41088"><strong>useEffect Trigger Re-renders? A Common React Misconception</strong></a></p><p><strong>Part 2 —</strong><a href="https://medium.com/works-on-my-machine/what-actually-causes-a-react-component-to-re-render-66976be65f33"><strong> What Actually Causes a React Component to Re-render?</strong></a></p><p><strong>Part 3 — </strong><a href="https://medium.com/works-on-my-machine/react-render-phase-vs-commit-phase-what-really-happens-behind-the-scenes-9ff1a8d13b1d"><strong>React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?</strong></a></p><p><strong>Part 4 — </strong><a href="https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e"><strong>Why React Needs Keys — And Why </strong></a><a href="https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e"><strong>index as a Key Can Break More Than You Think</strong></a></p><p><strong>Part 5 —</strong><a href="https://medium.com/works-on-my-machine/understanding-react-reconciliation-how-react-decides-what-to-update-ec93067fcada"><strong> Understanding React Reconciliation: How React Decides What to Update</strong></a></p><p><strong>Part 6 — Why Doesn’t </strong><strong>useRef Trigger Re-renders? The Mental Model Every React Developer Should Know</strong><em>(Current Article)</em></p><h3>What’s Next?</h3><p>So far, we’ve explored how React decides <strong>when</strong> to render and <strong>why</strong> it sometimes chooses not to.</p><p>The next logical step is to look at something that confuses almost every React developer at least once:</p><h3>Where Does React Actually Store State?</h3><p>If every render creates a brand-new function call, why doesn’t React lose your state?</p><p>How does React know that the count from your previous render is the same count you read in the next one?</p><p>We’ll explore how Hooks are stored, why hook order matters, what the Fiber tree really keeps track of, and why changing the order of hooks breaks everything.</p><p>By the end of that article, you’ll have an even clearer picture of what React is doing behind the scenes every time your component renders.</p><blockquote>Enjoyed this article? 👏 Give it a clap (or 50!) and follow the writer for more of their work. Don’t forget to follow <a href="https://medium.com/works-on-my-machine">WORKS ON MY MACHINE</a> so you never miss a story.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cacc2d60fd57" width="1" height="1" alt=""><hr><p><a href="https://medium.com/works-on-my-machine/why-doesnt-useref-trigger-re-renders-cacc2d60fd57">Why Doesn’t useRef Trigger Re-renders?</a> was originally published in <a href="https://medium.com/works-on-my-machine">Works On My Machine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding React Reconciliation: How React Decides What to Update]]></title>
            <link>https://medium.com/works-on-my-machine/understanding-react-reconciliation-how-react-decides-what-to-update-ec93067fcada?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec93067fcada</guid>
            <category><![CDATA[rendering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[document-object-model]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Wed, 22 Jul 2026 18:40:03 GMT</pubDate>
            <atom:updated>2026-07-23T12:10:48.157Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hcGwhXOFsC6AkMlB8nTRHg.png" /></figure><p>A few weekends ago, I was trying to optimize a dashboard that rendered hundreds of rows.</p><p>Nothing looked particularly expensive.</p><p>The components were fairly small.</p><p>The API wasn’t slow.</p><p>Yet every interaction felt just a little heavier than it should.</p><p>Naturally, I opened React DevTools and started looking at what was re-rendering.</p><p>One component rendered.</p><p>Then another.</p><p>Then another.</p><p>That part made sense.</p><p>But what I couldn’t stop wondering was something much simpler.</p><p>When React renders a component again…</p><p><strong>How does it know what actually needs to change on the screen?</strong></p><p>Surely it doesn’t delete the entire page and recreate everything.</p><p>That would be incredibly slow.</p><p>The answer lies in one of React’s core ideas:</p><p><strong>Reconciliation.</strong></p><p>If you’ve been following this series, we’ve already discussed:</p><ul><li>What causes a component to re-render</li><li>The difference between the Render Phase and Commit Phase</li><li>Why keys matter</li></ul><p>Reconciliation is the piece that connects all of those ideas together.</p><p>It’s the process React uses to decide:</p><blockquote><em>“Given the previous UI and the new UI, what is the smallest amount of work I need to do?”</em></blockquote><p>Let’s see how it works.</p><h3>First, What Is Reconciliation?</h3><p>Reconciliation is React’s algorithm for comparing two versions of the UI.</p><p>Think of it like reviewing two versions of the same document.</p><p>Imagine you wrote an article yesterday.</p><p>Today, you change only one sentence.</p><p>If someone asks,</p><blockquote><em>“What changed?”</em></blockquote><p>you wouldn’t rewrite the entire article.</p><p>You’d simply point to that one sentence.</p><p>React does something very similar.</p><p>Every time your component renders, React gets a new description of the UI.</p><p>Instead of rebuilding everything, it compares that new description with the previous one.</p><p>Then it updates only what’s necessary.</p><h3>Let’s Start With a Simple Example</h3><p>Suppose your component returns:</p><pre>&lt;h1&gt;Hello, Vikash&lt;/h1&gt;</pre><p>Later, after updating some state, it returns:</p><pre>&lt;h1&gt;Hello, Rahul&lt;/h1&gt;</pre><p>React compares the two trees.</p><p>It notices:</p><ul><li>The &lt;h1&gt; element is still there.</li><li>Only the text changed.</li></ul><p>Instead of replacing the whole element, React simply updates the text node.</p><p>That’s reconciliation doing its job.</p><h3>Another Example</h3><p>Now imagine this:</p><p>First render:</p><pre>&lt;div&gt;<br>    &lt;h1&gt;Dashboard&lt;/h1&gt;<br>    &lt;button&gt;Save&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Second render:</p><pre>&lt;div&gt;<br>    &lt;h1&gt;Dashboard&lt;/h1&gt;<br>    &lt;button&gt;Submit&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Again, React compares both trees.</p><p>It sees:</p><ul><li>The &lt;div&gt; didn&#39;t change.</li><li>The &lt;h1&gt; didn&#39;t change.</li><li>Only the button text changed.</li></ul><p>So the browser only updates the button text.</p><p>Everything else stays untouched.</p><h3>React Doesn’t Compare the Real DOM First</h3><p>This is something I misunderstood when I started learning React.</p><p>I assumed React constantly looked at the browser DOM to decide what changed.</p><p>It doesn’t.</p><p>React compares two <strong>React element trees</strong> first.</p><p>Only after reconciliation finishes does React know which DOM updates are actually required.</p><p>That’s an important distinction.</p><p>The browser DOM is expensive to manipulate.</p><p>Comparing lightweight JavaScript objects is much cheaper.</p><p>That’s one reason React performs so well.</p><h3>What Exactly Is React Comparing?</h3><p>Every render produces a new tree of React elements.</p><p>A simplified example might look like this:</p><pre>App<br> ├── Header<br> ├── Sidebar<br> └── Dashboard<br>      ├── Card<br>      ├── Card<br>      └── Card</pre><p>When something changes, React creates another tree.</p><p>Now reconciliation starts.</p><p>React walks through both trees and asks questions like:</p><ul><li>Is this the same element?</li><li>Did its props change?</li><li>Is this node still here?</li><li>Was something removed?</li><li>Was something added?</li></ul><p>Every answer helps React determine what work needs to happen during the Commit Phase.</p><h3>What Happens When Element Types Change?</h3><p>Suppose your first render returns:</p><pre>&lt;h1&gt;Hello&lt;/h1&gt;</pre><p>Later it returns:</p><pre>&lt;p&gt;Hello&lt;/p&gt;</pre><p>Even though the text is identical, the element type changed.</p><p>React treats these as different elements.</p><p>The old &lt;h1&gt; is removed.</p><p>A new &lt;p&gt; is created.</p><p>Why?</p><p>Because changing the element type usually means the structure has fundamentally changed.</p><h3>Where Keys Become Important</h3><p>In the previous article, we talked about keys.</p><p>Now we can see why they matter.</p><p>Imagine this list:</p><pre>[<br>  &quot;Alice&quot;,<br>  &quot;Bob&quot;,<br>  &quot;Charlie&quot;<br>]</pre><p>Now Bob is deleted.</p><p>Without keys, React mainly compares items by their position.</p><p>With stable keys, React can immediately identify:</p><ul><li>Alice stayed.</li><li>Bob disappeared.</li><li>Charlie stayed.</li></ul><p>That means React performs less unnecessary work and preserves component state correctly.</p><p>Keys aren’t just identifiers.</p><p>They’re one of the inputs reconciliation uses to match elements between renders.</p><h3>React Doesn’t Always Update the DOM</h3><p>Here’s something that surprised me when I first learned it.</p><p>A component can render again…</p><p>Reconciliation can run…</p><p>And the DOM still doesn’t change.</p><p>Consider this component:</p><pre>function Greeting() {<br>    return &lt;h1&gt;Hello React&lt;/h1&gt;;<br>}</pre><p>Suppose React renders it again because its parent rendered.</p><p>React still compares the new tree with the previous one.</p><p>After comparing both trees, it realizes:</p><p>Nothing actually changed.</p><p>So no DOM updates are necessary.</p><p>The render happened.</p><p>The comparison happened.</p><p>The browser stayed exactly the same.</p><p>This is why rendering isn’t always expensive.</p><p>DOM manipulation usually is.</p><h3>Reconciliation Is All About Doing Less Work</h3><p>One way I like to think about reconciliation is this.</p><p>Imagine you’re proofreading a book.</p><p>Someone changes one comma.</p><p>You wouldn’t print the entire book again.</p><p>You’d change that one comma.</p><p>React follows the same philosophy.</p><p>It tries to reuse as much of the existing UI as possible.</p><p>Only the parts that genuinely changed get updated.</p><h3>A Common Misunderstanding</h3><p>Sometimes people say,</p><blockquote><em>“React re-rendered everything.”</em></blockquote><p>That’s not entirely accurate.</p><p>React may execute many component functions.</p><p>But after reconciliation, only a small part of the DOM might actually change.</p><p>Those are two different things.</p><p>Understanding this difference helped me stop worrying every time I saw a render in React DevTools.</p><p>A render doesn’t automatically mean expensive work happened.</p><h3>Why This Matters for Performance</h3><p>Once you understand reconciliation, several React concepts start making more sense.</p><p>For example:</p><ul><li>Why stable keys improve list rendering.</li><li>Why React.memo can prevent unnecessary work.</li><li>Why changing object references can trigger more rendering than expected.</li><li>Why React is often much faster than directly manipulating the DOM yourself.</li></ul><p>Performance isn’t about preventing every render.</p><p>It’s about helping React avoid unnecessary work during reconciliation.</p><h3>The Mental Model That Helped Me</h3><p>Today, when I think about reconciliation, I imagine React asking a series of simple questions.</p><blockquote><em>Is this still the same element?</em></blockquote><blockquote><em>Can I reuse this?</em></blockquote><blockquote><em>Did something move?</em></blockquote><blockquote><em>Did something disappear?</em></blockquote><blockquote><em>What is the smallest change I can make?</em></blockquote><p>That’s all reconciliation really is.</p><p>A fast comparison process whose goal is to avoid doing more work than necessary.</p><h3>Key Takeaways</h3><ul><li>Reconciliation is React’s process of comparing the previous UI with the new UI.</li><li>React compares React element trees before touching the browser DOM.</li><li>Only the parts that actually changed are updated.</li><li>Stable keys help reconciliation correctly identify elements between renders.</li><li>A render does not automatically mean the DOM changes.</li><li>The goal of reconciliation is to minimize DOM updates while keeping the UI correct.</li></ul><p>When I first started learning React, reconciliation sounded like one of those complicated internal terms that only framework contributors needed to understand.</p><p>It turned out to be the opposite.</p><p>Once I understood what reconciliation was trying to achieve, a lot of React’s behavior stopped feeling mysterious.</p><p>Instead of thinking,</p><blockquote><em>“Why is React doing this?”</em></blockquote><p>I started thinking,</p><blockquote><em>“React is just trying to figure out the smallest possible update.”</em></blockquote><p>And that’s a much better mental model to carry into every React project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec93067fcada" width="1" height="1" alt=""><hr><p><a href="https://medium.com/works-on-my-machine/understanding-react-reconciliation-how-react-decides-what-to-update-ec93067fcada">Understanding React Reconciliation: How React Decides What to Update</a> was originally published in <a href="https://medium.com/works-on-my-machine">Works On My Machine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why React Needs Keys — And Why index as a Key Can Break More Than You Think]]></title>
            <link>https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/43eeeb4df84e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rerender]]></category>
            <category><![CDATA[keys-in-react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 17:17:41 GMT</pubDate>
            <atom:updated>2026-07-15T17:17:41.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ru_WgndxY0QvHiak5LyeBg.png" /></figure><p>There was one bug that stayed with me for much longer than I’d like to admit.<br>It happened on a Monday morning while I was working on a small dashboard feature.</p><p>Nothing looked unusual.<br>The page displayed a list of users.<br>Each user had a checkbox.<br>Users could be removed from the list.<br>Simple enough.</p><p>Everything worked perfectly…<br>Until I deleted the second user.<br>Suddenly, another checkbox appeared selected.<br>For a second, I thought the state management was broken.<br>I checked my reducer.<br>I checked my API response.<br>I even added a few console.log() statements.<br>Everything looked correct.<br>The actual problem wasn’t my state.</p><p>It was this line:</p><pre>users.map((user, index) =&gt; (<br>    &lt;UserCard key={index} user={user} /&gt;<br>))</pre><p>At that moment I realized something important.</p><p>Keys aren’t there to remove React warnings.</p><p>They’re how React keeps track of which component is which.</p><p>Once I understood that, React’s reconciliation process made much more sense.</p><p>Let’s talk about why.</p><h3>First, Why Does React Need Keys?</h3><p>Imagine React didn’t have keys.</p><p>Suppose your component renders this list.</p><pre>[<br>  &quot;Alice&quot;,<br>  &quot;Bob&quot;,<br>  &quot;Charlie&quot;<br>]</pre><p>A few seconds later it becomes</p><pre>[<br>  &quot;Alice&quot;,<br>  &quot;Charlie&quot;<br>]</pre><p>React now has a problem.</p><p>It knows the UI changed.</p><p>But it doesn’t know <strong>which item disappeared.</strong></p><p>Did Bob disappear?</p><p>Did Charlie move?</p><p>Did Alice change?</p><p>Without extra information, React has to guess.</p><p>That’s exactly what keys solve.</p><h3>Keys Give Every Element an Identity</h3><p>Think of keys like employee IDs inside a company.</p><p>Imagine two employees have the same first name.</p><p>If someone says,</p><blockquote><em>“Rahul submitted the report.”</em></blockquote><p>Which Rahul?</p><p>Nobody knows.</p><p>But if every employee has an Employee ID, the confusion disappears.</p><p>React works in a similar way.</p><p>Instead of remembering</p><blockquote><em>“the second item”</em></blockquote><p>React remembers</p><blockquote><em>“the item whose key is 24”</em></blockquote><p>That identity stays consistent across renders.</p><h3>A Better Example</h3><p>Suppose you render</p><pre>[<br>  { id: 101, name: &quot;Alice&quot; },<br>  { id: 102, name: &quot;Bob&quot; },<br>  { id: 103, name: &quot;Charlie&quot; }<br>]</pre><pre>users.map(user =&gt; (<br>    &lt;UserCard<br>        key={user.id}<br>        user={user}<br>    /&gt;<br>))</pre><p>Later Bob gets deleted.</p><p>Now React sees</p><pre>101<br>102<br>103</pre><p>becoming</p><pre>101<br>103</pre><p>Immediately React understands</p><blockquote><em>Key 102 disappeared.</em></blockquote><p>Everything else stays exactly the same.</p><p>No guessing required.</p><h3>Where Keys Are Actually Used</h3><p>Earlier in this series we talked about the <strong>Render Phase</strong> and <strong>Commit Phase</strong>.</p><p>During the Render Phase, React creates a new tree.</p><p>Then reconciliation compares it with the previous tree.</p><p>This comparison heavily relies on keys.</p><p>Instead of comparing only by position, React compares by identity.</p><p>That makes updates much faster and much safer.</p><h3>What Happens Without Keys?</h3><p>Suppose React only compared items by their position.</p><p>Previous render</p><pre>0 Alice<br>1 Bob<br>2 Charlie</pre><p>Next render</p><pre>0 Alice<br>1 Charlie</pre><p>React might think</p><blockquote><em>Position 1 changed from Bob to Charlie.</em></blockquote><p>Instead of understanding</p><blockquote><em>Bob was removed.</em></blockquote><p>That small misunderstanding can lead to components keeping the wrong internal state.</p><h3>So What’s Wrong With Using index?</h3><p>Let’s look at this code.</p><pre>users.map((user, index) =&gt; (<br>    &lt;UserCard<br>        key={index}<br>        user={user}<br>    /&gt;<br>))</pre><p>Initially</p><pre>0 Alice<br>1 Bob<br>2 Charlie</pre><p>Delete Bob.</p><p>Now</p><pre>0 Alice<br>1 Charlie</pre><p>Notice what happened.</p><p>Charlie used to have key</p><pre>2</pre><p>Now Charlie suddenly has key</p><pre>1</pre><p>From React’s perspective,</p><p>that’s not Charlie anymore.</p><p>It’s an entirely different component.</p><p>That means React may reuse component instances incorrectly.</p><p>If those components contain local state,</p><p>unexpected bugs can appear.</p><h3>A Real Example</h3><p>Imagine every row contains an input.</p><pre>&lt;UserRow<br>    key={index}<br>/&gt;</pre><p>A user types</p><pre>Alice<br>Bob<br>Charlie</pre><p>Now delete Bob.</p><p>Without stable keys,</p><p>React may reuse the old component instance.</p><p>The input that previously belonged to Bob can suddenly appear under Charlie.</p><p>The data didn’t move.</p><p>The component identity did.</p><p>Those are the bugs that usually take much longer to debug than they should.</p><h3>Does That Mean index Is Always Wrong?</h3><p>Not really.</p><p>This is something I misunderstood early in my React journey.</p><p>You’ll often hear</p><blockquote><em>Never use index as a key.</em></blockquote><p>That’s a good rule of thumb.</p><p>But it’s not an absolute rule.</p><p>Using the index is generally fine when:</p><ul><li>the list never changes order</li><li>items are never inserted</li><li>items are never deleted</li><li>the list is completely static</li></ul><p>For example,</p><pre>const weekdays = [<br>    &quot;Monday&quot;,<br>    &quot;Tuesday&quot;,<br>    &quot;Wednesday&quot;<br>];</pre><p>This list will probably never change.</p><p>Using the index here is unlikely to cause problems.</p><p>The issue starts when the list becomes dynamic.</p><h3>What Makes a Good Key?</h3><p>A good key should be</p><ul><li>unique among sibling elements</li><li>stable between renders</li><li>derived from the actual data</li></ul><p>Database IDs are usually perfect.</p><pre>key={user.id}</pre><p>UUIDs also work well.</p><pre>key={product.uuid}</pre><p>Anything that changes every render should be avoided.</p><p>For example,</p><pre>key={Math.random()}</pre><p>or</p><pre>key={Date.now()}</pre><p>These create a completely new identity every render.</p><p>React ends up throwing away the old component and creating a new one every time.</p><h3>The Mental Model That Helped Me</h3><p>Nowadays I don’t think of keys as something that satisfies React.</p><p>I think of them as <strong>names that React uses to recognize components across renders.</strong></p><p>Without names,</p><p>React has to guess.</p><p>With stable names,</p><p>React knows exactly which component stayed,</p><p>which moved,</p><p>which disappeared,</p><p>and which one is brand new.</p><p>Once I started looking at keys this way,</p><p>the warning message in the console stopped feeling like an annoying reminder and started making perfect sense.</p><h3>Key Takeaways</h3><ul><li>Keys are not just for removing React warnings.</li><li>They give elements a stable identity across renders.</li><li>React uses keys during reconciliation to match old and new elements.</li><li>Stable keys help preserve component state.</li><li>Using index can lead to subtle bugs when lists change.</li><li>index is generally acceptable for static lists that never reorder or change.</li><li>Whenever possible, use a unique identifier from your data instead.</li></ul><p>React isn’t asking for keys because it likes extra code.</p><p>It’s asking because, just like us, it needs a reliable way to recognize what’s changed and what’s still the same.</p><h3>What’s Next?</h3><p>So far in this series we’ve answered three important questions:</p><ul><li>What actually causes a React component to re-render?</li><li>What happens during the Render Phase and Commit Phase?</li><li>Why do keys matter during reconciliation?</li></ul><p>The next logical step is to look at the engine behind all of these ideas:</p><h3>Understanding React Reconciliation: How React Decides What to Update</h3><p>We’ll explore how React compares two UI trees, why some updates are surprisingly cheap, and how understanding reconciliation can help you write components that are both simpler and more performant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43eeeb4df84e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/works-on-my-machine/why-react-needs-keys-and-why-index-as-a-key-can-break-more-than-you-think-43eeeb4df84e">Why React Needs Keys — And Why index as a Key Can Break More Than You Think</a> was originally published in <a href="https://medium.com/works-on-my-machine">Works On My Machine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?]]></title>
            <link>https://medium.com/works-on-my-machine/react-render-phase-vs-commit-phase-what-really-happens-behind-the-scenes-9ff1a8d13b1d?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ff1a8d13b1d</guid>
            <category><![CDATA[react-render-phase]]></category>
            <category><![CDATA[reconciliation]]></category>
            <category><![CDATA[react-hook-useeffect]]></category>
            <category><![CDATA[uselayouteffect-hook]]></category>
            <category><![CDATA[react-commit-phase]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 10:43:01 GMT</pubDate>
            <atom:updated>2026-07-08T10:43:01.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zf-36evgi9NyTVtbM3w1fA.png" /></figure><p>A few months ago, I was debugging a React screen late in the evening after work.</p><p>Nothing unusual at first — a fairly normal component, one useEffect, one API call, and a UI that looked fine most of the time.</p><p>But then I noticed something odd.</p><p>A console.log() inside the component was running before an effect.<br>A console.log() inside useEffect was running later.<br>And when I changed a piece of state, I could see React doing work in an order that wasn’t obvious if you only think in terms of “the component rendered.”</p><p>That was one of those moments where React stops feeling like “just components and hooks” and starts feeling like a rendering engine with its own internal pipeline.</p><p>And that’s exactly what it is.</p><p>If you’ve worked with React for a while, you’ve probably heard terms like:</p><ul><li><strong>rendering</strong></li><li><strong>commit</strong></li><li><strong>reconciliation</strong></li><li><strong>effects</strong></li><li><strong>layout effects</strong></li></ul><p>These words get used a lot, but they often get compressed into one vague idea:</p><blockquote><em>“React renders the component and then does some stuff.”</em></blockquote><p>The problem is that React doesn’t just have one “render step.”</p><p>At a high level, React’s work is split into <strong>two important phases</strong>:</p><ol><li><strong>Render Phase</strong></li><li><strong>Commit Phase</strong></li></ol><p>Once you understand the difference between these two, a lot of React behavior starts making more sense — especially useEffect, useLayoutEffect, re-renders, and why some logic belongs in render while other logic must wait until after the DOM updates.</p><p>Let’s break it down carefully.</p><h3>The Big Picture</h3><p>When React needs to update the UI, it doesn’t immediately change the DOM the moment something happens.</p><p>Instead, it roughly goes through a flow like this:</p><pre>Something changes<br>   ↓<br>React starts the Render Phase<br>   ↓<br>React figures out what the UI should look like next<br>   ↓<br>React enters the Commit Phase<br>   ↓<br>React updates the DOM<br>   ↓<br>Effects run</pre><p>That’s the mental model I keep in mind now.</p><p>The <strong>Render Phase</strong> is where React calculates.</p><p>The <strong>Commit Phase</strong> is where React applies changes.</p><p>That distinction matters a lot.</p><h3>First: What is the Render Phase?</h3><p>The <strong>Render Phase</strong> is the phase where React decides what the next version of the UI should be.</p><p>In simple terms, React executes your component functions and builds a new representation of the UI.</p><p>For example:</p><pre>function Counter({ count }) {<br>  return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>When React renders this component, it calls the function:</p><pre>Counter({ count: 5 })</pre><p>and gets back:</p><pre>&lt;h1&gt;5&lt;/h1&gt;</pre><p>That’s the render phase in action.</p><p>React is asking:</p><blockquote><em>“If I run this component with the latest props and state, what UI should it return?”</em></blockquote><p>It’s important to notice what React is <strong>not</strong> doing yet.</p><p>During the render phase, React is <strong>not directly updating the browser DOM</strong>.</p><p>It’s only computing what should change.</p><h3>What Happens During the Render Phase?</h3><p>A few important things happen here:</p><ul><li>React calls your component function</li><li>React reads the current state and props</li><li>React evaluates the JSX you return</li><li>React builds a new React element tree</li><li>React compares it with the previous one to determine what changed</li></ul><p>This is why I often describe render phase as <strong>“React preparing the next UI”</strong> rather than “React painting the screen.”</p><p>It’s preparation work.</p><p>Not DOM mutation.</p><h3>A Simple Example</h3><p>Take this component:</p><pre>function Profile({ name }) {<br>  console.log(&quot;Profile render&quot;);<br>  return &lt;h1&gt;Hello, {name}&lt;/h1&gt;;<br>}</pre><p>If name changes from &quot;Vikash&quot; to &quot;Rahul&quot;, React will run Profile again.</p><p>During the render phase:</p><ul><li>Profile() executes</li><li>React sees the new JSX output</li><li>React notices that the text content should change</li></ul><p>But the browser DOM hasn’t been updated yet at this point.</p><p>React has only figured out <em>what</em> needs to change.</p><h3>Then Comes the Commit Phase</h3><p>Once React finishes calculating the next UI, it moves to the <strong>Commit Phase</strong>.</p><p>This is the phase where React applies the changes to the real DOM.</p><p>If the render phase determined that:</p><ul><li>a text node changed,</li><li>a class name changed,</li><li>an element should be inserted,</li><li>an element should be removed,</li></ul><p>the commit phase is where those updates actually happen in the browser.</p><p>So if the render phase is:</p><blockquote><em>“What should the UI look like?”</em></blockquote><p>then the commit phase is:</p><blockquote><em>“Apply those changes to the screen.”</em></blockquote><h3>A Practical Way to Think About It</h3><p>When I first started looking into this more carefully, the easiest analogy for me was this:</p><h3>Render Phase = planning the update</h3><h3>Commit Phase = applying the update</h3><p>Imagine you’re renovating a room.</p><p>First, you plan:</p><ul><li>what furniture stays</li><li>what gets removed</li><li>what gets moved</li><li>what new things need to be added</li></ul><p>That’s the render phase.</p><p>Then you actually move the furniture, paint the wall, and replace things.</p><p>That’s the commit phase.</p><p>React works in a similar way.</p><h3>Where Does Reconciliation Fit In?</h3><p>This is where the term <strong>reconciliation</strong> comes in.</p><p>Reconciliation is React’s process of comparing the previous tree with the new one to figure out what changed.</p><p>This mostly happens during the <strong>render phase</strong>.</p><p>Suppose the previous render returned:</p><pre>&lt;h1&gt;Hello, Vikash&lt;/h1&gt;</pre><p>and the next render returns:</p><pre>&lt;h1&gt;Hello, Rahul&lt;/h1&gt;</pre><p>React compares the two and sees that the &lt;h1&gt; element is the same, but the text content is different.</p><p>So instead of destroying and recreating everything, it can just update the text node.</p><p>That comparison work is part of how React decides what to commit.</p><h3>Why useEffect Runs After Rendering</h3><p>This is exactly where many of the earlier confusions around useEffect start to clear up.</p><p>useEffect does <strong>not</strong> run during the render phase.</p><p>It runs <strong>after React commits changes to the DOM</strong>.</p><p>That means this sequence is more accurate:</p><pre>State changes<br>↓<br>React renders the component<br>↓<br>React commits DOM updates<br>↓<br>useEffect runs</pre><p>So if you have:</p><pre>function UserProfile() {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Effect executed&quot;);<br>  }, []);<br>  return &lt;h1&gt;User Profile&lt;/h1&gt;;<br>}</pre><p>the order is not:</p><ol><li>useEffect</li><li>render</li><li>DOM update</li></ol><p>It’s the opposite.</p><p>The component renders first.<br>The DOM is updated if needed.<br>Then the effect runs.</p><p>This is why effects are the right place for things like:</p><ul><li>API calls</li><li>subscriptions</li><li>timers</li><li>syncing with browser APIs</li><li>updating external systems</li></ul><p>These are things that should happen <strong>after</strong> React has finished updating the UI.</p><h3>Where useLayoutEffect Fits In</h3><p>Now let’s talk about the hook that usually gets mentioned right after this topic: useLayoutEffect.</p><p>At a high level:</p><ul><li><strong>useEffect</strong> runs after the browser has had a chance to paint updates</li><li><strong>useLayoutEffect</strong> runs after React has committed DOM changes, but before the browser paints them to the screen</li></ul><p>That makes useLayoutEffect useful when you need to read layout or make DOM measurements before the user sees the result.</p><p>For example:</p><ul><li>measuring element width or height</li><li>reading scroll position</li><li>synchronously adjusting layout before paint</li></ul><p>A rough sequence looks like this:</p><pre>Render Phase<br>↓<br>Commit DOM updates<br>↓<br>useLayoutEffect<br>↓<br>Browser paint<br>↓<br>useEffect</pre><p>You don’t need to memorize every internal detail right now. The key idea is simply this:</p><ul><li>useEffect is for side effects after paint</li><li>useLayoutEffect is for DOM-related work that must happen before paint</li></ul><h3>What You Should Avoid During the Render Phase</h3><p>This is one of the most useful practical takeaways from understanding render vs commit.</p><p>Because the render phase is supposed to be a pure calculation of UI, you generally should <strong>not perform side effects inside the component body</strong>.</p><p>For example, this is a bad pattern:</p><pre>function ProductPage() {<br>  localStorage.setItem(&quot;page&quot;, &quot;product&quot;);<br>  return &lt;h1&gt;Product Page&lt;/h1&gt;;<br>}</pre><p>Why is this problematic?</p><p>Because the component body runs during the render phase, and React may render more often than you expect.</p><p>That means side effects in render can happen multiple times and at unpredictable moments relative to DOM updates.</p><p>Similarly, things like these don’t belong directly in render:</p><ul><li>API calls</li><li>manual DOM manipulation</li><li>timers</li><li>subscriptions</li><li>writing to storage as part of rendering logic</li></ul><p>The render phase should stay focused on returning UI.</p><h3>A Small Debugging Example</h3><p>Let’s make this concrete with logs.</p><pre>function Demo() {<br>  console.log(&quot;Render phase&quot;);<br>  useLayoutEffect(() =&gt; {<br>    console.log(&quot;useLayoutEffect&quot;);<br>  });<br>  useEffect(() =&gt; {<br>    console.log(&quot;useEffect&quot;);<br>  });<br>  return &lt;h1&gt;Hello&lt;/h1&gt;;<br>}</pre><p>The rough order will be:</p><pre>Render phase<br>useLayoutEffect<br>useEffect</pre><p>That ordering tells you something important:</p><ul><li>The component body runs first during render</li><li>useLayoutEffect runs after DOM commit but before paint</li><li>useEffect runs later</li></ul><p>The exact behavior can look slightly different in development because of <strong>Strict Mode</strong>, but the mental model still holds.</p><h3>Why Strict Mode Sometimes Makes This Feel More Confusing</h3><p>If you’ve ever logged inside a component or effect and thought:</p><blockquote><em>“Why is this running twice?”</em></blockquote><p>there’s a good chance you were testing in development with <strong>React Strict Mode</strong> enabled.</p><p>Strict Mode intentionally re-runs certain logic in development to help surface side effects and unsafe patterns.</p><p>That can make the render/commit flow look noisier than it will in production.</p><p>This is one of the reasons React can feel confusing when you’re learning these internals from console logs alone.</p><p>If you don’t know Strict Mode is involved, it’s easy to build the wrong mental model.</p><h3>Render Does Not Always Mean DOM Update</h3><p>This is another subtle but important point.</p><p>A component can render again without causing visible DOM changes.</p><p>For example, React may call your component, compare the new output to the previous output, and conclude:</p><blockquote><em>“Nothing meaningful changed here.”</em></blockquote><p>In that case, the render phase still happened.</p><p>But the commit phase may result in little or no DOM work.</p><p>That’s one reason I try to separate these ideas in my head:</p><ul><li><strong>rendering</strong> = React calculating UI</li><li><strong>committing</strong> = React applying DOM updates</li></ul><p>They are related, but not identical.</p><h3>How This Changes the Way I Write React Code</h3><p>Understanding render vs commit changed a few habits in my own React code.</p><p>Now, when I write a component, I mentally split logic into two buckets:</p><h3>1. Logic that belongs in render</h3><p>This includes:</p><ul><li>deriving values from props/state</li><li>conditional JSX</li><li>mapping arrays to UI</li><li>simple calculations needed to describe the UI</li></ul><h3>2. Logic that belongs after commit</h3><p>This includes:</p><ul><li>fetching data</li><li>subscriptions</li><li>DOM access</li><li>browser APIs</li><li>syncing state with external systems</li></ul><p>That separation has made components easier to reason about, especially in larger screens where rendering logic and side-effect logic can get mixed together very quickly.</p><h3>The Mental Model I’d Keep</h3><p>If you remember only one thing from this article, let it be this:</p><h3>React updates happen in two broad steps:</h3><h3>Render Phase</h3><p>React figures out what the next UI should look like.</p><h3>Commit Phase</h3><p>React applies those changes to the DOM and then runs post-render effects.</p><p>That’s the core model.</p><p>Once that clicks, a lot of React behavior becomes easier to explain:</p><ul><li>why useEffect runs later</li><li>why side effects shouldn’t live in render</li><li>why a component can render without visibly changing the DOM</li><li>why React can feel like it “renders more often than expected”</li></ul><h3>Key Takeaways</h3><ul><li>React doesn’t update the DOM the moment state changes.</li><li>It first enters the <strong>render phase</strong> to calculate the next UI.</li><li>During render, React executes your component functions and compares the new output with the previous one.</li><li>After that, React enters the <strong>commit phase</strong> and applies the necessary DOM updates.</li><li>useEffect runs after the commit phase.</li><li>useLayoutEffect runs after DOM updates but before the browser paints.</li><li>Side effects should generally not live inside the component body because render should stay focused on describing UI.</li></ul><p>React feels much less magical once you stop treating “render” as one single event and start seeing it as a pipeline.</p><p>And in practice, that pipeline is one of the most useful mental models you can have when working with hooks, debugging re-renders, or reasoning about performance.</p><h3>What’s Next?</h3><p>In the next article, I want to go one step deeper into a topic that causes a lot of unnecessary re-renders in real projects:</p><h3>Why React Needs Keys — and Why index as a Key Can Break More Than You Think</h3><p>Because once you understand render vs commit, the next natural step is understanding how React identifies elements between renders — and that’s exactly where <strong>keys</strong> become important.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff1a8d13b1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/works-on-my-machine/react-render-phase-vs-commit-phase-what-really-happens-behind-the-scenes-9ff1a8d13b1d">React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?</a> was originally published in <a href="https://medium.com/works-on-my-machine">Works On My Machine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Actually Causes a React Component to Re-render?]]></title>
            <link>https://medium.com/works-on-my-machine/what-actually-causes-a-react-component-to-re-render-66976be65f33?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/66976be65f33</guid>
            <category><![CDATA[context-changes]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[react-components]]></category>
            <category><![CDATA[component-rerender]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Mon, 06 Jul 2026 10:40:18 GMT</pubDate>
            <atom:updated>2026-07-06T10:40:18.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FmilqAmRGL4Z6f8LkqX0rw.png" /></figure><p>In my previous article, we discussed a common misconception:</p><blockquote><strong><em>useEffect doesn&#39;t directly cause a component to re-render.</em></strong></blockquote><p>That naturally leads to another question:</p><blockquote><strong><em>If </em></strong><strong><em>useEffect isn&#39;t responsible, then what actually causes a React component to re-render?</em></strong></blockquote><p>If you’ve ever opened React DevTools and wondered,</p><p><em>“Why did this component render again? I didn’t even change anything!”</em></p><p>you’re not alone.</p><p>React’s rendering behavior often feels mysterious until you understand the small set of rules it follows.</p><p>The good news?</p><p>React isn’t unpredictable.</p><p>It’s actually very consistent.</p><p>Let’s break it down.</p><h3>The Short Answer</h3><p>A React component re-renders when one of these happens:</p><ul><li>Its <strong>state</strong> changes.</li><li>Its <strong>props</strong> change.</li><li>A <strong>context value</strong> it consumes changes.</li><li>Its <strong>parent component</strong> re-renders.</li></ul><p>That’s it.</p><p>Everything else is either a consequence of one of these events or a common misunderstanding.</p><h3>1. State Changes</h3><p>This is the most obvious trigger.</p><p>Whenever you update a component’s state, React schedules another render.</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>return (<br>    &lt;&gt;<br>      &lt;p&gt;{count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>When the button is clicked:</p><ol><li>setCount() updates the state.</li><li>React schedules another render.</li><li>The component executes again.</li><li>React compares the new UI with the previous one.</li><li>Only the necessary DOM updates are applied.</li></ol><p>Notice something important.</p><p>React <strong>doesn’t reload the page.</strong></p><p>It simply calls your component function again to determine what the UI should look like.</p><h3>2. Props Change</h3><p>A component also re-renders whenever the props it receives change.</p><p>Consider this example:</p><pre>function Parent() {<br>  const [name, setName] = useState(&quot;John&quot;);<br>  return (<br>    &lt;&gt;<br>      &lt;Child name={name} /&gt;  <br>      &lt;button onClick={() =&gt; setName(&quot;David&quot;)}&gt;<br>        Change Name<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>function Child({ name }) {<br>  console.log(&quot;Child rendered&quot;);<br>  return &lt;h1&gt;{name}&lt;/h1&gt;;<br>}</pre><p>Initially:</p><pre>name = &quot;John&quot;</pre><p>After clicking the button:</p><pre>name = &quot;David&quot;</pre><p>Since the name prop changed, React renders the Child component again.</p><p>This makes sense because the UI now needs to display different data.</p><h3>3. Context Changes</h3><p>Context allows components to share data without manually passing props through every level.</p><p>However, there’s something developers often overlook.</p><p>Whenever a context value changes, <strong>every component consuming that context becomes eligible for re-rendering.</strong></p><p>For example:</p><pre>const ThemeContext = createContext();<br>const theme = useContext(ThemeContext);</pre><p>If the theme changes from:</p><pre>Light</pre><p>to</p><pre>Dark</pre><p>every component reading that context will render again.</p><p>This is one of the reasons developers often split large contexts into smaller ones.</p><p>Smaller contexts mean fewer unnecessary renders.</p><h3>4. Parent Component Re-renders</h3><p>This is probably the least understood trigger.</p><p>Imagine this component hierarchy:</p><pre>App<br> ├── Header<br> ├── Sidebar<br> └── Profile</pre><p>Now suppose App updates its own state.</p><p>React will execute App again.</p><p>While doing so, it also executes its child components.</p><p>This surprises many developers.</p><p>They think:</p><blockquote><em>“But the child’s props didn’t change!”</em></blockquote><p>That’s true.</p><p>Yet React still calls the child component unless you’ve explicitly optimized it.</p><p>For example:</p><pre>function Parent() {<br>  const [count, setCount] = useState(0);<br><br>return (<br>    &lt;&gt;<br>      &lt;Child /&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increment<br>      &lt;/button&gt;<br>    &lt;/&gt;<br>  );<br>}<br></pre><p>Even though Child receives no props, it will execute every time Parent renders.</p><p>This is completely normal.</p><p>Later in this series, we’ll see how React.memo can help avoid unnecessary renders.</p><h3>What Does Not Cause Re-renders?</h3><p>Now that we know what <em>does</em> trigger rendering, let’s clear up a few common myths.</p><h3>useEffect</h3><p>As we covered in Part 1,</p><p>useEffect runs <strong>after</strong> rendering.</p><p>It doesn’t initiate rendering.</p><p>State updates inside an effect may trigger another render, but the effect itself doesn’t.</p><h3>Updating a Ref</h3><pre>const countRef = useRef(0);<br>countRef.current++;</pre><p>Nothing happens.</p><p>The UI doesn’t update.</p><p>That’s because refs are mutable values that React doesn’t track for rendering.</p><p>This is exactly why they’re useful for storing values that shouldn’t affect the UI.</p><h3>Changing a Local Variable</h3><pre>let count = 0;<br>count++;</pre><p>Again, React has no idea this happened.</p><p>Local variables disappear after every render.</p><p>Only state is preserved between renders.</p><h3>Does Re-render Mean the DOM Changes?</h3><p>Not necessarily.</p><p>This is another misconception.</p><p>When React re-renders a component, it simply executes the component function again.</p><p>After that, React compares the previous UI with the new one.</p><p>If nothing changed, React updates nothing in the DOM.</p><p>For example:</p><pre>function Welcome() {<br>  console.log(&quot;Rendered&quot;);<br>  return &lt;h1&gt;Hello React&lt;/h1&gt;;<br>}</pre><p>Even if this component executes multiple times, React may determine that the resulting UI is identical.</p><p>In that case, no DOM updates are required.</p><p>Rendering and updating the DOM are related, but they are <strong>not the same thing</strong>.</p><p>Understanding this distinction is key to reasoning about React performance.</p><h3>A Mental Model That Helped Me</h3><p>One way I like to think about React is this:</p><p>Imagine your component is just a JavaScript function.</p><p>Whenever React thinks something <em>might</em> affect the UI, it simply calls that function again.</p><p>The function returns a new description of the UI.</p><p>React then compares it with the previous description and applies only the necessary DOM changes.</p><p>Once I started thinking this way, React’s rendering behavior became much easier to understand.</p><h3>Key Takeaways</h3><ul><li>A component re-renders when its <strong>state</strong>, <strong>props</strong>, or <strong>consumed context</strong> change.</li><li>Parent component renders also cause child components to execute unless they’re optimized.</li><li>useEffect doesn&#39;t directly trigger re-renders.</li><li>Updating a ref doesn&#39;t cause a render.</li><li>Changing local variables doesn’t cause a render.</li><li>A re-render doesn’t automatically mean the DOM will change.</li></ul><p>React isn’t constantly updating the browser.</p><p>It’s constantly asking one simple question:</p><blockquote><strong><em>“Given the latest data, what should the UI look like now?”</em></strong></blockquote><p>Everything else is just React efficiently finding the smallest set of DOM changes needed to make that happen.</p><h3>What’s Next?</h3><p>In the next article, we’ll dive into something many developers mention but few truly understand:</p><blockquote><strong><em>React Render Phase vs Commit Phase: What Really Happens Behind the Scenes?</em></strong></blockquote><p>Once you understand these two phases, concepts like useEffect, useLayoutEffect, rendering, reconciliation, and performance optimizations start making much more sense.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66976be65f33" width="1" height="1" alt=""><hr><p><a href="https://medium.com/works-on-my-machine/what-actually-causes-a-react-component-to-re-render-66976be65f33">What Actually Causes a React Component to Re-render?</a> was originally published in <a href="https://medium.com/works-on-my-machine">Works On My Machine</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Does useEffect Trigger Re-renders? A Common React Misconception]]></title>
            <link>https://medium.com/@vikash_yadav_41088/does-useeffect-trigger-re-renders-a-common-react-misconception-784706ee21ce?source=rss-5c24637cd9bc------2</link>
            <guid isPermaLink="false">https://medium.com/p/784706ee21ce</guid>
            <dc:creator><![CDATA[Vikash Yadav]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 11:35:51 GMT</pubDate>
            <atom:updated>2026-06-23T11:35:51.280Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been working with React for a while, you’ve probably heard someone say:</p><blockquote><em>“The component re-rendered because useEffect ran.”</em></blockquote><p>At first glance, this sounds reasonable.</p><p>After all, we often see a component render, then an effect runs, and shortly afterward the component renders again. It’s easy to assume that useEffect is responsible for the second render.</p><p>But that’s not actually what happens.</p><p>Understanding this distinction can help you avoid unnecessary effects, prevent infinite render loops, and build a much stronger mental model of how React works under the hood.</p><p>Let’s break it down.</p><h3>The Misconception</h3><p>Many developers believe that useEffect itself causes a component to re-render.</p><p>Consider the following example:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  useEffect(() =&gt; {<br>    console.log(&quot;Effect executed&quot;);<br>  }, []);</pre><pre>  return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>When this component mounts:</p><ol><li>React renders the component.</li><li>React updates the DOM.</li><li>React executes the effect.</li><li>The effect runs successfully.</li></ol><p>But notice something important:</p><p><strong>No additional render occurs.</strong></p><p>The component renders only once.</p><p>This immediately tells us that useEffect itself does not trigger a re-render.</p><h3>What Actually Causes Re-renders?</h3><p>In React, components re-render when:</p><ul><li>State changes</li><li>Props change</li><li>Context values change</li><li>A parent component re-renders (depending on optimization)</li></ul><p>That’s it.</p><p>The effect hook isn’t on that list.</p><p><strong>React doesn’t re-render because an effect executed.</strong></p><p>React re-renders because something changed that affects the component’s output.</p><h3>Why the Confusion Exists</h3><p>Let’s look at a slightly different example:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  useEffect(() =&gt; {<br>    setCount(1);<br>  }, []);</pre><pre>  return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>This component renders twice.</p><p>Many developers conclude:</p><blockquote><em>“useEffect caused the second render.”</em></blockquote><p>Not exactly.</p><p>Here’s what actually happens:</p><h3>Initial Render</h3><pre>count = 0</pre><p>React renders the component.</p><h3>Effect Execution</h3><pre>setCount(1);</pre><p>The effect runs after React commits changes to the DOM.</p><h3>State Update</h3><p>setCount(1) updates component state.</p><h3>Re-render</h3><p>React schedules another render because the state changed.</p><pre>count = 1</pre><p>The second render happens because of the state update, not because the effect executed.</p><p>The effect merely contained the code that updated state.</p><h3>A Better Mental Model</h3><p>Think of useEffect as a place to synchronize your component with the outside world.</p><p>Examples include:</p><ul><li>Fetching data</li><li>Subscribing to events</li><li>Updating document titles</li><li>Connecting to WebSockets</li><li>Interacting with browser APIs</li><li>Synchronizing third-party libraries</li></ul><p>The key idea is:</p><blockquote><em>Effects react to rendering. They don’t initiate rendering.</em></blockquote><p>A render happens first.</p><p>Then React runs the effect.</p><h3>Understanding React’s Lifecycle Flow</h3><p>A simplified version of React’s workflow looks like this:</p><pre>Render Component<br>       ↓<br>Update DOM<br>       ↓<br>Run Effects</pre><p>Notice where effects sit in the process.</p><p>They run after rendering has already completed.</p><p>That’s why an effect cannot be responsible for the render that caused it to execute.</p><h3>The Infinite Loop Trap</h3><p>This misunderstanding often leads to one of the most common React bugs.</p><p>Consider this code:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);</pre><pre>  useEffect(() =&gt; {<br>    setCount(count + 1);<br>  },[count]);</pre><pre>  return &lt;h1&gt;{count}&lt;/h1&gt;;<br>}</pre><p>What happens?</p><ol><li>Component renders.</li><li>Effect runs.</li><li>State updates.</li><li>Component re-renders.</li><li>Effect runs again.</li><li>State updates again.</li><li>Repeat forever.</li></ol><p>Developers sometimes say:</p><blockquote><em>“useEffect is causing an infinite re-render.”</em></blockquote><p>A more accurate statement would be:</p><blockquote><em>“The effect continuously updates state, and those state updates continuously trigger re-renders.”</em></blockquote><p>Understanding the difference makes debugging much easier.</p><h3>When State Updates Inside Effects Are Completely Fine</h3><p>This article doesn’t mean you should never update state inside an effect.</p><p>There are plenty of legitimate use cases.</p><p>For example:</p><pre>useEffect(() =&gt; {<br>  fetchUser().then(data =&gt; {<br>    setUser(data);<br>  });<br>}, []);</pre><p>This pattern is perfectly normal.</p><p>The important thing is understanding that the re-render occurs because setUser updates state, not because the effect exists.</p><h3>The Question I Ask During Code Reviews</h3><p>Whenever I see an effect, I ask a simple question:</p><blockquote><em>If I remove this effect entirely, what state, prop, or external system would stop being synchronized?</em></blockquote><p>If the answer is “nothing,” the effect is probably unnecessary.</p><p>Many React applications become overly complicated because developers use effects for logic that could be handled directly during rendering.</p><h3>Key Takeaways</h3><ul><li>useEffect does not directly trigger re-renders.</li><li>React re-renders when state, props, or context values change.</li><li>Effects run after React commits updates to the DOM.</li><li>State updates inside effects may trigger additional renders.</li><li>Understanding this distinction helps avoid infinite loops and unnecessary effects.</li><li>A good mental model is: <strong>renders happen first, effects happen afterward.</strong></li></ul><p>The next time someone says:</p><blockquote><em>“useEffect re-rendered the component.”</em></blockquote><p>You’ll know the more precise explanation:</p><blockquote><em>“A state update inside useEffect caused React to schedule another render.”</em></blockquote><p>And in React, that distinction matters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=784706ee21ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>