<?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 Nilupul Perera on Medium]]></title>
        <description><![CDATA[Stories by Nilupul Perera on Medium]]></description>
        <link>https://medium.com/@hasunnilupul?source=rss-715e55318b35------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OncDtlIUP_5vl-GqdmOUVw.jpeg</url>
            <title>Stories by Nilupul Perera on Medium</title>
            <link>https://medium.com/@hasunnilupul?source=rss-715e55318b35------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:02:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hasunnilupul/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[useEffect: Side Effects, Dependencies, and Cleanup]]></title>
            <link>https://javascript.plainenglish.io/useeffect-side-effects-dependencies-and-cleanup-6ef97fe1bd71?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ef97fe1bd71</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 07:55:40 GMT</pubDate>
            <atom:updated>2026-11-16T07:55:40.787Z</atom:updated>
            <content:encoded><![CDATA[<p><em>React Zero to Senior · Part 1: Foundations · Article 5 of 24</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXPVNwr_L63AsRQXLXW1jg.png" /><figcaption>useEffect: Side Effects, Dependencies, and Cleanup</figcaption></figure><p><strong>What you’ll learn:</strong> when you actually need useEffect, how the dependency array decides when it runs, how to clean up after yourself, and how to fetch data without showing the wrong result.</p><blockquote><strong><em>Versions used:</em></strong><em> React 19.3.1 · Vite 8.3.4 · @vitejs/plugin-react 6.2.1 · pnpm </em><strong><em>Code:</em></strong><em> </em><a href="https://github.com/hasunnilupul/react-zero-to-hero/tree/main/05-useeffect-side-effects-cleanup"><em>react-zero-to-hero/05-useeffect-side-effects-cleanup</em></a></blockquote><p>Up to now, everything we’ve written has lived inside render. A component takes props and state, and returns JSX. Same inputs, same output, no surprises. That’s the “UI is a function of state” model from Article 1, and it’s why React code is easy to reason about.</p><p>But real apps have to talk to the outside world. They fetch data, start timers, listen for window resizes, connect to chat servers, and update the browser tab’s title. None of that is “return some JSX”. That’s what useEffect is for.</p><p>In <a href="https://medium.com/javascript-in-plain-english/conditional-rendering-lists-and-keys-f4c9c68e4494?sharedUserId=hasunnilupul">Article 4</a> we decided <em>what</em> to render. Now we’ll step outside render to keep the page in sync with things React doesn’t control.</p><p>To follow along, clone the repo, open the 05-useeffect-side-effects-cleanup folder, and run pnpm install then pnpm dev. Keep the browser console open, because most of the demos log what their effects are doing.</p><h3>What counts as a side effect</h3><p>A <strong>side effect</strong> is anything your component does that reaches outside of “calculate the JSX”. Setting document.title, starting a setInterval, adding a window event listener, opening a WebSocket, sending a network request: all side effects.</p><p>React wants render to stay pure, so you don’t do these things in the component body. You put them in an effect, and React runs that effect <strong>after</strong> it has updated the screen.</p><p>The mental model that makes useEffect click is this: <strong>an effect synchronizes your component with an external system.</strong> It isn&#39;t a lifecycle method, and it isn&#39;t &quot;code that runs when something changes&quot;. It says, &quot;while this component is on screen with these values, the outside world should look like <em>this</em>.&quot; When the values change, React re-syncs. When the component leaves the screen, React cleans up.</p><h3>When you don’t need an effect</h3><p>The most common useEffect mistake is using one when there&#39;s no external system involved at all. The classic case is copying derived data into state:</p><pre>// ❌ An effect that only syncs state with other state<br>const [first, setFirst] = useState(&#39;Ada&#39;);<br>const [last, setLast] = useState(&#39;Lovelace&#39;);<br>const [fullName, setFullName] = useState(&#39;&#39;);<br><br>useEffect(() =&gt; {<br>  setFullName(`${first} ${last}`);<br>}, [first, last]);<br><br>// ✅ Just calculate it during render<br>const fullName = `${first} ${last}`;</pre><p>Both versions show the same name, but the effect version is worse in every way. It renders once with the <strong>stale</strong> name, runs the effect, then renders again with the right one. It has an extra piece of state that can drift out of sync. And it’s more code. In the demo, type one letter into each form and compare the console. The effect version logs two renders per keystroke, and the first one has the old name.</p><p>This is the same “derived data” rule from Article 4’s filtered list. A quick checklist before you reach for an effect:</p><ul><li><strong>Can you calculate it from props or state?</strong> Do it during render.</li><li><strong>Is it a response to a user action</strong> (a click, a submit)? Put it in the event handler. An effect runs because the component <em>rendered</em>, not because the user <em>did</em> something.</li><li><strong>Is it synchronizing with something outside React</strong> (the DOM API, a timer, the network, a third-party widget)? That’s what an effect is for.</li></ul><h3>The dependency array</h3><p>useEffect takes two arguments: a function to run, and an array of the values that function uses. That array tells React <em>when</em> to re-sync:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br><br>function DocumentTitle() {<br>  const [count, setCount] = useState(0);<br>  useEffect(() =&gt; {<br>    document.title = `Clicked ${count} times`;<br>  }, [count]); // re-run only when count changes<br>  return &lt;button onClick={() =&gt; setCount((c) =&gt; c + 1)}&gt;Count: {count}&lt;/button&gt;;<br>}<br><br>// useEffect(fn)       → runs after every render<br>// useEffect(fn, [])   → runs once after the first render (and cleans up on unmount)<br>// useEffect(fn, [a])  → runs after the first render, then whenever `a` changes</pre><p>After every render, React compares each value in the array to the one from the previous render using Object.is. If nothing changed, the effect is skipped. In the demo there&#39;s a second button that toggles an unrelated label. It re-renders the component, but the title effect doesn&#39;t run again, because count is the same.</p><p>Here’s the important part: <strong>you don’t choose the dependencies. Your code does.</strong> Every prop, state value, or variable declared in the component body that the effect reads must be in the array. If you leave one out, the effect keeps using the value from an old render. That’s the infamous stale closure bug, and it’s very hard to spot by reading the code.</p><p>That’s why the react-hooks/exhaustive-deps lint rule exists. It reads your effect and tells you exactly what&#39;s missing. Vite&#39;s React template includes it through eslint-plugin-react-hooks. If your project doesn&#39;t have it, add it before you write another effect.</p><p>When the linter asks for a dependency you don’t want, the answer is never to silence it with an eslint-disable comment. Change the code instead:</p><ul><li>Use an <strong>updater function</strong> (setCount((c) =&gt; c + 1)), so you don&#39;t need to read count at all.</li><li><strong>Move</strong> an object or function the effect needs <strong>inside</strong> the effect, so it isn’t recreated every render.</li><li>If you really need to read the latest value of something <em>without</em> re-syncing on it, React 19 has useEffectEvent. We&#39;ll come back to it later in the series.</li></ul><h3>Cleanup: undo what you started</h3><p>Whatever an effect starts, it should stop. You do that by returning a <strong>cleanup function</strong>. React calls it before the effect runs again with new values, and once more when the component unmounts.</p><pre>// A timer: start it, and clear it on cleanup<br>useEffect(() =&gt; {<br>  const id = setInterval(() =&gt; setSeconds((s) =&gt; s + 1), 1000);<br>  return () =&gt; clearInterval(id);<br>}, []);<br><br>// An event listener: add it, and remove the *same* function on cleanup<br>useEffect(() =&gt; {<br>  function handleResize() {<br>    setWidth(window.innerWidth);<br>  }<br>  window.addEventListener(&#39;resize&#39;, handleResize);<br>  return () =&gt; window.removeEventListener(&#39;resize&#39;, handleResize);<br>}, []);</pre><p>The pattern is always symmetrical: setInterval / clearInterval, addEventListener / removeEventListener, subscribe / unsubscribe, connect / disconnect.</p><p>The demo puts two timers side by side. The left one has no cleanup, and in development it counts <strong>two seconds for every one</strong>. Click <strong>Hide timers</strong> and check the console: the leaky timer is still ticking, updating state for a component that no longer exists. In a real app, that’s a memory leak, a socket that never closes, or a listener that fires on the wrong page.</p><p>Notice that setSeconds uses an updater function. That&#39;s what lets the dependency array stay empty. The interval never needs to read seconds itself.</p><h3>Fetching data and race conditions</h3><p>Fetching data is a side effect, so the first version most people write is an effect with [userId] as its dependency that calls fetchUser(userId).then(setUser). It works in a demo and breaks in real life. Requests don&#39;t come back in the order you sent them. Click <strong>User 1</strong> (a slow 1.6 s response) and then quickly <strong>User 2</strong> (0.3 s). User 2 arrives first and renders. Then User 1&#39;s response finally lands and <strong>overwrites</strong> it. You selected User 2, but you&#39;re looking at User 1. That&#39;s a race condition.</p><p>The fix is to use cleanup again. When userId changes, the old request is no longer wanted, so cancel it:</p><pre>function UserCard({ userId }) {<br>  const [result, setResult] = useState(null);<br><br>  useEffect(() =&gt; {<br>    const controller = new AbortController();<br>    fetchUser(userId, { signal: controller.signal })<br>      .then((user) =&gt; setResult({ id: userId, user, error: null }))<br>      .catch((error) =&gt; {<br>        if (error.name !== &#39;AbortError&#39;) setResult({ id: userId, user: null, error });<br>      });<br>    return () =&gt; controller.abort(); // the old request is cancelled before the new one starts<br>  }, [userId]);<br><br>  if (result?.id !== userId) return &lt;p&gt;Loading…&lt;/p&gt;;<br>  if (result.error) return &lt;p&gt;Something went wrong.&lt;/p&gt;;<br><br>  return &lt;p&gt;{result.user.name}&lt;/p&gt;;<br>}</pre><p>Three things are going on here:</p><ol><li><strong>Cleanup aborts the stale request.</strong> With the real fetch, passing { signal } does exactly this, and the aborted promise rejects with an AbortError, which we ignore.</li><li><strong>The result remembers which id it belongs to.</strong> That makes “loading” something we <em>derive</em> (no result yet, or a result for a different id) instead of another piece of state to keep in sync.</li><li><strong>Errors are a real state</strong>, not something we forget to handle.</li></ol><p>The demo shows the naive card and this one side by side. Then try step 4 from the folder’s README: delete the abort() line and watch the right card get stuck on &quot;Loading…&quot;. The id check stops the wrong user from showing, but only the cleanup fixes the race.</p><p>Honestly, this is a lot of code for one request, and we haven’t touched caching, retries, or refetching yet. That’s why most React apps don’t fetch in effects at all. In Article 12 we’ll replace all of this with TanStack Query, and in Article 17 we’ll look at Suspense and the use hook. But you should understand the race first, because every data library is solving exactly this problem for you.</p><h3>Strict Mode runs your effects twice</h3><p>Open the console on the last demo and reload. You’ll see this:</p><pre>✅ connect to &quot;general&quot;<br>❌ disconnect from &quot;general&quot;<br>✅ connect to &quot;general&quot;</pre><p>That isn’t a bug. Our main.jsx wraps the app in &lt;StrictMode&gt;, and in development React 19 mounts every component, immediately unmounts it, and mounts it again. It&#39;s a stress test. If your effect has proper cleanup, the user can&#39;t tell the difference: you end up with exactly one connection. If it doesn&#39;t, you see the problem now, in development, instead of in production when a user navigates back and forth.</p><p>That’s exactly why the leaky timer counted double. Strict Mode started it twice, and nothing stopped the first one.</p><p>So when you see your effect run twice, <strong>don’t remove </strong><strong>&lt;StrictMode&gt;</strong> and don&#39;t add a useRef flag to skip the second run. Ask &quot;what does my cleanup need to undo?&quot; Fix the cleanup and the double run becomes harmless.</p><p>Run pnpm build &amp;&amp; pnpm preview and reload. The extra pair is gone. Strict Mode&#39;s checks only run in development.</p><h3>Common mistakes</h3><ul><li><strong>Using an effect for derived data.</strong> If you can calculate it from props or state, do it during render. An effect that only calls setState with other state is a red flag.</li><li><strong>Using an effect for event logic.</strong> “When the user submits, send the request” belongs in the submit handler, not in an effect watching a submitted flag.</li><li><strong>Lying about dependencies.</strong> Leaving a value out of the array, or silencing exhaustive-deps, gives you stale values. Restructure the code instead.</li><li><strong>Forgetting cleanup.</strong> Every interval, listener, subscription, and connection needs a matching undo, or it outlives the component.</li><li><strong>Removing a listener with a different function.</strong> removeEventListener only works with the exact function you added. Define the handler inside the effect and pass the same reference to both calls.</li><li><strong>Ignoring race conditions.</strong> A fetch without cleanup will eventually show the wrong data. Abort it or ignore the stale result.</li><li><strong>Making the effect function </strong><strong>async.</strong> useEffect(async () =&gt; …) returns a promise, not a cleanup function. Define an async function inside the effect and call it, or use .then as we did above.</li><li><strong>Fighting Strict Mode.</strong> A double run in development means your cleanup is missing or incomplete. Fix that, not the double run.</li></ul><h3>Recap</h3><ul><li>An effect synchronizes a component with something outside React. If nothing external is involved, you probably don’t need one.</li><li>The dependency array lists every reactive value the effect reads. Let the linter decide what goes in it.</li><li>Return a cleanup function that undoes whatever the effect started. React runs it before re-syncing and on unmount.</li><li>When fetching in an effect, cancel stale requests in cleanup so the slowest response can’t win.</li><li>Strict Mode’s mount, unmount, mount cycle in development is a free test of your cleanup.</li></ul><p>The full demo, with the leaky timer and the fetch race side by side, is in the <a href="https://github.com/hasunnilupul/react-zero-to-hero/tree/main/05-useeffect-side-effects-cleanup">repo folder for this article</a>. Break it on purpose: remove a cleanup, drop a dependency, and see what happens.</p><p><strong>Next up → Article 6: Mini Project: Build a Task Tracker</strong> (Nov 20). We close out Part 1 by building a complete app from scratch, using everything so far: components, state, forms, lists, keys, and an effect that saves your tasks to localStorage.</p><p>📚 Every article in the series: <a href="https://medium.com/@hasunnilupul/react-zero-to-senior-the-complete-series-index-045e4fa582cc"><strong>React Zero to Senior: The Complete Series Index</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ef97fe1bd71" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/useeffect-side-effects-dependencies-and-cleanup-6ef97fe1bd71">useEffect: Side Effects, Dependencies, and Cleanup</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conditional Rendering, Lists, and Keys]]></title>
            <link>https://javascript.plainenglish.io/conditional-rendering-lists-and-keys-f4c9c68e4494?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c9c68e4494</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Wed, 11 Nov 2026 07:46:24 GMT</pubDate>
            <atom:updated>2026-11-11T07:46:24.006Z</atom:updated>
            <content:encoded><![CDATA[<p><em>React Zero to Senior · Part 1: Foundations · Article 4 of 24</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*40RkSepP5pvtsvJkAzmXTA.png" /><figcaption>Conditional Rendering, Lists, and Keys</figcaption></figure><p><strong>What you’ll learn:</strong> how to show and hide UI without stray zeros, render lists from arrays, and pick keys that keep React from mixing up your rows.</p><p>Almost every screen you build answers two questions. <em>Should this piece of UI be here right now?</em> And <em>how many of these do I need?</em> A cart badge appears only when the cart has items. A search page shows ten results, or one, or a friendly “nothing found” message.</p><p>In <a href="https://medium.com/javascript-in-plain-english/events-forms-and-controlled-inputs-in-react-19-bb6f50e3679c?sharedUserId=hasunnilupul">Article 3</a> we wired up events and forms. Now we’ll use that state to decide <strong>what</strong> to render and <strong>how many times</strong>. Both ideas lean on the mental model from Article 1: your component is a function of state, so conditions and loops are just JavaScript running inside that function.</p><p>To follow along, clone the repo, open the <a href="https://github.com/hasunnilupul/react-zero-to-hero">04-conditional-rendering-lists-keys</a> folder, and run pnpm install then pnpm dev.</p><h3>Four ways to render conditionally</h3><p>JSX has no if tag. Instead, you use plain JavaScript, and React renders whatever value you hand it. There are four patterns worth knowing, and each one fits a different job.</p><ol><li><strong>Ternary (</strong><strong>a ? b : c)</strong> when you&#39;re choosing between two pieces of UI.</li><li><strong>Logical AND (</strong><strong>a &amp;&amp; b)</strong> when you&#39;re showing something or nothing.</li><li><strong>Early return</strong> when a whole component has nothing useful to show (not signed in, no data yet).</li><li><strong>A variable</strong> assigned with a normal if above the return, when the logic is too long to read inline.</li></ol><pre>function Greeting({ user }) {<br>  // Early return: deal with the &quot;nothing to show&quot; case first<br>  if (!user) {<br>    return &lt;p&gt;Please sign in.&lt;/p&gt;;<br>  }<br><br>  // Ternary: pick between two pieces of UI<br>  return (<br>    &lt;p&gt;<br>      Welcome back, {user.isAdmin ? &lt;strong&gt;admin {user.name}&lt;/strong&gt; : user.name}!<br>    &lt;/p&gt;<br>  );<br>}<br>function InboxBadge({ count }) {<br>  // ❌ When count is 0, this renders a literal &quot;0&quot; on the page<br>  // return count &amp;&amp; &lt;span className=&quot;badge&quot;&gt;{count} new&lt;/span&gt;;<br>  // ✅ Make the left side a real boolean<br>  return count &gt; 0 &amp;&amp; &lt;span className=&quot;badge&quot;&gt;{count} new&lt;/span&gt;;<br>}</pre><h3>The 0 bug</h3><p>That commented-out line in InboxBadge is the most common conditional bug in React, so it&#39;s worth slowing down on.</p><p>&amp;&amp; doesn&#39;t return true or false. It returns the first falsy value it meets, or the last value if everything is truthy. So 0 &amp;&amp; &lt;span /&gt; evaluates to 0, not false.</p><p>React skips false, null, undefined, and true when rendering. But it <strong>does</strong> render numbers, and 0 is a number. You end up with a lonely &quot;0&quot; sitting where your badge should have been. (NaN has the same problem.)</p><p>The fix is to make sure the left side is an actual boolean: count &gt; 0 &amp;&amp;, items.length &gt; 0 &amp;&amp;, or Boolean(count) &amp;&amp;. In the demo app, step the counter down to zero and you&#39;ll see the buggy and fixed versions side by side.</p><p><strong>Rule of thumb:</strong> if the left side of &amp;&amp; could be a number, compare it to something.</p><h3>Rendering lists with map</h3><p>React renders arrays of elements. So to turn an array of data into UI, you map each item to JSX:</p><pre>const products = [<br>  { id: &#39;p-101&#39;, name: &#39;Mechanical Keyboard&#39;, price: 89 },<br>  { id: &#39;p-103&#39;, name: &#39;27&quot; Monitor&#39;, price: 249 },<br>];<br><br>function ProductNames() {<br>  return (<br>    &lt;ul&gt;<br>      {products.map((product) =&gt; (<br>        &lt;li key={product.id}&gt;<br>          {product.name} · ${product.price}<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>Two details matter here. First, the arrow function uses parentheses, (product) =&gt; ( ... ), so the JSX is returned automatically. If you switch to curly braces, you need an explicit return, and forgetting it is a classic &quot;why is my list empty?&quot; moment.</p><p>Second, the key goes on the <strong>outermost element returned from </strong><strong>map</strong>, not on something nested inside it.</p><h3>What keys actually do</h3><p>When state changes, React compares the new list to the previous one and works out what changed. Keys are how it matches items between the two renders. An item with key p-103 before is the same item as key p-103 after, even if it moved from position 2 to position 0.</p><p>A good key is:</p><ul><li><strong>Stable:</strong> the same item gets the same key on every render.</li><li><strong>Unique among its siblings:</strong> it only needs to be unique within this one list, not across your whole app.</li><li><strong>Tied to the data:</strong> usually the database id, a slug, or an id you created when the item was added.</li></ul><p>What makes a bad key? Math.random() (a new key on every render, so React throws away and rebuilds every row each time), and, more subtly, <strong>the array index</strong>.</p><h3>Why index keys cause bugs</h3><p>Index keys look harmless, and for a list that never reorders, filters, or gets new items at the top, they technically work. The trouble starts the moment the order changes.</p><p>Here’s the demo from the repo. Each row has an uncontrolled &lt;input&gt; where you can type a note:</p><pre>function TodoRow({ todo }) {<br>  return (<br>    &lt;li&gt;<br>      &lt;span&gt;{todo.text}&lt;/span&gt;<br>      &lt;input placeholder=&quot;type a note…&quot; /&gt;<br>    &lt;/li&gt;<br>  );<br>}<br><br>// ❌ Index key: identity follows the position<br>{todos.map((todo, index) =&gt; &lt;TodoRow key={index} todo={todo} /&gt;)}<br>// ✅ Stable key: identity follows the data<br>{todos.map((todo) =&gt; &lt;TodoRow key={todo.id} todo={todo} /&gt;)}</pre><p>Type “draft first” next to <em>Write article 4</em>, then click <strong>Add to top</strong>. Here’s what happens with index keys:</p><ol><li>A new task is inserted at position 0.</li><li>React sees key 0 before and key 0 after, so it assumes it&#39;s the same row and reuses it, including the DOM &lt;input&gt; holding &quot;draft first&quot;.</li><li>It just updates the text from <em>Write article 4</em> to <em>New task 1</em>.</li></ol><p>Your note is now sitting next to the wrong task. Every row has shifted down, but every input stayed where it was.</p><p>With key={todo.id}, React sees a brand-new key at the top, creates one fresh row, and moves the existing rows (with their inputs) down intact. Run both lists side by side in the demo and the difference is obvious within a few seconds.</p><p>The same bug shows up with anything that holds its own state inside a row: component useState, focus, scroll position, animations, or a half-filled form. Index keys are fine only when the list is static and never reordered. For anything else, use an id. If your data doesn&#39;t have one, create it when the item is created (with crypto.randomUUID(), for example), not during render.</p><h3>Filtering, sorting, and empty states</h3><p>Real lists are rarely shown raw. Users filter, search, and sort them. The key idea: <strong>filtered and sorted lists are derived data</strong>. Calculate them during render from the source array and your filter state. Don’t copy them into a separate useState, or you&#39;ll have two sources of truth that drift apart.</p><pre>const [query, setQuery] = useState(&#39;&#39;);<br>const [inStockOnly, setInStockOnly] = useState(false);<br>const [sortBy, setSortBy] = useState(&#39;name&#39;);<br><br>const visible = products<br>  .filter((p) =&gt; !inStockOnly || p.inStock)<br>  .filter((p) =&gt; p.name.toLowerCase().includes(query.trim().toLowerCase()))<br>  .toSorted(sorters[sortBy]); // returns a new array, never mutates `products`<br>return visible.length === 0 ? (<br>  &lt;div className=&quot;empty&quot;&gt;<br>    &lt;p&gt;No products match your filters.&lt;/p&gt;<br>    &lt;button onClick={clearFilters}&gt;Clear filters&lt;/button&gt;<br>  &lt;/div&gt;<br>) : (<br>  &lt;ul&gt;<br>    {visible.map((product) =&gt; (<br>      &lt;ProductItem key={product.id} product={product} /&gt;<br>    ))}<br>  &lt;/ul&gt;<br>);</pre><p>A few things are worth noticing:</p><ul><li><strong>toSorted instead of </strong><strong>sort.</strong> Array.prototype.sort sorts in place, so calling it on props or state mutates data you don&#39;t own. That&#39;s the same immutability rule from Article 2. toSorted (ES2023, supported in all current browsers) returns a copy. On older targets, [...products].sort(...) does the same job.</li><li><strong>The empty state is a real piece of UI.</strong> It explains why the list is empty and gives the user a way out. A blank space just looks broken.</li><li><strong>The ternary chooses between two layouts</strong>, which is exactly the job ternaries are good for.</li></ul><p>If filtering ever becomes slow with thousands of items, there are tools for that later in the series (useMemo in Article 8, virtualization in Article 16). For a few hundred items, plain filter on every render is fast enough, so don&#39;t optimize yet.</p><h3>Splitting a list into item components</h3><p>Once each row has more than a line of markup, pull it into its own component. In the demo, ProductItem owns how a product looks, including its own small condition:</p><pre>export default function ProductItem({ product }) {<br>  return (<br>    &lt;li className=&quot;product&quot;&gt;<br>      &lt;p&gt;{product.name}&lt;/p&gt;<br>      &lt;p&gt;${product.price}&lt;/p&gt;<br>      {!product.inStock &amp;&amp; &lt;span className=&quot;tag&quot;&gt;Out of stock&lt;/span&gt;}<br>    &lt;/li&gt;<br>  );<br>}</pre><p>The parent decides <strong>which</strong> items to show. The item decides <strong>how</strong> one item looks. Notice that key stays in the parent&#39;s map call (&lt;ProductItem key={product.id} ... /&gt;), because the key belongs to the list, not to the item. In fact, key isn&#39;t passed into the component as a prop at all. If ProductItem needs the id, pass it separately as id={product.id}.</p><h3>Common mistakes</h3><ul><li><strong>Rendering </strong><strong>0 with </strong><strong>&amp;&amp;.</strong> {items.length &amp;&amp; &lt;List /&gt;} prints &quot;0&quot; on an empty list. Use items.length &gt; 0 &amp;&amp;.</li><li><strong>Using the index as the key for dynamic lists.</strong> It works until you insert, delete, filter, or sort, and then state ends up on the wrong rows.</li><li><strong>Generating keys during render.</strong> key={Math.random()} or key={crypto.randomUUID()} inside map gives a new key every render, so React remounts every row and loses its state every time.</li><li><strong>Putting </strong><strong>key on the wrong element.</strong> It goes on the outermost element returned from map, not on a child inside it. Need a key on a group with no wrapper? Use &lt;Fragment key={id}&gt; instead of &lt;&gt;.</li><li><strong>Sorting props or state in place.</strong> products.sort() mutates the original array. Use toSorted() or copy first.</li><li><strong>Storing filtered results in state.</strong> Derive them during render instead. Keep only the inputs (query, category, sort order) in state.</li><li><strong>Forgetting the empty state.</strong> An empty &lt;ul&gt; is not a design. Tell users what happened and how to fix it.</li></ul><h3>Recap</h3><ul><li>Use a ternary to choose between two pieces of UI, &amp;&amp; to show something or nothing, and an early return when the whole component has nothing to show.</li><li>Make the left side of &amp;&amp; a boolean, so 0 and NaN never leak onto the page.</li><li>Render lists with map, and put a stable, unique key on the outermost element.</li><li>Keys are identity. Index keys break as soon as the order changes.</li><li>Treat filtered and sorted lists as derived data, sort without mutating, and design the empty state.</li></ul><p>The full demo, with the side-by-side key bug, is in the <a href="https://github.com/hasunnilupul/react-zero-to-hero/tree/main/04-conditional-rendering-lists-keys">repo folder for this article</a>. Break it on purpose: switch the keys, remove the &gt; 0, and watch what happens.</p><p><strong>Next up → Article 5: useEffect: Side Effects, Dependencies, and Cleanup</strong> (Nov 15). So far everything has happened inside render. Next time we step outside it to fetch data, set timers, and subscribe to things, and we’ll learn when you don’t need an effect at all.</p><p>📚 Every article in the series: <a href="https://medium.com/@hasunnilupul/react-zero-to-senior-the-complete-series-index-045e4fa582cc?sharedUserId=hasunnilupul"><strong>React Zero to Senior: The Complete Series</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c9c68e4494" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/conditional-rendering-lists-and-keys-f4c9c68e4494">Conditional Rendering, Lists, and Keys</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Events, Forms, and Controlled Inputs in React 19]]></title>
            <link>https://javascript.plainenglish.io/events-forms-and-controlled-inputs-in-react-19-bb6f50e3679c?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb6f50e3679c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Thu, 05 Nov 2026 12:34:24 GMT</pubDate>
            <atom:updated>2026-11-12T09:06:25.658Z</atom:updated>
            <content:encoded><![CDATA[<p><em>React Zero to Senior · Part 1: Foundations · Article 3 of 24</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0c7cSHjHZiadTUGXxJ9CEQ.png" /></figure><blockquote><strong><em>What you’ll learn:</em></strong><em> how React handles events, the difference between controlled and uncontrolled inputs, and how to build a validated form with text, checkbox, and select fields without fighting the framework.</em></blockquote><p><strong>Versions used in this article:</strong> React 19.3.1, React DOM 19.3.1, Vite 8.3.4, pnpm 10. Everything here works on any React 19.x release.</p><p><strong>Code:</strong> every example lives in the series repo under <a href="https://github.com/hasunnilupul/react-zero-to-hero">03-events-forms</a>. Clone it and run pnpm install &amp;&amp; pnpm dev inside that folder.</p><p>In <a href="https://medium.com/javascript-in-plain-english/props-state-and-one-way-data-flow-a3ea3619a54e">the previous article</a> we passed data down with props and stored it with useState. Data flowed one way: parent to child. But an app that only displays data is a poster. The moment a user clicks, types, or picks an option, information has to flow back <em>into</em> your state.</p><p>That’s what this article is about. Events are how the user talks to your components, and forms are where that conversation gets serious.</p><h3>Handling events: the basics</h3><p>In React you attach event handlers as props, written in camelCase: onClick, onChange, onSubmit, onKeyDown. You pass a <strong>function</strong>, not a string and not a function call.</p><pre>function LikeButton({ postId }) {<br>  const [likes, setLikes] = useState(0);<br>  <br>  function handleClick(event) {<br>    console.log(event.type);          // &quot;click&quot;<br>    console.log(event.currentTarget); // the &lt;button&gt; element<br>    setLikes((n) =&gt; n + 1);<br>  }<br><br>  return (<br>    &lt;&gt;<br>      {/* ✅ pass the function itself */}<br>      &lt;button onClick={handleClick}&gt;👍 {likes}&lt;/button&gt;<br><br>      {/* ✅ need an argument? wrap it in an arrow function */}<br>      &lt;button onClick={() =&gt; reportPost(postId)}&gt;Report&lt;/button&gt;<br><br>      {/* ❌ this CALLS reportPost on every render */}<br>      {/* &lt;button onClick={reportPost(postId)}&gt;Report&lt;/button&gt; */}<br>    &lt;/&gt;<br>  );<br>}</pre><p>That last commented-out line is the single most common event bug for beginners. onClick={reportPost(postId)} runs reportPost immediately during render and passes its <em>return value</em> to onClick. If that function also sets state, you get an infinite render loop and React throws &quot;Too many re-renders.&quot;</p><p>The rule of thumb: if you see parentheses directly inside the braces, ask yourself whether you meant to call it <em>right now</em>.</p><h3>Naming conventions</h3><p>The community convention is:</p><ul><li>Handlers defined inside a component start with handle: handleClick, handleSubmit, handleEmailChange.</li><li>Props that receive a handler start with on: &lt;SearchBar onSearch={handleSearch} /&gt;.</li></ul><p>This makes it obvious at a glance which side of the conversation you’re looking at.</p><h3>What is a synthetic event?</h3><p>The event object your handler receives is not the browser&#39;s native event. It&#39;s a <strong>SyntheticEvent</strong>, a thin wrapper React creates so that events behave the same way across browsers.</p><p>A few things worth knowing:</p><ul><li>It has the same interface you’d expect: target, currentTarget, preventDefault(), stopPropagation(), key, clientX, and so on.</li><li>If you ever need the real browser event, it’s on event.nativeEvent.</li><li>React doesn’t attach a listener to every button. It attaches listeners <strong>once, at the root container</strong> where you mounted your app, and dispatches events to your components from there. You never see this, but it’s why event handling stays cheap even in huge lists.</li><li>Event pooling is gone. Older tutorials warn that you can’t read event.target inside a setTimeout or after an await. That restriction was removed back in React 17, so ignore that advice.</li></ul><h3>target vs currentTarget</h3><ul><li>event.target is the element the user actually interacted with (maybe an &lt;svg&gt; icon inside your button).</li><li>event.currentTarget is the element the handler is attached to (the button itself).</li></ul><p>When you need to read a value or a data- attribute from the element you put the handler on, use currentTarget. For inputs, target and currentTarget are the same element, which is why you&#39;ll see e.target.value everywhere.</p><h3>Controlled vs uncontrolled inputs</h3><p>Here’s where forms get interesting. An &lt;input&gt; already has its own internal state in the DOM: the text you type lives inside the element. React gives you two ways to deal with that.</p><pre>// Controlled: React state is the single source of truth<br>function ControlledName() {<br>  const [name, setName] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;label&gt;<br>      Name<br>      &lt;input value={name} onChange={(e) =&gt; setName(e.target.value)} /&gt;<br>      &lt;small&gt;Hello, {name || &quot;stranger&quot;}&lt;/small&gt;<br>    &lt;/label&gt;<br>  );<br>}<br><br>// Uncontrolled: the DOM keeps the value; you read it when you need it<br>function UncontrolledName() {<br>  function handleSubmit(e) {<br>    e.preventDefault();<br>    const data = new FormData(e.currentTarget);<br>    alert(`Hello, ${data.get(&quot;name&quot;)}`);<br>  }<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input name=&quot;name&quot; defaultValue=&quot;&quot; /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Greet&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p><strong>Controlled</strong> inputs take a value prop and an onChange handler. Every keystroke goes: user types → onChange fires → you call setName → React re-renders → the input shows the new value. React state is the truth; the DOM just mirrors it.</p><p><strong>Uncontrolled</strong> inputs use defaultValue (or defaultChecked for checkboxes) to set a starting value, and then the browser manages the rest. You read the values when you need them, usually on submit, using FormData or a ref.</p><p>Two details that trip people up:</p><ol><li>In React, onChange fires on <strong>every keystroke</strong>, not when the input loses focus like the native change event. React&#39;s onChange behaves like the native input event.</li><li>If you pass value without onChange, the input becomes read-only and React warns you in the console. Either add onChange, switch to defaultValue, or add readOnly if that&#39;s what you meant.</li></ol><h3>Which one should you use?</h3><p>Use <strong>controlled</strong> when… Use <strong>uncontrolled</strong> when… You validate as the user types You only need the values on submit One field affects another (e.g. “same as billing address”) The form is simple and mostly static You format input live (uppercase, phone masks) You’re integrating non-React code or a file input The submit button is disabled until the form is valid You want the least re-rendering possible</p><p>For this series we’ll default to controlled inputs while learning, because they make the data flow visible. In Article 19 we’ll meet React Hook Form, which is built on uncontrolled inputs for performance, and the trade-off will make a lot more sense.</p><blockquote><strong><em>Note:</em></strong><em> </em><em>&lt;input type=&quot;file&quot;&gt; is always uncontrolled. Its value can only be set by the user, for security reasons.</em></blockquote><h3>Building a real form</h3><p>Let’s put it together: a workshop sign-up form with a text field, an email field, a select, a checkbox, validation, and error messages.</p><p>The trick that keeps this manageable is <strong>one state object for all the fields</strong> and <strong>one change handler</strong> that uses each input’s name attribute.</p><pre>import { useState } from &quot;react&quot;;<br><br>const initialValues = { name: &quot;&quot;, email: &quot;&quot;, track: &quot;&quot;, agree: false };<br><br>function validate(values) {<br>  const errors = {};<br>  if (!values.name.trim()) errors.name = &quot;Name is required.&quot;;<br>  if (!/^\S+@\S+\.\S+$/.test(values.email)) errors.email = &quot;Enter a valid email.&quot;;<br>  if (!values.track) errors.track = &quot;Pick a track.&quot;;<br>  if (!values.agree) errors.agree = &quot;You must accept the code of conduct.&quot;;<br>  return errors;<br>}<br><br>export default function SignupForm() {<br>  const [values, setValues] = useState(initialValues);<br>  const [touched, setTouched] = useState({});<br>  const [submitted, setSubmitted] = useState(false);<br>  const errors = validate(values); // derived on every render, never stored<br>  <br>  const showError = (field) =&gt; (touched[field] || submitted) &amp;&amp; errors[field];<br>  <br>  function handleChange(e) {<br>    const { name, type, value, checked } = e.target;<br>    setValues((v) =&gt; ({ ...v, [name]: type === &quot;checkbox&quot; ? checked : value }));<br>  }<br>  <br>  function handleBlur(e) {<br>    setTouched((t) =&gt; ({ ...t, [e.target.name]: true }));<br>  }<br>  <br>  function handleSubmit(e) {<br>    e.preventDefault(); // stop the browser&#39;s full-page reload<br>    setSubmitted(true);<br>    if (Object.keys(errors).length &gt; 0) return;<br>    console.log(&quot;Submitting&quot;, values);<br>    setValues(initialValues);<br>    setTouched({});<br>    setSubmitted(false);<br>  }<br><br>  return (<br>    &lt;form onSubmit={handleSubmit} noValidate&gt;<br>      &lt;label htmlFor=&quot;name&quot;&gt;Name&lt;/label&gt;<br>      &lt;input id=&quot;name&quot; name=&quot;name&quot; value={values.name}<br>        onChange={handleChange} onBlur={handleBlur}<br>        aria-invalid={!!showError(&quot;name&quot;)} aria-describedby=&quot;name-error&quot; /&gt;<br>      {showError(&quot;name&quot;) &amp;&amp; &lt;p id=&quot;name-error&quot; role=&quot;alert&quot;&gt;{errors.name}&lt;/p&gt;}<br><br>      &lt;label htmlFor=&quot;email&quot;&gt;Email&lt;/label&gt;<br>      &lt;input id=&quot;email&quot; name=&quot;email&quot; type=&quot;email&quot; value={values.email}<br>        onChange={handleChange} onBlur={handleBlur}<br>        aria-invalid={!!showError(&quot;email&quot;)} aria-describedby=&quot;email-error&quot; /&gt;<br>      {showError(&quot;email&quot;) &amp;&amp; &lt;p id=&quot;email-error&quot; role=&quot;alert&quot;&gt;{errors.email}&lt;/p&gt;}<br>      <br>      &lt;label htmlFor=&quot;track&quot;&gt;Track&lt;/label&gt;<br>      &lt;select id=&quot;track&quot; name=&quot;track&quot; value={values.track}<br>        onChange={handleChange} onBlur={handleBlur}&gt;<br>        &lt;option value=&quot;&quot;&gt;Choose one…&lt;/option&gt;<br>        &lt;option value=&quot;beginner&quot;&gt;Beginner&lt;/option&gt;<br>        &lt;option value=&quot;advanced&quot;&gt;Advanced&lt;/option&gt;<br>      &lt;/select&gt;<br>      {showError(&quot;track&quot;) &amp;&amp; &lt;p role=&quot;alert&quot;&gt;{errors.track}&lt;/p&gt;}<br>      <br>      &lt;label&gt;<br>        &lt;input type=&quot;checkbox&quot; name=&quot;agree&quot; checked={values.agree}<br>          onChange={handleChange} onBlur={handleBlur} /&gt;<br>        I accept the code of conduct<br>      &lt;/label&gt;<br>      {showError(&quot;agree&quot;) &amp;&amp; &lt;p role=&quot;alert&quot;&gt;{errors.agree}&lt;/p&gt;}<br><br>      &lt;button type=&quot;submit&quot;&gt;Sign up&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>There’s a lot packed in here, so let’s walk through the decisions that matter.</p><p><strong>One handler for every field.</strong> Each input has a name that matches a key in values. The handler reads e.target.name and updates just that key with a computed property: [name]: .... Adding a new field means adding an input and a key, not a new handler.</p><p><strong>Checkboxes read </strong><strong>checked, not </strong><strong>value.</strong> A checkbox&#39;s value is just a label string that never changes. Its on/off state lives in checked, so the handler branches on type. Controlled checkboxes use the checked prop instead of value.</p><p><strong>Selects are controlled on the </strong><strong>&lt;select&gt;.</strong> In plain HTML you&#39;d put selected on an &lt;option&gt;. In React you put value on the &lt;select&gt; itself, and React selects the matching option for you.</p><p><strong>Errors are derived, not stored.</strong> We never call setErrors. Errors are a pure function of values, so we compute them during render. Storing them separately would mean keeping two pieces of state in sync, and that&#39;s how bugs are born. This is the same principle from Article 2: don&#39;t store what you can calculate.</p><p><strong>Errors show at the right time.</strong> Nobody likes a form that screams “Name is required!” before they’ve typed a single letter. The touched state records which fields the user has left, and submitted reveals all remaining errors when they hit the button. That small piece of UX makes forms feel polite.</p><p><strong>noValidate on the form.</strong> We turn off the browser&#39;s built-in validation bubbles so our own messages are the only ones shown, and they look the same in every browser.</p><p><strong>Accessibility comes along for free.</strong> Every input has a &lt;label&gt; connected with htmlFor and id (for is a reserved word in JavaScript, so React uses htmlFor). aria-invalid tells screen readers the field has a problem, aria-describedby points to the message, and role=&quot;alert&quot; announces it when it appears. We&#39;ll go much deeper on this in Article 22.</p><h3>Preventing default behavior</h3><p>Some elements come with built-in browser behavior:</p><ul><li>Submitting a &lt;form&gt; reloads the page (or navigates to its action URL).</li><li>Clicking an &lt;a href&gt; navigates.</li><li>Pressing Enter in a text input inside a form submits it.</li></ul><p>When you want React to handle the interaction instead, call e.preventDefault() in your handler. Unlike some older frameworks, <strong>returning </strong><strong>false from a handler does nothing in React</strong>. You have to call the method.</p><p>Put preventDefault() in the form&#39;s onSubmit, not in the submit button&#39;s onClick. The onSubmit handler catches <em>every</em> way a form can be submitted, including pressing Enter, while onClick only catches the mouse.</p><blockquote><strong><em>A peek ahead at React 19:</em></strong><em> React 19 also lets you pass a function to </em><em>&lt;form action={...}&gt;. React then calls it with the form&#39;s </em><em>FormData, handles the submission without a page reload, and resets uncontrolled fields afterwards. It pairs with hooks like </em><em>useActionState and </em><em>useFormStatus. It&#39;s a powerful pattern, and we&#39;ll cover it properly in Article 17 once we&#39;ve met transitions. For now, </em><em>onSubmit plus </em><em>preventDefault() is the foundation everything else builds on.</em></blockquote><h3>Event propagation and other pitfalls</h3><p>React events bubble just like DOM events: a click on a button inside a card fires the button’s onClick, then the card&#39;s. Usually that&#39;s what you want. When it isn&#39;t, stop it at the source.</p><pre>function TaskCard({ task, onOpen, onDelete }) {<br>  return (<br>    &lt;div className=&quot;card&quot; onClick={() =&gt; onOpen(task.id)}&gt;<br>      &lt;h3&gt;{task.title}&lt;/h3&gt;<br>      &lt;button<br>        type=&quot;button&quot;<br>        onClick={(e) =&gt; {<br>          e.stopPropagation(); // don&#39;t also open the card<br>          onDelete(task.id);<br>        }}<br>      &gt;<br>        Delete<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Notice type=&quot;button&quot;. A &lt;button&gt; inside a &lt;form&gt; defaults to type=&quot;submit&quot;, so a &quot;Delete&quot; or &quot;Toggle password&quot; button with no type will quietly submit the whole form. Get into the habit of writing the type on every button.</p><p>(In a real app, a clickable card should also be reachable by keyboard. Using a &lt;button&gt; or a link for the main action, rather than onClick on a &lt;div&gt;, is the accessible fix. We&#39;ll cover that in Article 22.)</p><h3>Common mistakes</h3><ol><li><strong>Calling the handler instead of passing it.</strong> onClick={save()} runs on render. Use onClick={save} or onClick={() =&gt; save(id)}.</li><li><strong>value without </strong><strong>onChange.</strong> The input freezes and React warns you. Add a handler, or use defaultValue.</li><li><strong>Switching between controlled and uncontrolled.</strong> Starting with value={user.name} when user.name is undefined makes the input uncontrolled, then controlled once data arrives, and React warns about it. Always initialize to &quot;&quot; (or false for checkboxes), for example value={user.name ?? &quot;&quot;}.</li><li><strong>Reading </strong><strong>value from a checkbox.</strong> Use e.target.checked.</li><li><strong>Forgetting that inputs give you strings.</strong> &lt;input type=&quot;number&quot;&gt; still returns &quot;42&quot;, not 42. Convert with Number(e.target.value) (and handle the empty string) before doing math.</li><li><strong>Storing errors in state.</strong> Derive them from your values instead, so they can never fall out of sync.</li><li><strong>Buttons without </strong><strong>type.</strong> Inside a form, they default to submit.</li></ol><h3>Wrapping up</h3><p>You now have the full loop of a React app: state flows <strong>down</strong> through props, and user intent flows back <strong>up</strong> through event handlers that update state. Controlled inputs make that loop explicit for forms, which is exactly why they’re the best place to start.</p><p>The key ideas to take with you:</p><ul><li>Pass functions to event props; don’t call them.</li><li>Controlled inputs: value + onChange, with React state as the source of truth. Uncontrolled: defaultValue, read on submit.</li><li>One values object, one handleChange, and validation derived on render keeps forms simple.</li><li>preventDefault() in onSubmit, stopPropagation() when bubbling gets in the way, and type=&quot;button&quot; on every non-submit button.</li></ul><p><strong>Try it yourself:</strong> add a “Confirm email” field to the sign-up form that shows an error when it doesn’t match the first email. You won’t need any new state for the error. Can you see why?</p><p><strong>Next up:</strong> <a href="https://javascript.plainenglish.io/conditional-rendering-lists-and-keys-f4c9c68e4494?sharedUserId=hasunnilupul">Conditional Rendering, Lists, and Keys</a>: showing and hiding UI, rendering lists with map, and a live demo of why index keys cause real bugs.</p><p><em>This article is part of the </em><a href="https://medium.com/@hasunnilupul/react-zero-to-senior-the-complete-series-index-045e4fa582cc?sharedUserId=hasunnilupul"><em>React Zero to Senior series</em></a><em>. Follow along for a new article every five days.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb6f50e3679c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/events-forms-and-controlled-inputs-in-react-19-bb6f50e3679c">Events, Forms, and Controlled Inputs in React 19</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Props, State, and One-Way Data Flow]]></title>
            <link>https://javascript.plainenglish.io/props-state-and-one-way-data-flow-a3ea3619a54e?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/a3ea3619a54e</guid>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Sun, 01 Nov 2026 11:15:36 GMT</pubDate>
            <atom:updated>2026-11-12T09:07:17.635Z</atom:updated>
            <content:encoded><![CDATA[<p><em>React Zero to Senior, Part 1: Foundations · Article 2 of 24</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFxHVpBc6kS-X_yvAXFk1A.png" /><figcaption>Props, useState, and lifting state up</figcaption></figure><p><strong>What you’ll learn:</strong> how data moves through a React app, how to pass it down with props, how to remember it with useState, and how to share it between components by lifting state up.</p><p>In <a href="https://medium.com/javascript-in-plain-english/how-react-thinks-components-jsx-and-the-render-model-1cbc32ed3885">article 1</a> we treated the UI as a function of state, but we never changed any state. This article fixes that. By the end you will build a small cart where two separate components stay in sync, and you will know why React insists on updating data in one direction only.</p><p><strong>Versions used:</strong> React 19, Vite 8 (Node.js 20.19 or newer), pnpm. Create the project with pnpm create vite@latest props-state --template react, then pnpm install and pnpm dev. Code: the 02-props-state-data-flow folder in the <a href="https://github.com/hasunnilupul/react-zero-to-hero">series repo</a>.</p><p><strong>Reading time:</strong> about 9 minutes.</p><h3>Props: passing data down</h3><p>Props are the arguments of a component. A parent decides what to hand over, and the child receives it as a single object. The child can read props but must never change them. That rule is the foundation of one-way data flow: data goes down, and only the owner of the data can change it.</p><p>Destructure props in the function signature, give optional ones defaults, and use children for anything nested between the opening and closing tags.</p><pre>// ProfileCard.jsx<br>function ProfileCard({ name, role = &quot;Developer&quot;, children }) {<br>  return (<br>    &lt;section className=&quot;card&quot;&gt;<br>      &lt;h2&gt;{name}&lt;/h2&gt;<br>      &lt;p&gt;{role}&lt;/p&gt;<br>      {children}<br>    &lt;/section&gt;<br>  );<br>}<br><br>// App.jsx<br>&lt;ProfileCard name=&quot;Nilupul&quot; role=&quot;Senior Engineer&quot;&gt;<br>  &lt;button&gt;Follow&lt;/button&gt;<br>&lt;/ProfileCard&gt;<br>&lt;ProfileCard name=&quot;Sam&quot; /&gt;   {/* role falls back to &quot;Developer&quot; */}</pre><p>Two details trip up beginners. Strings can be passed as name=&quot;Sam&quot;, but everything else needs braces: age={30}, isAdmin={true}, tags={[&quot;a&quot;, &quot;b&quot;]}. And children is just another prop, which is what makes wrapper components like cards, layouts and modals possible.</p><p>One-way flow means a child never reaches up and edits what it was given. If a child needs to request a change, the parent passes down a function as a prop. You will use that in a moment.</p><h3>State: data a component remembers</h3><p>Props come from outside. State belongs to the component itself. A plain variable resets on every render and changing it does not trigger one, so React gives you useState for values that change over time.</p><pre>import { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  function addThree() {<br>    setCount(count + 1);<br>    setCount(count + 1);<br>    setCount(count + 1);          // still only +1<br>    // setCount((c) =&gt; c + 1) x3  // +3, uses the latest value<br>  }<br><br>  return &lt;button onClick={addThree}&gt;Clicked {count} times&lt;/button&gt;;<br>}</pre><p>useState returns the current value and a setter. Calling the setter does not change count right away. It asks React to re-render with a new value. That is why the three calls above add only one: each reads the same snapshot of count from the current render. React also <strong>batches</strong> updates from one event into a single re-render, so the screen updates once, not three times.</p><p>When the next value depends on the previous one, pass an updater function, setCount((c) =&gt; c + 1). React feeds it the latest queued value, so the three calls correctly add three.</p><p>Rule of thumb: if a value can be computed from props or other state, do not store it. Compute it during render.</p><h3>Updating objects and arrays immutably</h3><p>React decides whether to re-render by comparing the old state to the new state by reference. If you edit an object in place, the reference is the same, so React sees no change and the screen goes stale. The fix is to treat state as read-only and always set a fresh copy.</p><pre>// object: copy with spread, override one field<br>setUser({ ...user, name: &quot;Sam&quot; });<br><br>// array: add, remove, update, each returns a NEW array<br>setItems([...items, newItem]);                              // add<br>setItems(items.filter((i) =&gt; i.id !== id));                 // remove<br>setItems(items.map((i) =&gt; (i.id === id ? { ...i, qty: i.qty + 1 } : i))); // update</pre><p>The pattern is always the same: spread the old data into a new object or array, then change only what you need. Avoid push, splice, sort and direct assignment such as user.name = &quot;Sam&quot; on state, because they change the original. For deeply nested data, copy each level on the path you change, or reach for a helper like Immer later in the series.</p><h3>Lifting state up</h3><p>What if two components need the same data? A product list needs to add items to the cart, and a summary needs to show them. Siblings cannot pass data to each other, and data only flows down. So you move the state to their closest common parent, then pass the value down as props and the update function down as a callback.</p><pre>// App.jsx: the parent owns the cart<br>import { useState } from &quot;react&quot;;<br>import ProductList from &quot;./ProductList&quot;;<br>import CartSummary from &quot;./CartSummary&quot;;<br><br>const PRODUCTS = [<br>  { id: 1, name: &quot;Keyboard&quot;, price: 49 },<br>  { id: 2, name: &quot;Mouse&quot;, price: 25 },<br>  { id: 3, name: &quot;Monitor&quot;, price: 189 },<br>];<br><br>export default function App() {<br>  const [cart, setCart] = useState([]);<br><br>  const addToCart = (product) =&gt; setCart([...cart, product]);<br>  const removeAt = (index) =&gt; setCart(cart.filter((_, i) =&gt; i !== index));<br><br>  return (<br>    &lt;&gt;<br>      &lt;ProductList products={PRODUCTS} onAdd={addToCart} /&gt;<br>      &lt;CartSummary items={cart} onRemove={removeAt} /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>// ProductList.jsx: reads props, asks the parent to change data<br>export default function ProductList({ products, onAdd }) {<br>  return (<br>    &lt;ul&gt;<br>      {products.map((p) =&gt; (<br>        &lt;li key={p.id}&gt;<br>          {p.name} ${p.price}<br>          &lt;button onClick={() =&gt; onAdd(p)}&gt;Add&lt;/button&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>// CartSummary.jsx: derives the total instead of storing it<br>export default function CartSummary({ items, onRemove }) {<br>  const total = items.reduce((sum, item) =&gt; sum + item.price, 0);<br><br>  return (<br>    &lt;aside&gt;<br>      &lt;h2&gt;Cart ({items.length})&lt;/h2&gt;<br>      {items.map((item, i) =&gt; (<br>        &lt;p key={i}&gt;<br>          {item.name} &lt;button onClick={() =&gt; onRemove(i)}&gt;Remove&lt;/button&gt;<br>        &lt;/p&gt;<br>      ))}<br>      &lt;strong&gt;Total: ${total}&lt;/strong&gt;<br>    &lt;/aside&gt;<br>  );<br>}</pre><p>Follow one click through the loop. The button calls onAdd, which is the parent&#39;s addToCart. The parent sets new state, React re-renders App, and both children receive fresh props. Neither child owns the cart, and neither can reach sideways into the other. Data goes down, events go up.</p><p>Notice that total is not state. It is calculated from items on every render, so it can never drift out of sync. (The index key in CartSummary is a shortcut for this demo. Article 4 explains why stable keys matter.)</p><p>Lift state only as high as it needs to go. If just one component uses a value, keep it there.</p><h3>Common mistakes</h3><p><strong>1. Mutating state directly.</strong> The classic bug: the data changes, the screen does not.</p><pre>// Broken: same array reference, React sees no change<br>function addToCart(product) {<br>  cart.push(product);<br>  setCart(cart);<br>}<br><br>// Fixed: a new array<br>function addToCart(product) {<br>  setCart([...cart, product]);<br>}</pre><p><strong>2. Expecting the value to change right after calling the setter.</strong> Logging count straight after setCount(count + 1) prints the old value. The new one arrives on the next render.</p><p><strong>3. Calling the handler instead of passing it.</strong> onClick={addToCart(p)} runs during render and causes an infinite loop. Write onClick={() =&gt; addToCart(p)}.</p><p><strong>4. Copying props into state.</strong> useState(props.price) captures the value once and ignores later changes. Use the prop directly, or compute from it.</p><p><strong>5. Storing derived values.</strong> Totals, counts and filtered lists belong in render, not in extra state that you have to keep in sync.</p><h3>Recap and next up</h3><ul><li>Props flow down and are read-only; children is a prop too.</li><li>State is a component’s memory. Setters queue a re-render, and updates in one event are batched.</li><li>Update objects and arrays by making copies, never by editing the original.</li><li>When siblings need the same data, lift state to their common parent and pass down values and callbacks.</li></ul><p><strong>Try it:</strong> extend the cart so that adding the same product twice increases a quantity instead of adding a second row. Hint: use map with a spread to update the matching item.</p><p><strong>Next up:</strong> <a href="https://javascript.plainenglish.io/events-forms-and-controlled-inputs-in-react-19-bb6f50e3679c?sharedUserId=hasunnilupul">Events, Forms, and Controlled Inputs</a>. We will wire up real user input and make React the single source of truth for every field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a3ea3619a54e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/props-state-and-one-way-data-flow-a3ea3619a54e">Props, State, and One-Way Data Flow</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Zero to Senior: The Complete Series]]></title>
            <link>https://hasunnilupul.medium.com/react-zero-to-senior-the-complete-series-index-045e4fa582cc?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/045e4fa582cc</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 10:33:26 GMT</pubDate>
            <atom:updated>2026-11-12T04:24:44.177Z</atom:updated>
            <content:encoded><![CDATA[<p><em>24 articles that take you from “what is JSX?” to senior-level React 19.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qoxW1HeOFDXDymgWd5eWEg.png" /><figcaption><em>24 articles that take you from “what is JSX?” to senior-level React 19</em></figcaption></figure><p>Every article in the series, in reading order. A new one comes out every 5 days, and I update this page each time. Bookmark it to follow along.</p><p>New to React? Start at Article 1. Already comfortable? Jump to the part that fits you. All the code is in one repo, with a folder per article: <a href="https://github.com/hasunnilupul/react-zero-to-hero"><strong>GitHub: react-zero-to-senior</strong></a></p><h3>Part 1: Foundations</h3><p><strong>1.</strong> <a href="https://medium.com/javascript-in-plain-english/how-react-thinks-components-jsx-and-the-render-model-1cbc32ed3885?sharedUserId=hasunnilupul">How React Thinks: Components, JSX, and the Render Model </a>· Oct 26 ✅</p><p><strong>2.</strong> <a href="https://medium.com/javascript-in-plain-english/props-state-and-one-way-data-flow-a3ea3619a54e?sharedUserId=hasunnilupul">Props, State, and One-Way Data Flow</a> · Oct 31 ✅</p><p><strong>3.</strong> <a href="https://javascript.plainenglish.io/events-forms-and-controlled-inputs-in-react-19-bb6f50e3679c?sharedUserId=hasunnilupul">Events, Forms, and Controlled Inputs</a> · Nov 5 ✅</p><p><strong>4.</strong> <a href="https://medium.com/javascript-in-plain-english/conditional-rendering-lists-and-keys-f4c9c68e4494?sharedUserId=hasunnilupul">Conditional Rendering, Lists, and Keys</a> · Nov 10 ✅</p><p><strong>5.</strong> useEffect: Side Effects, Dependencies, and Cleanup · Nov 15</p><p><strong>6.</strong> Mini Project: Build a Task Tracker · Nov 20</p><h3>Part 2: Intermediate</h3><p><strong>7.</strong> Custom Hooks and Logic Reuse · Nov 25</p><p><strong>8.</strong> useRef, useMemo, useCallback: When They Help and When They Don’t · Nov 30</p><p><strong>9.</strong> Context API and Avoiding Prop Drilling · Dec 5</p><p><strong>10.</strong> useReducer and Complex State · Dec 10</p><p><strong>11.</strong> Routing with React Router · Dec 15</p><p><strong>12.</strong> Data Fetching with TanStack Query · Dec 20</p><p><strong>13.</strong> Project: A Multi-Page App with Real API Data · Dec 25</p><h3>Part 3: Advanced</h3><p><strong>14.</strong> Component Design Patterns · Dec 30</p><p><strong>15.</strong> Global State: Zustand, Redux Toolkit, and How to Choose · Jan 4</p><p><strong>16.</strong> Performance: Reconciliation, Memoization, Profiling, Code Splitting · Jan 9</p><p><strong>17.</strong> Concurrent React: Suspense, Transitions, and use · Jan 14</p><p><strong>18.</strong> TypeScript with React · Jan 19</p><p><strong>19.</strong> Forms at Scale: React Hook Form and Zod · Jan 24</p><h3>Part 4: Senior-Level</h3><p><strong>20.</strong> Testing React Apps: Testing Library, Vitest, and Mocking · Jan 29</p><p><strong>21.</strong> Server Components and Next.js Architecture · Feb 3</p><p><strong>22.</strong> Accessibility and Error Boundaries · Feb 8</p><p><strong>23.</strong> Project Structure, Scalability, and Micro-Frontends · Feb 13</p><p><strong>24.</strong> Capstone: Shipping to Production and What “Senior” Really Means · Feb 18</p><p>Follow me on Medium to get each article the day it’s out, and leave a comment if there’s a topic you’d like covered.</p><p>Start here → <a href="https://medium.com/javascript-in-plain-english/how-react-thinks-components-jsx-and-the-render-model-1cbc32ed3885?sharedUserId=hasunnilupul"><strong>Article 1: How React Thinks</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=045e4fa582cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How React Thinks: Components, JSX, and the Render Model]]></title>
            <link>https://javascript.plainenglish.io/how-react-thinks-components-jsx-and-the-render-model-1cbc32ed3885?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cbc32ed3885</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 10:18:20 GMT</pubDate>
            <atom:updated>2026-11-03T04:31:51.753Z</atom:updated>
            <content:encoded><![CDATA[<p><em>React Zero to Senior, Part 1: Foundations · Article 1 of 24</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpS4AemINWaiQneBO3D1cg.png" /><figcaption>React Zero to Senior, Article 1: How React Thinks</figcaption></figure><p><strong>What you’ll learn:</strong> what problem React solves, how to start a project with Vite, how JSX really works, and the one mental model (UI as a function of state) that the rest of this series builds on.</p><p><strong>Versions used in this article:</strong> React 19.3.1, React DOM 19.3.1, Vite 8, Node.js 22 LTS. Code lives in the series repo under <a href="https://github.com/hasunnilupul/react-zero-to-hero/tree/main/01-how-react-thinks">01-how-react-thinks/</a></p><h3>Why React exists</h3><p>Imagine a page with a counter. When the user clicks a button, the number on screen must change. With plain JavaScript you write the steps yourself: find the element, read its text, add one, write it back.</p><p>That works for one counter. Now picture a shopping cart, a notification badge, a total price, and a “checkout” button that is disabled when the cart is empty. A single click now has to update five places, and every new feature adds more places to forget. This is the problem with <strong>imperative</strong> UI code: you describe <em>how</em> to change the screen, step by step, and you are responsible for keeping everything in sync.</p><p>React flips this around. You write <strong>declarative</strong> code: you describe <em>what the screen should look like</em> for the current data, and React works out how to get there. You stop issuing DOM instructions and start describing outcomes.</p><p>That one idea is the foundation of everything in this series.</p><h3>Setting up a project with Vite</h3><p>Vite is a fast dev server and build tool. It has largely replaced Create React App as the default way to start a client-side React project.</p><pre>npm create vite@latest 01-how-react-thinks -- --template react<br>cd how-react-thinks<br>npm install<br>npm run dev</pre><p>Open the local URL it prints (usually http://localhost:5173). Check that package.json lists React 19. If it shows an older version, run npm install react@19 react-dom@19.</p><p>A quick tour of what Vite generated:</p><ul><li><strong>index.html</strong> is the single page of your app. It contains an empty &lt;div id=&quot;root&quot;&gt; and a script tag that loads your code.</li><li><strong>src/main.jsx</strong> is the entry point. It finds that root div and tells React to render your app inside it.</li><li><strong>src/App.jsx</strong> is your first component, the one you will edit most.</li><li><strong>vite.config.js</strong> holds build settings. You can ignore it for now.</li></ul><p>Everything React draws on the page ends up inside that one root div. React owns that div; you never reach in and change its contents by hand.</p><h3>JSX: HTML-looking syntax that is really JavaScript</h3><p>Open src/App.jsx and replace its contents with this:</p><pre>function App() {<br>  const name = &quot;Nilupul&quot;;<br>  const year = new Date().getFullYear();<br><br>  return (<br>    &lt;&gt;<br>      &lt;h1 className=&quot;title&quot;&gt;Hello, {name}!&lt;/h1&gt;<br>      &lt;p&gt;It is {year}, and this page is built with React.&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>export default App;</pre><p>That &lt;h1&gt; looks like HTML, but it is <strong>JSX</strong>, a syntax extension that lets you write markup inside JavaScript. Browsers do not understand JSX. Vite compiles it before it ever reaches the browser. Under the hood, the &lt;h1&gt; line becomes roughly this:</p><pre>_jsx(&quot;h1&quot;, { className: &quot;title&quot;, children: [&quot;Hello, &quot;, name, &quot;!&quot;] });</pre><p>Each JSX tag turns into a plain function call that returns a lightweight JavaScript object describing what you want on screen. Once you see that JSX is just function calls, its rules stop feeling arbitrary:</p><ol><li><strong>Curly braces run JavaScript.</strong> {name} and {year} are expressions. You can put anything inside that produces a value: variables, math, function calls, ternaries. You cannot put statements like if or for there.</li><li><strong>Attributes are camelCase.</strong> It is className, not class, because class is a reserved word in JavaScript. Likewise onClick, htmlFor, tabIndex.</li><li><strong>A component returns one root.</strong> A function can only return one value, so sibling elements must be wrapped. Use a <strong>fragment</strong> (&lt;&gt;...&lt;/&gt;) when you do not want an extra &lt;div&gt; in the page.</li><li><strong>Every tag must close.</strong> &lt;img /&gt; and &lt;input /&gt; need the trailing slash.</li><li><strong>Strings use quotes, everything else uses braces.</strong> className=&quot;title&quot; is a string; tabIndex={0} is a number.</li></ol><h3>Components: functions that return UI</h3><p>A <strong>component</strong> is a JavaScript function that returns JSX. That is the whole definition. App above is one. Components let you name a piece of UI and reuse it:</p><pre>function Greeting() {<br>  return &lt;h2&gt;Welcome to React&lt;/h2&gt;;<br>}<br><br>function App() {<br>  return (<br>    &lt;&gt;<br>      &lt;Greeting /&gt;<br>      &lt;Greeting /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>Two conventions matter from day one:</p><ul><li><strong>Component names start with a capital letter.</strong> &lt;Greeting /&gt; is treated as a component; &lt;greeting /&gt; is treated as an HTML tag that does not exist. This is the most common reason a new component silently renders nothing useful.</li><li><strong>One component per file is a good default</strong>, with the file named after the component: Greeting.jsx. Small helper components can share a file with their parent while you are learning.</li></ul><p>Notice that &lt;Greeting /&gt; is also compiled to a function call. React calls your function, gets back a description of the UI, and keeps going until it has described the whole screen.</p><h3>The mental model: UI is a function of state</h3><p>Here is the idea to remember from this article:</p><blockquote><strong><em>UI = f(state)</em></strong></blockquote><p>Given the same data, your component should always describe the same screen. When the data changes, React calls your component again with the new data and compares the new description to the old one. It then updates only the parts of the real DOM that differ.</p><p>Let’s see it with a counter. We will use useState here only to make something change, and we will study it properly in the next article.</p><pre>import { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      You clicked {count} times<br>    &lt;/button&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>Walk through what happens:</p><ol><li><strong>First render.</strong> React calls Counter(). useState(0) returns count as 0. The function returns a button reading &quot;You clicked 0 times&quot;, and React puts it on the page.</li><li><strong>A click.</strong> setCount(count + 1) tells React that the state is now 1. Note that you did not touch the button&#39;s text.</li><li><strong>Re-render.</strong> React calls Counter() again. This time useState returns 1, so the function returns a button reading &quot;You clicked 1 times&quot;. React compares it to the previous result, sees that only the text changed, and updates just that text node.</li></ol><p><strong>“Render” means “React calls your component function to find out what the UI should look like.”</strong> It does not mean “paint pixels” or “touch the DOM.” Rendering is just running your function, which is why components should be <em>pure</em>: no hidden changes to outside variables, same inputs giving the same output. Keeping render free of side effects is a rule you will lean on in every article that follows.</p><p>Compare this with the imperative version. You never wrote “find the button, read its text, add one.” You wrote what the button should say for a given count, and React handled the rest.</p><h3>Common mistakes</h3><ul><li><strong>Lowercase component names.</strong> &lt;counter /&gt; will not render your component. Capitalize it.</li><li><strong>Using </strong><strong>class instead of </strong><strong>className.</strong> React will warn you in the console; fix it as soon as you see it.</li><li><strong>Returning two sibling elements without a wrapper.</strong> Wrap them in a fragment (&lt;&gt;...&lt;/&gt;).</li><li><strong>Putting statements inside braces.</strong> {if (x) ...} is invalid because braces accept expressions only. Use a ternary ({x ? &quot;a&quot; : &quot;b&quot;}) or compute the value above the return.</li><li><strong>Changing the DOM by hand.</strong> Calling document.getElementById(...) to edit what React rendered fights the model. Describe the change through state instead.</li><li><strong>Forgetting that render can run more than once.</strong> Never assume your component function runs exactly once. It runs every time its data changes (and twice in development under Strict Mode, which we will meet in article 5).</li></ul><h3>Recap</h3><ul><li>React is <strong>declarative</strong>: you describe the UI for the current data and React makes the screen match.</li><li><strong>Vite</strong> gives you a fast project, and React draws everything inside a single root element.</li><li><strong>JSX</strong> is syntax that compiles to function calls; its rules follow from that.</li><li>A <strong>component</strong> is a function that returns JSX, with a capitalized name.</li><li><strong>UI = f(state)</strong>: “render” means React calls your function to learn what the screen should be.</li></ul><p><strong>Next up:</strong> <a href="https://medium.com/javascript-in-plain-english/props-state-and-one-way-data-flow-a3ea3619a54e">Props, State, and One-Way Data Flow</a>. We will pass data between components, look closely at useState, and learn why you must never mutate state directly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cbc32ed3885" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-react-thinks-components-jsx-and-the-render-model-1cbc32ed3885">How React Thinks: Components, JSX, and the Render Model</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering the Native HTML <dialog> Element — A Modern Approach to Modals]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/mastering-the-native-html-dialog-element-a-modern-approach-to-modals-7ae944386673?source=rss-715e55318b35------2"><img src="https://cdn-images-1.medium.com/max/1536/1*jWC6xxarRDh6-EEoRGGDyA.png" width="1536"></a></p><p class="medium-feed-snippet">Look, the frontend ecosystem has been drowning in modal libraries for years&#x200A;&#x2014;&#x200A;React Modal, Radix Dialog, Headless UI, you name it. But&#x2026;</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/mastering-the-native-html-dialog-element-a-modern-approach-to-modals-7ae944386673?source=rss-715e55318b35------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/mastering-the-native-html-dialog-element-a-modern-approach-to-modals-7ae944386673?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ae944386673</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 16:21:29 GMT</pubDate>
            <atom:updated>2025-11-27T16:21:29.422Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[React Compiler Goes Stable: Revolutionizing Performance in React Apps]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/react-compiler-goes-stable-revolutionizing-performance-in-react-apps-5ebabda9b797?source=rss-715e55318b35------2"><img src="https://cdn-images-1.medium.com/max/1536/1*oKwFq4PaqsA2Xx-eGYORug.png" width="1536"></a></p><p class="medium-feed-snippet">At React Conf 2025, the React team dropped a game-changing announcement</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/react-compiler-goes-stable-revolutionizing-performance-in-react-apps-5ebabda9b797?source=rss-715e55318b35------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/react-compiler-goes-stable-revolutionizing-performance-in-react-apps-5ebabda9b797?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ebabda9b797</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 00:58:01 GMT</pubDate>
            <atom:updated>2025-10-17T00:58:01.766Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript Events in 2025: preventDefault vs stopPropagation vs stopImmediatePropagation…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/mastering-javascript-events-in-2025-preventdefault-vs-stoppropagation-vs-stopimmediatepropagation-8e952f51c3fb?source=rss-715e55318b35------2"><img src="https://cdn-images-1.medium.com/max/1536/1*sV1qzG9eL6QU31SuC64Cbw.png" width="1536"></a></p><p class="medium-feed-snippet">How mastering preventDefault(), stopPropagation(), and stopImmediatePropagation() can save your 2025 React app from chaotic click events&#x2026;</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/mastering-javascript-events-in-2025-preventdefault-vs-stoppropagation-vs-stopimmediatepropagation-8e952f51c3fb?source=rss-715e55318b35------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/mastering-javascript-events-in-2025-preventdefault-vs-stoppropagation-vs-stopimmediatepropagation-8e952f51c3fb?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e952f51c3fb</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 01:20:46 GMT</pubDate>
            <atom:updated>2025-10-16T01:20:46.590Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[7 Frontend Performance Hacks I Wish I Knew Before My 2025 Code Review: Boost Your Web Vitals]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://javascript.plainenglish.io/7-frontend-performance-hacks-i-wish-i-knew-before-my-2025-code-review-boost-your-web-vitals-3a129423159c?source=rss-715e55318b35------2"><img src="https://cdn-images-1.medium.com/max/1536/1*3-MDM7-_zxo94nf87ME8FA.png" width="1536"></a></p><p class="medium-feed-snippet">Real-world fixes that cut load times in half, improved my Lighthouse score by 30 points, and saved me from a brutal code review.</p><p class="medium-feed-link"><a href="https://javascript.plainenglish.io/7-frontend-performance-hacks-i-wish-i-knew-before-my-2025-code-review-boost-your-web-vitals-3a129423159c?source=rss-715e55318b35------2">Continue reading on JavaScript in Plain English »</a></p></div>]]></description>
            <link>https://javascript.plainenglish.io/7-frontend-performance-hacks-i-wish-i-knew-before-my-2025-code-review-boost-your-web-vitals-3a129423159c?source=rss-715e55318b35------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a129423159c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Nilupul Perera]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 10:57:50 GMT</pubDate>
            <atom:updated>2025-10-05T11:35:12.507Z</atom:updated>
        </item>
    </channel>
</rss>