<?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"><channel><title><![CDATA[Reilly's Blog]]></title><description><![CDATA[Software craftsman ▫️ ♥ building & teaching ▫️ kick ass dad]]></description><link>https://blog.reilly.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 00:54:12 GMT</lastBuildDate><atom:link href="https://blog.reilly.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[perf overhead on context flattener?]]></title><description><![CDATA[Someone shared this image above. At first glance, I wasn’t sure about the perf implications — so let’s break it down from first principles :D Here’s the…]]></description><link>https://blog.reilly.dev/perf-overhead-on-context-flattener</link><guid isPermaLink="true">https://blog.reilly.dev/perf-overhead-on-context-flattener</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Thu, 14 Aug 2025 02:09:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1755129926566/1f06d0c2-a151-447e-8508-b6d14a18610d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755117937736/2038d693-d71b-4c76-9994-583247dfa78f.jpeg" alt class="image--center mx-auto" /></p>
<p>Someone shared this image above. At first glance, I wasn’t sure about the perf implications — so let’s break it down from first principles :D</p>
<h2 id="heading-lets-deconstruct-this-monster">Let’s deconstruct this monster</h2>
<p>Here’s the code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Function to flatten React Context Providers.</span>
<span class="hljs-keyword">const</span> flattenContextProviders = <span class="hljs-function">(<span class="hljs-params">providers</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> providers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, Provider</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span>&gt;</span>{acc({ children })}<span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
    );
  }, <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;&gt;</span>{children}<span class="hljs-tag">&lt;/&gt;</span></span>);
};

<span class="hljs-comment">// Array of Context Providers.</span>
<span class="hljs-keyword">const</span> contextProviders = [FirstContextProvider, SecondContextProvider,
ThirdContextProvider];

<span class="hljs-comment">// Flattened Context Provider.</span>
<span class="hljs-keyword">const</span> FlattenedContextProvider = flattenContextProviders(contextProviders);

<span class="hljs-comment">// ⚠️ Really bad idea for performance!</span>
<span class="hljs-comment">// It hides problem instead of solving it, and in really bad way.</span>
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">FlattenedContextProvider</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">FlattenedContextProvider</span>&gt;</span></span>
</code></pre>
<p>Off the top of my head I don’t know from intuition what flattenContextProviders becomes when called with the array so let’s construct it line by line:</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">// looks like this the first call</span>
<span class="hljs-keyword">const</span> flattenContextProviders = <span class="hljs-function">(<span class="hljs-params">[FirstContextProvider, SecondContextProvider,
ThirdContextProvider]</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> providers.reduce(<span class="hljs-function">(<span class="hljs-params">acc, Provider</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> (
      <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span>&gt;</span>{acc({ children })}<span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span>
    );
  }, <span class="hljs-function">(<span class="hljs-params">{ children }</span>) =&gt;</span> <span class="xml"><span class="hljs-tag">&lt;&gt;</span>{children}<span class="hljs-tag">&lt;/&gt;</span></span>);
};

 <span class="hljs-comment">/*
     Here's every run for reduce

     first run 
     acc = ({children}) =&gt; &lt;&gt;{children}&lt;/&gt;
     Provider = FirstContextProvider
     returns ({children}) =&gt; (
        &lt;FirstContextProvider&gt;
          {acc({ children })}}
        &lt;/FirstContextProvider&gt;

     )
     since our acc is ({children}) =&gt; &lt;&gt;{children}&lt;/&gt;
     which is a function that takes a parameter called children and returns 
     the children enclosed in jsx fragments

     and here in this line:
     {acc({ children })}}
     we're just calling the above function with {children} as the argument

     if that doesn't click we can work it out through substitution:
     ({children}) =&gt; (
        &lt;FirstContextProvider&gt;
          {
            // define a function, then CALL it immediately with { children }
            (({ children }) =&gt; &lt;&gt;{children}&lt;/&gt;)({ children })
            // which becomes &lt;&gt;{children}&lt;/&gt;
           }
        &lt;/FirstContextProvider&gt;
     )

     all in the first pass we're returning
     ({children}) =&gt; (
        &lt;FirstContextProvider&gt;
          &lt;&gt;{children}&lt;/&gt;
        &lt;/FirstContextProvider&gt;
     )


    */</span>

     <span class="hljs-comment">/*
     second run
     acc = the return from the first pass:
        ({children}) =&gt; (
            &lt;FirstContextProvider&gt;
              &lt;&gt;{children}&lt;/&gt;
            &lt;/FirstContextProvider&gt;
         )
     Provider = SecondContextProvider

     returns ({children}) =&gt; (
        &lt;SecondContextProvider&gt;
          {acc({ children })}}
        &lt;/SecondContextProvider&gt;
     )

    remember accumulator is now an anonymous function wrapping FirstContextProvider

    so the above becomes

    returns ({children}) =&gt; (
        &lt;SecondContextProvider&gt;
          &lt;FirstContextProvider&gt;
            {children}
          &lt;/FirstContextProvider&gt;
        &lt;/SecondContextProvider&gt;
     )    

    I think at this point you see the pattern. Once you get past that weird IIFE it's all good :D

    so at the very end flattenedContext becomes this:

     ({children}) =&gt; (
       &lt;ThirdContextProvider&gt;
        &lt;SecondContextProvider&gt;
          &lt;FirstContextProvider&gt;
            {children}
          &lt;/FirstContextProvider&gt;
        &lt;/SecondContextProvider&gt;
      &lt;/ThirdContextProvider&gt;
     )    
    */</span>
</code></pre>
<h2 id="heading-ia"> </h2>
<p>Perf implications</p>
<p>quick recap —<br />we have this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> FlattenedContextProvider = <span class="hljs-function">(<span class="hljs-params">{children}</span>) =&gt;</span> (
       <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ThirdContextProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">SecondContextProvider</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">FirstContextProvider</span>&gt;</span>
            {children}
          <span class="hljs-tag">&lt;/<span class="hljs-name">FirstContextProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">SecondContextProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ThirdContextProvider</span>&gt;</span></span>
     )
</code></pre>
<p>which is an arrow function / function bound to a constant variable that returns a bunch of wrappers around children i.e. a <strong>react component</strong>.  </p>
<p>Same rules of react apply here: don’t define components inside other components. So as long as you don’t do that there are no performance implications compared to directly wrapping your app around the same providers in the exact same location.</p>
<h2 id="heading-other-implications">Other implications</h2>
<p>What about in debugging? Does this wrapper hide the nested contexts under the name FlattenedContextProvider?</p>
<h3 id="heading-wo-wrapper">w/o wrapper</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755128924338/45e20198-d00c-43d1-9c1e-31d9bb666579.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-and-with-it">and with it</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1755128968781/4a14a3f0-f050-424f-83c6-8fa699757a7c.png" alt class="image--center mx-auto" /></p>
<p>all it did was add an additional fiber “Anonymous” which we could rename via:<br />`FlattenedContextProvider.displayName = "FlattenedContextProvider";`</p>
<h2 id="heading-tldr">tldr;</h2>
<p>This sort of structure — compared to manually nesting the same providers — is purely a matter of taste. It has no observability drawbacks and, most importantly, no performance overhead. :D</p>
]]></content:encoded></item><item><title><![CDATA[Diving into SSR with bun & react 19]]></title><description><![CDATA[Hello it’s me from the future! I originally was going to go over file based routing but pivoted to going over important SSR concepts with React / how Bun…]]></description><link>https://blog.reilly.dev/diving-into-ssr-with-bun-and-react-19</link><guid isPermaLink="true">https://blog.reilly.dev/diving-into-ssr-with-bun-and-react-19</guid><category><![CDATA[React]]></category><category><![CDATA[Bun]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Wed, 02 Apr 2025 03:56:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/2n-NlDEAhtk/upload/b1a8d9d0abbfdff9392434e24635c018.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-intro">Intro</h2>
<p>Hello it’s me from the future! I originally was going to go over file based routing but pivoted to going over important SSR concepts with React / how Bun makes it easy. It’s full of struggles with hydration (mismatches), React entry points, and how Bun handles jsx/ts.</p>
<p>At the end you’ll have a better grasp on how React handles rendering on the server via a stream, hydrating on the client, and you’ll have a working project to show!</p>
<p>Hope you learn something new!</p>
<h2 id="heading-start">Start</h2>
<p>Begin with `bun init` to start a new project. Bun comes with TS &amp; JSX baked in (literally has a transpiler step in the code that converts ts / JSX to js - [lexer is here if interested](<a target="_blank" href="https://github.com/oven-sh/bun/blob/main/src/js_lexer.zig">https://github.com/oven-sh/bun/blob/main/src/js_lexer.zig</a>) which means we don’t have to worry about that.</p>
<p>Ok the first step with ANY problem is that we need to understand the problem and have a starting mental model of HOW the problem works.</p>
<p>When you use an app that uses routing in general when you navigate to “/some/route” the files (i.e. html, css, js) mapped to those routes are sent to the browser. But something has to send it?</p>
<p>Have the intuition for what can send it?</p>
<p>-</p>
<p>-</p>
<p>an http server!</p>
<h2 id="heading-http-server">HTTP server</h2>
<p>Bun has it’s own syntax for an http server [here](<a target="_blank" href="https://bun.sh/docs/api/http">https://bun.sh/docs/api/http</a>)</p>
<p>With this:</p>
<pre><code class="lang-typescript">Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Hello World'</span>),
    <span class="hljs-string">'/bye'</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Goodbye!'</span>),
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);
</code></pre>
<p>run <code>bun run index.ts</code></p>
<p>Got an error?</p>
<div data-node-type="callout">
<div data-node-type="callout-emoji">⚠</div>
<div data-node-type="callout-text">Expected fetch() to be a function</div>
</div>

<p>That just means you need the latest version of bun w <code>bun upgrade</code></p>
<p>If you see the console log you’re golden!</p>
<p>Let’s visit <code>localhost:3000/</code> you should see “hello world” in the browser!</p>
<p>If you check the Network tab it’ll also show a content type of <code>text/plain;charset=utf-8</code></p>
<h2 id="heading-add-react">Add React</h2>
<p><code>bun i react &amp;&amp; bun i -D @types/react</code></p>
<p>Now I sorta want to just return some jsx for each separate route. Like:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> Response(Hello),
    <span class="hljs-string">'/bye'</span>: <span class="hljs-function">() =&gt;</span> <span class="hljs-keyword">new</span> Response(Bye),
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, _] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> &lt;h1&gt;Hello, {name}!&lt;/h1&gt;;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<blockquote>
<p>note since we’re using JSX we HAVE to update the file to end in .tsx/.jsx</p>
</blockquote>
<p>But there’s a fundamental flaw in this idea.</p>
<p>Anything that crosses network boundaries has to be serialized - fancy word for a string.</p>
<p>So how do we turn Hello and Bye to strings?</p>
<p>if we invoke via <code>&lt;Hello /&gt;</code> That's not getting the underlying string bc that goes through React and instantiates a fiber and all that. What we're really wanting / needing is the underlying HTML that represents this code.</p>
<p>React offers 2 api’s to get the underlying HTML and it’s the basis of all SSR apps. <code>renderToString</code> which transforms your react tree into html and <code>renderToReadableStream</code> which does the same but streams it to better scale / gets you a faster Time To First Byte TTFB.</p>
<p>We’ll do the stream approach but both work :D</p>
<p>Make sure you’ve got react-dom which is where the above api comes from</p>
<p><code>bun i react-dom</code></p>
<h2 id="heading-streams-in-bun">Streams in bun</h2>
<p>Streams are as simple as passing it to the Response as the first argument:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { renderToReadableStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;

Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-keyword">async</span> () =&gt;
      <span class="hljs-keyword">new</span> Response(<span class="hljs-keyword">await</span> renderToReadableStream(&lt;Hello /&gt;)),
    <span class="hljs-string">'/bye'</span>: <span class="hljs-keyword">async</span> () =&gt;
      <span class="hljs-keyword">new</span> Response(<span class="hljs-keyword">await</span> renderToReadableStream(&lt;Bye /&gt;)),
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, _] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> &lt;h1&gt;Hello, {name}!&lt;/h1&gt;;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<p>When you run the server and visit the above routes it’s working!</p>
<h2 id="heading-sprinkle-some-interactivity">Sprinkle some 🪄 interactivity</h2>
<p>Let’s make the Hello component more interactive by utilizing the dispatch and returning some stuff to make it interactive to the user:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> (
    &lt;div&gt;
      &lt;h1&gt;Hello, {name}!&lt;/h1&gt;
      &lt;input
        <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
        value={name}
        onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)}
      /&gt;
      &lt;p&gt;Type your name above!&lt;/p&gt;
    &lt;/div&gt;
  )
}
</code></pre>
<p>Sweet! Now let’s restart the server and run it and visit localhost:3000/</p>
<blockquote>
<p>tired of restarting? <code>bun run --hot index.tsx</code></p>
</blockquote>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743444277228/7bcb7b1e-ff12-480d-bbd5-210540bc09c9.png" alt class="image--center mx-auto" /></p>
<p>It’s not updating??</p>
<p>Let’s look at the payload sent from the server:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, 
    <span class="hljs-comment">&lt;!-- --&gt;</span>
    World
    <span class="hljs-comment">&lt;!-- --&gt;</span>
    !<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"World"</span>/&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Type your name above!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>So when we’re typing it’s updating the value but that World is hardcoded. We need the corresponding JS that updates the string in the html. This is called <em>hydration</em></p>
<p>We’ll need to update the server to send the needed JS so that when the user DOES type something the JS runs, updating the state, and updating what we see visually.</p>
<p>But before that we’ll need to explain some really important React concepts bc the above code needs to change a bit:</p>
<h3 id="heading-quick-aside-important-react-ideas-before-we-go-further">Quick aside: Important React ideas before we go further</h3>
<p>React needs an entry point in the HTML. It’s a major part of HOW react works under the hood - specifically it’s diffing algorithm.</p>
<p>Which means we’ll need to give react an entry point - canonically this is some html <code>id</code> we target.</p>
<p>Then we need to “attach” react to that targeted entry point via a <code>hydrateRoot</code> call</p>
<p>to implement we’ll need the html created from <code>renderToReadableStream</code> then a js file containing a <code>hydrateRoot</code> call to attach react.</p>
<p>Back to the code:</p>
<h2 id="heading-providing-an-entry-point-for-react">Providing an entry point for React</h2>
<p>From the docs for one of the arguments to <code>renderToReadableStream</code></p>
<blockquote>
<ul>
<li><strong>optional</strong> <code>bootstrapScripts</code>: An array of string URLs for the <code>&lt;script&gt;</code> tags to emit on the page. Use this to include the <code>&lt;script&gt;</code> that calls <a target="_blank" href="https://react.dev/reference/react-dom/client/hydrateRoot"><code>hydrateRoot</code>.</a> <a target="_blank" href="https://react.dev/reference/react-dom/client/hydrateRoot">Omit it if</a> you don’t want to run React on the client at all.</li>
</ul>
</blockquote>
<p>So we’ll need to prep a js file and attach it as the arg.</p>
<p>The gist of what the script needs to do is -</p>
<ol>
<li><p>target some html node</p>
</li>
<li><p>pass that node into <code>hydrateRoot</code> as well as the react node we want to render (Hello/ Bye) - we’ll need to import</p>
</li>
</ol>
<p>[here’s how it’s done in the docs] (<a target="_blank" href="https://react.dev/reference/react-dom/client/hydrateRoot#:~:text=import%20%7B%20hydrateRoot,reactNode\)%3B">https://react.dev/reference/react-dom/client/hydrateRoot#:~:text=import%20%7B%20hydrateRoot,reactNode)%3B</a>)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { hydrateRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>;
<span class="hljs-keyword">import</span> { Hello } <span class="hljs-keyword">from</span> <span class="hljs-string">'.'</span>
<span class="hljs-keyword">const</span> domNode = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>);
<span class="hljs-keyword">if</span>(domNode)hydrateRoot(domNode, <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Hello</span> /&gt;</span></span>);
</code></pre>
<p>Then we’ll need to include this file (main.js) in the arguments passed like so:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">new</span> Response(
        <span class="hljs-keyword">await</span> renderToReadableStream(
          <span class="hljs-string">`
      &lt;html&gt;
        &lt;head&gt;
          &lt;title&gt;My Bun App&lt;/title&gt;
          &lt;/head&gt;
        &lt;body&gt;
        &lt;div id="root"&gt;
        <span class="hljs-subst">${(&lt;Hello /&gt;)}</span>
        &lt;/div&gt;
        &lt;/body&gt;
      &lt;/html&gt;`</span>,
          {
            bootstrapScripts: [<span class="hljs-string">'/main.js'</span>],
          }
        )
      ),
</code></pre>
<p>This doesn’t work though!</p>
<p>To understand let’s go look at what <code>renderToReadableStream</code> [here](<a target="_blank" href="https://react.dev/reference/react-dom/server/renderToReadableStream#parameters">https://react.dev/reference/react-dom/server/renderToReadableStream#parameters</a>)</p>
<p>The first parameter is:</p>
<blockquote>
<p>A React node you want to render to HTML. For example, a JSX element like <code>&lt;App /&gt;</code>. It is expected to represent the entire document, so the <code>App</code> component should render the <code>&lt;html&gt;</code> tag.</p>
</blockquote>
<p>So we’ll need to update and have it render html instead of a string.</p>
<p>Then for the second object it says:</p>
<blockquote>
<ul>
<li><strong>optional</strong> <code>bootstrapScripts</code>: An array of string URLs for the <code>&lt;script&gt;</code> tags to emit on the page. Use this to include the <code>&lt;script&gt;</code> that calls <a target="_blank" href="https://react.dev/reference/react-dom/client/hydrateRoot"><code>hydrateRoot</code>.</a> <a target="_blank" href="https://react.dev/reference/react-dom/client/hydrateRoot">Omit it if</a> you don’t want to run React on the client at all.</li>
</ul>
</blockquote>
<p>Further down it says:</p>
<p><code>React will inject the doctype and your bootstrap &lt;script&gt; tags into the resulting HTML stream:</code></p>
<p>Let’s make the first change and take a look at the response from the server.</p>
<p>Here’s the change:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { renderToReadableStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;

Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
        <span class="hljs-keyword">await</span> renderToReadableStream(&lt;Hello /&gt;, {
          bootstrapScripts: [<span class="hljs-string">'/main.js'</span>],
        })
      );
    },

    <span class="hljs-string">'/bye'</span>: <span class="hljs-keyword">async</span> () =&gt; <span class="hljs-keyword">new</span> Response(<span class="hljs-keyword">await</span> renderToReadableStream(&lt;Bye /&gt;), {}),
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> (
    &lt;html&gt;
      &lt;head&gt;
        &lt;title&gt;My Bun App&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
        &lt;div id=<span class="hljs-string">"root"</span>&gt;
          &lt;h1&gt;Hello, {name}!&lt;/h1&gt;
          &lt;input
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            value={name}
            onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)}
          /&gt;
          &lt;p&gt;Type your name above!&lt;/p&gt;
        &lt;/div&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<p>We get a 404 for main.js!</p>
<p>The request that comes in for /main.js looks something like <code>localhost:3000/main.js</code> since there’s not a route covered / we’re not handling a fallback it automatically returns a 404.</p>
<p>Also remember earlier when we talked about renderToString (which is blocking in that the response isn’t send until the entire react tree is rendered and turned into a string?) and it’s alt the renderToReadableStream? There’s the two same ideas for reading a file and returning it’s contents for http servers. Thankfully Bun makes it REALLY easy to stream a file. [docs here](<a target="_blank" href="https://bun.sh/docs/api/http#streaming-files">https://bun.sh/docs/api/http#streaming-files</a>)</p>
<p>Their example is</p>
<pre><code class="lang-typescript">Bun.serve({
  fetch(req) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(Bun.file(<span class="hljs-string">"./hello.txt"</span>));
  },
});
</code></pre>
<p>That’s dead simple. Under the hood Bun is auto streaming it so no matter how big the file is it will always respond quickly!</p>
<p>Let’s put these 2 ideas - handling the request for /main.js and serving the contents of a file as a stream together:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { renderToReadableStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;

Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
        <span class="hljs-keyword">await</span> renderToReadableStream(&lt;Hello /&gt;, {
          bootstrapScripts: [<span class="hljs-string">'/main.js'</span>],
        })
      );
    },

    <span class="hljs-string">'/bye'</span>: <span class="hljs-keyword">async</span> () =&gt; <span class="hljs-keyword">new</span> Response(<span class="hljs-keyword">await</span> renderToReadableStream(&lt;Bye /&gt;), {}),
  },
  fetch(req) {
    <span class="hljs-keyword">if</span> (req.url === <span class="hljs-string">'main.js'</span>) <span class="hljs-keyword">new</span> Response(Bun.file(<span class="hljs-string">'main.js'</span>));
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Not Found'</span>, { status: <span class="hljs-number">404</span> });
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> (
    &lt;html&gt;
      &lt;head&gt;
        &lt;title&gt;My Bun App&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
        &lt;div id=<span class="hljs-string">"root"</span>&gt;
          &lt;h1&gt;Hello, {name}!&lt;/h1&gt;
          &lt;input
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            value={name}
            onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)}
          /&gt;
          &lt;p&gt;Type your name above!&lt;/p&gt;
        &lt;/div&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<p>I also added a fallback so now it manually returns a 404. Note that I’ve used the fetch. This is straight from the docs. Read more <a target="_blank" href="https://bun.sh/docs/api/http#:~:text=//%20\(optional\)%20fallback%20for%20unmatched%20routes%3A%0A%20%20//%20Required%20if%20Bun%27s%20version%20%3C%201.2.3%0A%20%20fetch\(req\)%20%7B%0A%20%20%20%20return%20new%20Response\(%22Not%20Found%22%2C%20%7B%20status%3A%20404%20%7D\)%3B%0A%20%20%7D%2C">here</a></p>
<p>Notice my mistake? I’m checking if the <code>url === 'main.js'</code> which it never will. The req.url will be something like <code>http://localhost:3000/main.js</code></p>
<p>It’s the pathname we want!</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">async</span> fetch(req) {
    <span class="hljs-keyword">const</span> path = <span class="hljs-keyword">new</span> URL(req.url).pathname;
    <span class="hljs-keyword">if</span> (path === <span class="hljs-string">'/main.js'</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(Bun.file(<span class="hljs-string">'main.js'</span>));
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Not Found'</span>, { status: <span class="hljs-number">404</span> });
  }
</code></pre>
<p>Rerun the server (if applicable) and check the network tab</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743454854641/2fe24355-3847-4a38-bd17-c1f2871b1805.png" alt class="image--center mx-auto" /></p>
<p>no 404! But when we type it doesn’t update. In the logs:</p>
<p><code>Uncaught SyntaxError: Cannot use import statement outside a module (at main.js:1:1)</code></p>
<p>Ah ok. Well the browser DOES understand ESM. The problem can be found when we inspect the html returned in the network tab:</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preload"</span> <span class="hljs-attr">as</span>=<span class="hljs-string">"script"</span> <span class="hljs-attr">fetchPriority</span>=<span class="hljs-string">"low"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"/main.js"</span>/&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>My Bun App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, 
            <span class="hljs-comment">&lt;!-- --&gt;</span>
            World
            <span class="hljs-comment">&lt;!-- --&gt;</span>
            !<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"World"</span>/&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Type your name above!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"/main.js"</span> <span class="hljs-attr">async</span>=<span class="hljs-string">""</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In the docs you can use:<br /><strong>optional</strong> <code>bootstrapModules</code>: Like <code>bootstrapScripts</code>, but emits <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules"><code>&lt;script type="module"&gt;</code></a> instead.</p>
<p>Perfect! Let’s use that instead of the <code>bootstrapScripts</code></p>
<p>Ok! Here’s the updated code:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { renderToReadableStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;

Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
        <span class="hljs-keyword">await</span> renderToReadableStream(&lt;Hello /&gt;, {
          bootstrapModules: [<span class="hljs-string">'/main.js'</span>],
        })
      );
    },

    <span class="hljs-string">'/bye'</span>: <span class="hljs-keyword">async</span> () =&gt; <span class="hljs-keyword">new</span> Response(<span class="hljs-keyword">await</span> renderToReadableStream(&lt;Bye /&gt;), {}),
  },
  <span class="hljs-keyword">async</span> fetch(req) {
    <span class="hljs-keyword">const</span> path = <span class="hljs-keyword">new</span> URL(req.url).pathname;
    <span class="hljs-keyword">if</span> (path === <span class="hljs-string">'/main.js'</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(Bun.file(<span class="hljs-string">'main.js'</span>));
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Not Found'</span>, { status: <span class="hljs-number">404</span> });
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> (
    &lt;html&gt;
      &lt;head&gt;
        &lt;title&gt;My Bun App&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
        &lt;div id=<span class="hljs-string">"root"</span>&gt;
          &lt;h1&gt;Hello, {name}!&lt;/h1&gt;
          &lt;input
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            value={name}
            onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)}
          /&gt;
          &lt;p&gt;Type your name above!&lt;/p&gt;
        &lt;/div&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<p>Ok another error! We’ve almost got this!</p>
<p><code>Uncaught SyntaxError: Unexpected token '&lt;' (at main.js:6:24)</code></p>
<p>Ah we’re using JSX in the main.js file (not really js) :/ so we’ll need to transpile it with Bun. We can do that with <code>Bun.build</code> we’ve got a couple options - we can do it for every request or do it once when the server starts/restarts… The second is a better idea.</p>
<p>Also I’m going to update main.js to be main.tsx since it’s going to be transpiled/compiled/whatever you wanna call it.</p>
<p>We want to compile that file when the server starts and output it somewhere. Then when requests come in for that file we can just serve the js file.</p>
<p>Ok. All in you get this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> { renderToReadableStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;

Bun.build({
  entrypoints: [<span class="hljs-string">'./main.tsx'</span>],
  outdir: <span class="hljs-string">'dist'</span>,
});

Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(
        <span class="hljs-keyword">await</span> renderToReadableStream(&lt;Hello /&gt;, {
          bootstrapModules: [<span class="hljs-string">'/dist/main.js'</span>],
        })
      );
    },

    <span class="hljs-string">'/bye'</span>: <span class="hljs-keyword">async</span> () =&gt; <span class="hljs-keyword">new</span> Response(<span class="hljs-keyword">await</span> renderToReadableStream(&lt;Bye /&gt;), {}),
  },
  <span class="hljs-keyword">async</span> fetch(req) {
    <span class="hljs-keyword">const</span> path = <span class="hljs-keyword">new</span> URL(req.url).pathname;
    <span class="hljs-keyword">if</span> (path === <span class="hljs-string">'/main.js'</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(Bun.file(<span class="hljs-string">'main.js'</span>));
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Not Found'</span>, { status: <span class="hljs-number">404</span> });
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> (
    &lt;html&gt;
      &lt;head&gt;
        &lt;title&gt;My Bun App&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
        &lt;div id=<span class="hljs-string">"root"</span>&gt;
          &lt;h1&gt;Hello, {name}!&lt;/h1&gt;
          &lt;input
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            value={name}
            onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)}
          /&gt;
          &lt;p&gt;Type your name above!&lt;/p&gt;
        &lt;/div&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<p>Another error! <code>Uncaught ReferenceError: Bun is not defined</code> because we’re sending <code>main.js</code> to the client to be executed to enable hydration, our import for hello, <code>import { Hello } from '.'</code>, is sending all of the code in that file!</p>
<p>To resolve this, move the components into a separate file. Which means we need to:</p>
<ol>
<li><p>change the import in main.tsx</p>
</li>
<li><p>in <code>index.tsx</code> import the components in the location you chose, <code>app.tsx</code> for me.</p>
</li>
</ol>
<p>Ok. After this I’ve run into ANOTHER error. Hydration mismatch causing the cpu to spike to 100%.</p>
<h3 id="heading-hydrateroot-wtf-even-is-hydration">hydrateRoot / wtf even is hydration</h3>
<p>In trying to debug this cpu issue I found some gaps in my understanding.</p>
<p>To start the definition is really confusing imo:</p>
<blockquote>
<p><code>hydrateRoot</code> lets you display React components inside a browser DOM node whose HTML content was previously generated by <a target="_blank" href="https://react.dev/reference/react-dom/server"><code>react-dom/server</code></a></p>
</blockquote>
<p>Further down in the docs on hydrateRoot there’s a bit more helpful info:</p>
<blockquote>
<p>Call hydrateRoot to “attach” React to existing HTML that was already rendered by React in a server environment… hydrateRoot() expects the rendered content to be identical with the server-rendered content.</p>
</blockquote>
<p>that explains everything we need to know: when you render html from react, the rendered content has to be identical to the server-content and since hydrate root expects an entry - it has to be THE entry, i.e. the html tag aka document.  </p>
<h2 id="heading-lets-put-it-all-together-now">Let’s put it all together now!</h2>
<p>Ok, be sure to move the components to their own files. Then update <code>main.tsx</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { hydrateRoot } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/client'</span>;
<span class="hljs-keyword">import</span> { Hello } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app'</span>;

hydrateRoot(<span class="hljs-built_in">document</span>, &lt;Hello /&gt;);
</code></pre>
<p><code>index.tsx</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { renderToReadableStream } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-dom/server'</span>;
<span class="hljs-keyword">import</span> { Bye, Hello } <span class="hljs-keyword">from</span> <span class="hljs-string">'./app'</span>;

<span class="hljs-keyword">await</span> Bun.build({
  entrypoints: [<span class="hljs-string">'./main.tsx'</span>],
  outdir: <span class="hljs-string">'dist'</span>,
});

Bun.serve({
  port: <span class="hljs-number">3000</span>,
  routes: {
    <span class="hljs-string">'/'</span>: <span class="hljs-keyword">async</span> () =&gt; {
      <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> stream = <span class="hljs-keyword">await</span> renderToReadableStream(&lt;Hello /&gt;, {
          bootstrapModules: [<span class="hljs-string">'main.js'</span>],
        });
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(stream, {
          headers: {
            <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'text/html'</span>,
          },
          status: <span class="hljs-number">200</span>,
        });
      } <span class="hljs-keyword">catch</span> (error) {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error rendering Hello component:'</span>, error);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Internal Server Error'</span>, { status: <span class="hljs-number">500</span> });
      }
    },
    <span class="hljs-comment">// '/bye': async () =&gt; new Response(await renderToReadableStream(&lt;Bye /&gt;), {}),</span>
  },
  <span class="hljs-keyword">async</span> fetch(req) {
    <span class="hljs-keyword">const</span> path = <span class="hljs-keyword">new</span> URL(req.url).pathname;
    <span class="hljs-keyword">if</span> (path === <span class="hljs-string">'/main.js'</span>)
      <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(Bun.file(<span class="hljs-string">'dist/main.js'</span>), {
        headers: {
          <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/javascript'</span>,
        },
      });
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Response(<span class="hljs-string">'Not Found'</span>, { status: <span class="hljs-number">404</span> });
  },
});

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Server running on http://localhost:3000'</span>);
</code></pre>
<p><code>app.tsx</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [name, setName] = React.useState(<span class="hljs-string">'World'</span>);
  <span class="hljs-keyword">return</span> (
    &lt;html&gt;
      &lt;head&gt;
        &lt;title&gt;My Bun App&lt;/title&gt;
      &lt;/head&gt;
      &lt;body&gt;
        &lt;div id=<span class="hljs-string">"root"</span>&gt;
          &lt;h1&gt;Hello, {name}!&lt;/h1&gt;
          &lt;input
            <span class="hljs-keyword">type</span>=<span class="hljs-string">"text"</span>
            value={name}
            onChange={<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> setName(e.target.value)}
          /&gt;
          &lt;p&gt;Type your name above!&lt;/p&gt;
        &lt;/div&gt;
      &lt;/body&gt;
    &lt;/html&gt;
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Bye</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> &lt;h1&gt;Goodbye!&lt;/h1&gt;;
}
</code></pre>
<p>And what it looks like visually:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1743565127001/d651468b-ce6d-44dd-80b0-84f5695bd1a8.png" alt class="image--center mx-auto" /></p>
]]></content:encoded></item><item><title><![CDATA[overview of cloudflare workers - part 1]]></title><description><![CDATA[Serverless is EVERYWHERE and for good reason: nearly infinite scalability, physically closer to users, and pay-for-what-you-use pricing. But not without…]]></description><link>https://blog.reilly.dev/overview-of-cloudflare-workers-part-1</link><guid isPermaLink="true">https://blog.reilly.dev/overview-of-cloudflare-workers-part-1</guid><category><![CDATA[cloudflare]]></category><category><![CDATA[Cloud]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Sat, 15 Feb 2025 20:51:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739651960242/e0105401-853a-4e6d-b594-7a727d61a505.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-history">history?</h2>
<p>Serverless is EVERYWHERE and for good reason: nearly infinite scalability, physically closer to users, and pay-for-what-you-use pricing. But not without tradeoffs — vendor lock-in, (potentially) higher costs, and the infamous cold-starts.</p>
<h2 id="heading-cfs-solution">cf’s solution</h2>
<p>In response to the issues of cold starts, CF introduced Workers. Workers are <strong>v8 isolates</strong> running throughout their 300+ data centers. Users provide js code, and it runs as soon as the isolate is provisioned, eliminating the main annoying characteristic of serverless — cold starts. Contrasted to typical serverless functions which need to spin up an entire vm/container.</p>
<h2 id="heading-wait-v8-iso-whats">wait — v8 iso-whats?</h2>
<p>v8 — yeah that [one](<a target="_blank" href="https://v8.dev/">https://v8.dev/</a>) is an individual in-process js/wasm sandbox running in a single OS process. V8 isolates <em>logically</em> isolate their JavaScript heaps (variables, objects, etc.), meaning <strong>one isolate cannot directly access another’s memory</strong>. However, they run in the <strong>same OS process</strong>, sharing the <em>same virtual memory space</em>. Most importantly, they spin up fast (Cloudflare reported an avg speed of [5ms](<a target="_blank" href="https://blog.cloudflare.com/cloud-computing-without-containers/#:~:text=Because%20Workers%20don%E2%80%99t%20have%20to%20start%20a%20process%2C%20Isolates%20start%20in%205%20milliseconds%2C%20a%20duration%20which%20is%20imperceptible">https://blog.cloudflare.com/cloud-computing-without-containers/#:~:text=Because%20Workers%20don%E2%80%99t%20have%20to%20start%20a%20process%2C%20Isolates%20start%20in%205%20milliseconds%2C%20a%20duration%20which%20is%20imperceptible</a>)</p>
<h2 id="heading-whats-the-catch">what’s the catch?</h2>
<p>Ah fair. You should know by now nothing is without tradeoffs. While v8 isolates reduces cold starts to a nearly invisible 5ms, there are still intrinsic difficulties in scaling. With isolates sharing the total compute, what happens when one takes forever and blocks the main thread (this is js after all)? Or how do you manage the total memory so that you don’t get a OOM and linux kernel decides to kill any process it deems less valuable? Cloudflare’s employed some really cool engineering to address this plus extra security concerns. Stay tuned for part 2!</p>
<h2 id="heading-ia"> </h2>
<p>sauces</p>
<ul>
<li><p><a target="_blank" href="https://www.infoq.com/presentations/cloudflare-v8/">https://www.infoq.com/presentations/cloudflare-v8/</a></p>
</li>
<li><p><a target="_blank" href="https://developers.cloudflare.com/workers/reference/security-model/">https://developers.cloudflare.com/workers/reference/security-model/</a></p>
</li>
<li><p><a target="_blank" href="https://developers.cloudflare.com/workers/reference/how-workers-works/">https://developers.cloudflare.com/workers/reference/how-workers-works/</a></p>
</li>
</ul>
<p>.</p>
]]></content:encoded></item><item><title><![CDATA[Send iMessage to a loved one from the terminal!]]></title><description><![CDATA[Powered by bash and AppleScript!]]></description><link>https://blog.reilly.dev/send-imessage-to-a-loved-one-from-the-terminal</link><guid isPermaLink="true">https://blog.reilly.dev/send-imessage-to-a-loved-one-from-the-terminal</guid><category><![CDATA[Bash]]></category><category><![CDATA[automation]]></category><category><![CDATA[applescript]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Tue, 12 Mar 2024 00:56:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/2PODhmrvLik/upload/25758896dfd9e985037ae7d872f001bb.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>mkdir ~/bin</code></p>
<p>Now let's go to it:</p>
<p><code>cd ~/bin</code> and create a file <code>text.sh</code></p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

MESSAGE=<span class="hljs-variable">$1</span>
<span class="hljs-comment"># Replace with their number (be sure to include the +1)</span>
PHONE_NUMBER=+11234567

<span class="hljs-keyword">if</span> [ <span class="hljs-string">"<span class="hljs-variable">$#</span>"</span> -ne 1 ]; <span class="hljs-keyword">then</span>
     <span class="hljs-built_in">echo</span> <span class="hljs-string">"Usage: <span class="hljs-variable">$0</span> MESSAGE"</span>
     <span class="hljs-built_in">exit</span> 1
<span class="hljs-keyword">fi</span>

osascript -e <span class="hljs-string">"tell application \"Messages\" to send \"<span class="hljs-variable">$MESSAGE</span>\" to buddy \"    <span class="hljs-variable">$PHONE_NUMBER</span>\""</span>
</code></pre>
<p>Now we need to make the file executable:<br /><code>chmod +x text.sh</code></p>
<p>Now we can use it!</p>
<p><code>./text.sh "I LOVE YOU"</code></p>
<h3 id="heading-alias">Alias</h3>
<p>To alias it so that you could say something like <code>rach "I LOVE YOU"</code></p>
<p>Add to your <code>.zshrc</code> or <code>.bashrc</code> the following:</p>
<pre><code class="lang-bash"><span class="hljs-comment"># local bin</span>
<span class="hljs-built_in">export</span> PATH=<span class="hljs-string">"<span class="hljs-variable">$HOME</span>/bin:<span class="hljs-variable">$PATH</span>"</span>
<span class="hljs-built_in">alias</span> rach=<span class="hljs-string">'text.sh'</span>
</code></pre>
<p>Now we can say <code>rach "I LOVE YOU"</code> and it sends!</p>
]]></content:encoded></item><item><title><![CDATA[Building Scalable WebSocket APIs with Socket.IO Syntax]]></title><description><![CDATA[Sockets can only transmit binary (text.) Imagine we have this data Here's the problem: we want to send this data to the ui but we have hundreds of…]]></description><link>https://blog.reilly.dev/building-scalable-websocket-apis-with-socketio-syntax</link><guid isPermaLink="true">https://blog.reilly.dev/building-scalable-websocket-apis-with-socketio-syntax</guid><category><![CDATA[websockets]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Wed, 28 Feb 2024 01:56:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1709085309801/a4eebd76-db76-49ca-8137-5e1ddeb78660.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sockets can only transmit binary (text.)</p>
<p>Imagine we have this data</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> message = {id: <span class="hljs-string">'123'</span>, name: <span class="hljs-string">'Reilly'</span>, message: <span class="hljs-string">'Hey'</span>}
</code></pre>
<p>Here's the problem: we want to send this data to the ui but we have hundreds of useEffects spread throughout the codebase. How can we make sure that this message is processed in the right part of the codebase and not somewhere else?</p>
<p>The best solution I've seen is to use a unique identifier - like a title.</p>
<p>This is what Socket.IO does.</p>
<p>Here's how we could implement their API from scratch:</p>
<h3 id="heading-the-client">The client</h3>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ws</span>(<span class="hljs-params">url: <span class="hljs-built_in">string</span></span>) </span>{
  <span class="hljs-keyword">const</span> socket = <span class="hljs-keyword">new</span> WebSocket(url);

  <span class="hljs-comment">// This looks scary</span>
  <span class="hljs-comment">// It's just a way to manage subscriptions</span>
  <span class="hljs-comment">// The key is the thing we are subbing to </span>
  <span class="hljs-comment">// the value is an array of functions to call when we get a message</span>
  <span class="hljs-keyword">const</span> subscriptions: { [key: <span class="hljs-built_in">string</span>]: (<span class="hljs-function">(<span class="hljs-params">content: <span class="hljs-built_in">any</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>)[] } = {};

  <span class="hljs-comment">// Connection opened</span>
  socket.addEventListener(<span class="hljs-string">'open'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    socket.send(<span class="hljs-string">'Hello Server!'</span>);
  });

  <span class="hljs-comment">// Listen for messages</span>
  socket.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
    <span class="hljs-keyword">try</span> {
      <span class="hljs-keyword">const</span> message = <span class="hljs-built_in">JSON</span>.parse(event.data);
      <span class="hljs-keyword">if</span> (!message.type || !message.content) <span class="hljs-keyword">return</span>;
      <span class="hljs-keyword">const</span> { <span class="hljs-keyword">type</span>, content } = message;

      <span class="hljs-keyword">if</span> (!subscriptions[message.type]) <span class="hljs-keyword">return</span>;

      <span class="hljs-keyword">if</span> (subscriptions[<span class="hljs-keyword">type</span>]) {
        subscriptions[<span class="hljs-keyword">type</span>].forEach(<span class="hljs-function">(<span class="hljs-params">fn</span>) =&gt;</span> fn(content));
      }
    } <span class="hljs-keyword">catch</span> (error) {
      <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error parsing message'</span>, error);
    }
  });

  <span class="hljs-keyword">return</span> {
    on: (<span class="hljs-keyword">type</span>: <span class="hljs-built_in">string</span>, fn: <span class="hljs-function">(<span class="hljs-params">content: <span class="hljs-built_in">any</span></span>) =&gt;</span> <span class="hljs-built_in">void</span>) =&gt; {
      <span class="hljs-keyword">if</span> (!subscriptions[<span class="hljs-keyword">type</span>]) {
        subscriptions[<span class="hljs-keyword">type</span>] = [];
      }
      subscriptions[<span class="hljs-keyword">type</span>].push(fn);
    },
  };
}
</code></pre>
<h3 id="heading-heres-how-it-works">Here's how it works:</h3>
<p>1. We start with the return part - we know we want the person to say socket.on(...) so we need to return the on property.<br />2. They provide a string to <strong>"sub"</strong> them to the message they care about. They give us a function and we call that function with their data when that message comes in.</p>
<p><em>Now we just need a mechanism to keep track of the messages they've</em> <strong><em>subbed</em></strong> <em>to.</em></p>
<p>3. We implement an object where the keys are the names of the messages and the values are an array of the functions they provide.<br />4. Call the functions when the messages come in.  </p>
<p>And here's how we can call it:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> socket = ws(<span class="hljs-string">'ws://localhost:3000/ws'</span>)

socket.on(<span class="hljs-string">'test'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(data);
})
</code></pre>
<p>Now your turn! How would you implement the server part so that we could say</p>
<pre><code class="lang-typescript">socket.emit(<span class="hljs-string">'message'</span>, {id: <span class="hljs-number">0</span>, name: <span class="hljs-string">"Reilly"</span>, message: <span class="hljs-string">'hi'</span>})
</code></pre>
<p>Thanks for reading &lt;3</p>
]]></content:encoded></item><item><title><![CDATA[How to  get sorted set in descending order with node redis]]></title><description><![CDATA[everything is zRange now]]></description><link>https://blog.reilly.dev/how-to-get-sorted-set-in-descending-order-with-node-redis</link><guid isPermaLink="true">https://blog.reilly.dev/how-to-get-sorted-set-in-descending-order-with-node-redis</guid><category><![CDATA[Redis]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Sun, 04 Feb 2024 15:44:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707061423030/be6f7202-22bd-43c2-b304-d0485dad8211.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You've got a structure like this:</p>
<pre><code class="lang-typescript">redisClient.zAdd(<span class="hljs-string">'leaderboard'</span>, {score: <span class="hljs-number">0</span>, value: <span class="hljs-string">"charlie"</span>}
redisClient.zAdd(<span class="hljs-string">'leaderboard'</span>, {score: <span class="hljs-number">1</span>, value: <span class="hljs-string">"beth"</span>}
redisClient.zAdd(<span class="hljs-string">'leaderboard'</span>, {score: <span class="hljs-number">2</span>, value: <span class="hljs-string">"adam"</span>}
</code></pre>
<p>Sadly the below only retrieves the values in ASCENDING order</p>
<pre><code class="lang-typescript">redisClient.zRange(<span class="hljs-string">'leaderboard'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>);
</code></pre>
<p>This will give us:</p>
<pre><code class="lang-yaml"><span class="hljs-number">1</span><span class="hljs-string">)</span> <span class="hljs-string">"charlie"</span>
<span class="hljs-number">2</span><span class="hljs-string">)</span> <span class="hljs-string">"beth"</span>
<span class="hljs-number">3</span><span class="hljs-string">)</span> <span class="hljs-string">"adam"</span>
</code></pre>
<p>We have to pass the REV flag in the options</p>
<pre><code class="lang-typescript">redisClient.zRange(<span class="hljs-string">'leaderboard'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">2</span>, {
      REV: <span class="hljs-literal">true</span>,
    });
  }
</code></pre>
<p>If you ctrl+space in the object you get so many options it's hard to find it.</p>
<p>It took me a solid 10 min to find this. Hope this helps someone!</p>
<h2 id="heading-bonus"><strong>Bonus</strong>:</h2>
<p><strong>How to sort in desc order for top 10 results:</strong></p>
<pre><code class="lang-typescript">zRange(<span class="hljs-string">'leaderboard'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, {
      REV: <span class="hljs-literal">true</span>,
    });
  }
</code></pre>
<p><strong>how to do it with scores:</strong></p>
<pre><code class="lang-typescript">redisClient.zRangeWithScores(<span class="hljs-string">'leaderboard'</span>, <span class="hljs-number">0</span>, <span class="hljs-number">9</span>, {
      REV: <span class="hljs-literal">true</span>,
     });
</code></pre>
<p><strong>How to do it in CLI:</strong></p>
<pre><code class="lang-yaml"><span class="hljs-string">ZRANGEBYSCORE</span> <span class="hljs-string">leaderboard</span> <span class="hljs-number">0</span> <span class="hljs-number">9</span> <span class="hljs-string">rev</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Creating UDP server from scratch in Zig]]></title><description><![CDATA[At a high level this is how UDP servers work: Create a socket Bind the socket to a specific address and port (through the OS) Listen for messages at that…]]></description><link>https://blog.reilly.dev/creating-udp-server-from-scratch-in-zig</link><guid isPermaLink="true">https://blog.reilly.dev/creating-udp-server-from-scratch-in-zig</guid><category><![CDATA[zig]]></category><category><![CDATA[networking]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Sun, 07 Jan 2024 22:18:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/zx7VUt9txos/upload/0eda5f8a6fae3c778714762c9687aefe.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>At a high level this is how UDP servers work:</p>
<ol>
<li><p>Create a socket</p>
</li>
<li><p>Bind the socket to a specific address and port (through the OS)</p>
</li>
<li><p>Listen for messages at that specific address and port</p>
</li>
</ol>
<p>Here's how we do these steps in Zig:</p>
<h2 id="heading-create-a-socket">Create a socket</h2>
<p>We need to tell the OS to create a socket via the <code>std.os.socket</code> function.</p>
<p>Here's its signature:</p>
<pre><code class="lang-typescript">fn socket(domain: u32, socket_type: u32, protocol: u32) SocketError!socket_t
</code></pre>
<p><code>domain</code> refers to the IP address family: i.e. IPv4, or IPv6.</p>
<p><code>socket_type</code> is exactly what it sounds like. We'll use DGRAM (datagram) to signal we're making a UDP socket.</p>
<p><code>protocol</code> is for when we support multiple protocols for our server. For our simple one we only support 1 protocol: UDP. By passing a 0 we're telling the system to use the inferred protocol.</p>
<p>We get a <code>socket_t</code> from this to represent a socket.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> sock = <span class="hljs-keyword">try</span> std.os.socket(std.os.AF.INET, std.os.SOCK.DGRAM, <span class="hljs-number">0</span>);
</code></pre>
<h2 id="heading-bind-the-socket">bind the socket</h2>
<p>Next we need to tell the OS to bind the socket to a specific port and address so we can listen for messages.</p>
<p>Here's the function signature for bind</p>
<pre><code class="lang-typescript">fn bind(sock: socket_t, addr: *<span class="hljs-keyword">const</span> sockaddr, len: socklen_t) BindError!<span class="hljs-built_in">void</span>
<span class="hljs-comment">// addr is *const T where T is one of the sockaddr</span>
</code></pre>
<p><code>sock</code> is the socket we created from earlier (remember the <code>socket_t</code> )</p>
<p><code>addr</code> is a pointer to a <code>sockaddr</code> struct</p>
<p><code>len</code> is the size of the <code>Address</code> struct. Use the <code>getOsSockLen</code> method from our <code>Address</code> instance.</p>
<hr />
<p>Let's talk about how to get the <code>sockaddr</code> instance:</p>
<p>First we need to give the socket an address via: <code>parseIP4</code> Here's the function signature:</p>
<pre><code class="lang-typescript">fn parseIp4(buf: []<span class="hljs-keyword">const</span> u8, port: u16) !Address
</code></pre>
<p>the <code>buf</code> is the IP (idk why it's called a buf here)</p>
<p>From this we get an <code>Address</code> instance.</p>
<p>Address looks like this:</p>
<pre><code class="lang-typescript">pub <span class="hljs-keyword">const</span> Address = extern union {
    <span class="hljs-built_in">any</span>: os.sockaddr,
    <span class="hljs-keyword">in</span>: Ip4Address,
    in6: Ip6Address,
....
</code></pre>
<p>We can use the <code>.any</code> to access the socket address!</p>
<p>It needs a pointer so be sure to pass the address (via <code>&amp;</code> )</p>
<hr />
<p>We have this so far:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> std = <span class="hljs-meta">@import</span>(<span class="hljs-string">"std"</span>);
<span class="hljs-keyword">const</span> os = std.os;

pub fn main() !<span class="hljs-built_in">void</span> {
    <span class="hljs-keyword">const</span> sock = <span class="hljs-keyword">try</span> std.os.socket(std.os.AF.INET, std.os.SOCK.DGRAM, <span class="hljs-number">0</span>);
    <span class="hljs-keyword">const</span> parsed_address = <span class="hljs-keyword">try</span> std.net.Address.parseIp4(<span class="hljs-string">"127.0.0.1"</span>, <span class="hljs-number">3000</span>);
    <span class="hljs-keyword">try</span> os.bind(socket, address.any, address.getOsSockLen());

}
</code></pre>
<h2 id="heading-listen-for-messages">Listen for messages</h2>
<p>We'll use the <code>recvfrom</code> provided by the OS. This will get us the data from the socket without the address from the client.</p>
<p>The signature looks like this:</p>
<pre><code class="lang-typescript">fn recvfrom(
    sockfd: socket_t,
    buf: []u8,
    flags: u32,
    src_addr: ?*sockaddr,
    addrlen: ?*socklen_t,
) RecvFromError!usize
</code></pre>
<p>It needs a few things:</p>
<ol>
<li><p>what socket we're wanting to listen to (<code>sockfd</code>)</p>
</li>
<li><p>A buffer to put the bytes it gets from the stream</p>
</li>
</ol>
<p>The rest of the args from the signature aren't needed in this example.</p>
<p>Be sure to stick recvfrom in a persisted loop to keep listening for data.</p>
<h2 id="heading-code-example">Code example</h2>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> std = <span class="hljs-meta">@import</span>(<span class="hljs-string">"std"</span>);
<span class="hljs-keyword">const</span> expect = std.testing.expect;
<span class="hljs-keyword">const</span> net = std.net;
<span class="hljs-keyword">const</span> os = std.os;

test <span class="hljs-string">"create a socket"</span> {
    <span class="hljs-keyword">var</span> socket = <span class="hljs-keyword">try</span> Socket.init(<span class="hljs-string">"127.0.0.1"</span>, <span class="hljs-number">3000</span>);
    <span class="hljs-keyword">try</span> expect(<span class="hljs-meta">@TypeOf</span>(socket.socket) == std.os.socket_t);
}

<span class="hljs-keyword">const</span> Socket = struct {
    address: std.net.Address,
    socket: std.os.socket_t,

    fn init(ip: []<span class="hljs-keyword">const</span> u8, port: u16) !Socket {
        <span class="hljs-keyword">const</span> parsed_address = <span class="hljs-keyword">try</span> std.net.Address.parseIp4(ip, port);
        <span class="hljs-keyword">const</span> sock = <span class="hljs-keyword">try</span> std.os.socket(std.os.AF.INET, std.os.SOCK.DGRAM, <span class="hljs-number">0</span>);
        errdefer os.closeSocket(sock);
        <span class="hljs-keyword">return</span> Socket{ .address = parsed_address, .socket = sock };
    }

    fn bind(self: *Socket) !<span class="hljs-built_in">void</span> {
        <span class="hljs-keyword">try</span> os.bind(self.socket, &amp;self.address.any, self.address.getOsSockLen());
    }

    fn listen(self: *Socket) !<span class="hljs-built_in">void</span> {
        <span class="hljs-keyword">var</span> buffer: [<span class="hljs-number">1024</span>]u8 = <span class="hljs-literal">undefined</span>; 

        <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {
            <span class="hljs-keyword">const</span> received_bytes = <span class="hljs-keyword">try</span> std.os.recvfrom(self.socket, buffer[<span class="hljs-number">0.</span>.], <span class="hljs-number">0</span>, <span class="hljs-literal">null</span>, <span class="hljs-literal">null</span>);
            std.debug.print(<span class="hljs-string">"Received {d} bytes: {s}\n"</span>, .{ received_bytes, buffer[<span class="hljs-number">0.</span>.received_bytes] }); 
        }
    }
};
</code></pre>
<h2 id="heading-interacting-with-the-server">Interacting with the server</h2>
<p>We can run <code>nc -u 127.0.0.1 3000</code> to interact with the UDP server. Be sure to pass the -u flag to tell netcat that this is a UDP connection as it defaults to TCP.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704666075063/f2c1f36b-7146-413d-a407-1d2483698212.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1704666085925/37d352b4-862c-442c-9fb7-096602de3706.png" alt class="image--center mx-auto" /></p>
<p>Thanks for reading :)</p>
]]></content:encoded></item><item><title><![CDATA[Why we use containers]]></title><description><![CDATA[There are a metric shit ton of things that interact with an application that you run locally - your OS, system & env variables, software deps, & configs…]]></description><link>https://blog.reilly.dev/why-we-use-containers</link><guid isPermaLink="true">https://blog.reilly.dev/why-we-use-containers</guid><category><![CDATA[containers]]></category><category><![CDATA[containerization]]></category><category><![CDATA[Docker]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Mon, 29 May 2023 01:19:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/dI_S0Kyq1Z0/upload/6244bc41b08c226161b1578d31b55c0f.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>There are a metric shit ton of things that interact with an application that you run locally - your OS, system &amp; env variables, software deps, &amp; configs. It's super common in the software industry to run into problems like: "This works on my computer - I'm not sure why it's not working on yours."  </p>
<p>There's a solution - <strong>containerization</strong>.</p>
<p>TLDR; containerization allows applications to run consistently on any computer no matter what the differences mentioned above may be.</p>
<h2 id="heading-how-containerization-works">How containerization works</h2>
<p>Containerization packs all the important shit into a standardized environment that locks in all of the dependencies into its own isolated segment. This means that we don't have to worry about interferences between containers - we could conceptually have thousands of containers running on the same OS and there would be no risk of them interfering with each other (handling a lot of containers efficiently is difficult - which is why container orchestration platforms like Kubernetes exist.)</p>
<p>All of this is made possible by <strong>images</strong> - which feels like a strange word but it just refers to a "snapshot" of the configuration needed to create the standardized environment.</p>
]]></content:encoded></item><item><title><![CDATA[Getting closure with React]]></title><description><![CDATA[Closures are like a backpack for functions. The backpack holds all of the values the function needs from its original environment, even if it's called in a…]]></description><link>https://blog.reilly.dev/getting-closure-with-react</link><guid isPermaLink="true">https://blog.reilly.dev/getting-closure-with-react</guid><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Sat, 22 Apr 2023 13:35:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/ALZb2Gv20TY/upload/v1653687736724/QG767M2dC.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-whats-a-closure">What's a closure?</h2>
<p>Closures are like a backpack for functions. The backpack holds all of the values the function needs from its original environment, even if it's called in a different place. <strong>It gives functions access to all of its belongings no matter where it's called</strong>.</p>
<p>Here's a simple code example:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createCounter</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">let</span> count = <span class="hljs-number">0</span>

    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>)</span>{
        count++
        <span class="hljs-built_in">console</span>.log(count)
    }

}

<span class="hljs-keyword">const</span> counter = createCounter()
counter() <span class="hljs-comment">// Outputs: 1</span>
counter() <span class="hljs-comment">// Outputs: 2</span>
counter() <span class="hljs-comment">// Outputs: 3</span>
</code></pre>
<p>The inner function has a closure (or backpack) that allows it to "remember" the value of count no matter where we call it!</p>
<p>This is a super powerful tool that makes a lot of things possible!</p>
<h2 id="heading-closures-in-react">Closures in React</h2>
<p>Here's the "React" version of the above code</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCount</span>(<span class="hljs-params"></span>)</span>{
        setCount(count + <span class="hljs-number">1</span>);
    }

    <span class="hljs-keyword">return</span> (  
        &lt;button onClick={updateCount}&gt;
            {count}
        &lt;/button&gt;  
    )
}
</code></pre>
<p>The <em>closure</em> is what allows <code>updateCount</code> to <strong>remember</strong> and access the value of <code>count</code> and the <code>setCount</code> function.  </p>
<h2 id="heading-react-rendering-a-snapshot-of-the-component">React Rendering - a snapshot of the component</h2>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>)

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateCount</span>(<span class="hljs-params"></span>)</span>{
        setCount(count + <span class="hljs-number">1</span>);
        <span class="hljs-built_in">console</span>.log(count) <span class="hljs-comment">// what do we get here?</span>
    }

    <span class="hljs-keyword">return</span> (  
        &lt;button onClick={updateCount}&gt;
            {count}
        &lt;/button&gt;  
    )
}
</code></pre>
<p>Now what happens when we log the value of <code>count</code> after updating it?</p>
<p>It may surprise you - but it's still whatever the value was before you updated it! (i.e. 0 after first clicked)</p>
<p>The reason: React doesn't immediately update <code>count</code> so we are left with a <em>stale</em> value - in this case, what the count originally was before the update.</p>
<p>Instead, <code>count</code> (state) won't be updated until React <strong>renders</strong> the component again.</p>
<p>This is because [state behaves like a snapshot](<a target="_blank" href="https://react.dev/learn/state-as-a-snapshot">https://react.dev/learn/state-as-a-snapshot</a>)</p>
]]></content:encoded></item><item><title><![CDATA[Building Typesafe Full Stack App w/ Apollo Server 4, Railway, Prisma, Pothos, Next, & TS (part 1 - setting up the server)]]></title><description><![CDATA[The best way to get typesafety in Graphql]]></description><link>https://blog.reilly.dev/building-typesafe-full-stack-app-w-apollo-server-4-railway-prisma-pothos-next-ts-part-1-setting-up-the-server</link><guid isPermaLink="true">https://blog.reilly.dev/building-typesafe-full-stack-app-w-apollo-server-4-railway-prisma-pothos-next-ts-part-1-setting-up-the-server</guid><category><![CDATA[Next.js]]></category><category><![CDATA[GraphQL]]></category><category><![CDATA[Apollo GraphQL]]></category><category><![CDATA[TypeScript]]></category><category><![CDATA[prisma]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Sun, 08 Jan 2023 16:04:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/YZPh3-B4iZk/upload/926b78ed89f79390cc75fcfcbcb29ded.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>I've spent the past few days or so setting this up and wanted to share everything I've learned to hopefully help some people out!</p>
<p>This article assumes basic proficiency with Graphql. We're going to be talking about resolvers, schemas, mutations, and queries. If those things sound confusing to you check out <a target="_blank" href="https://www.prisma.io/blog/graphql-server-basics-the-schema-ac5e2950214e">Prisma's fresher on GraphQL</a>.</p>
<p>Let's get started!</p>
<h2 id="heading-setting-up-next">Setting up Next</h2>
<pre><code class="lang-bash">npx create-next-app@latest --typescript
</code></pre>
<p>It will then prompt you for the project name and if you want eslint enabled then begins downloading the packages!</p>
<h2 id="heading-setting-up-postgres-railway">Setting up Postgres (Railway)</h2>
<p>It's insane how quickly you can provision a Postgres server on Railway I promise it will blow your mind.</p>
<p>Head over to <a target="_blank" href="https://railway.app/new">https://railway.app/new</a> and select "Provision PostgreSQL."</p>
<p>Once the database is provisioned (it'll show the date created in the node box) click on it and go over to the "Connect" tab.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673231139340/205f444b-bc08-4c3a-b1b8-da46ae879997.png" alt class="image--center mx-auto" /></p>
<p>From there copy the Postgres Connection URL and paste it into the .env file for the value for the DATABASE_URL key.</p>
<p>BOOM! 🤯 How easy was that? Now let's set up Prisma.</p>
<h2 id="heading-setting-up-prisma">Setting up Prisma</h2>
<p>Prisma is a sweet ORM that gives fantastic type safety by auto-generating types from our database schema! This is perfect for our TS project!</p>
<p>To get started:</p>
<pre><code class="lang-bash">yarn add -D prisma @prisma/client
</code></pre>
<p>After that completes initialize Prisma</p>
<pre><code class="lang-bash">npx prisma init
</code></pre>
<p>Add the following to the <code>schema.prisma</code> file</p>
<pre><code class="lang-plaintext">generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
  id               Int       @id @default(autoincrement())
  email            String    @unique
  username         String    @unique
  hashedPassword   String
  name             String
  birthday         DateTime
  createdAt        DateTime  @default(now())
  isOnline         Boolean   @default(false)
  posts            Post[]
}

model Post {
  id          Int       @id @default(autoincrement())
  title       String
  content     String
  createdAt   DateTime  @default(now())
  updatedAt   DateTime  @updatedAt
  url         String
  isPublished Boolean   @default(false)
  author      User      @relation(fields: [authorId], references: [id])
  authorId    Int
}
</code></pre>
<p>In summary, we've defined a one-to-many relationship between the User model and Post model. In the Post model we've set a foreign key - "authorId" - paired to a primary key in the User model - "id".</p>
<h3 id="heading-seeding-database">Seeding Database</h3>
<p>Now let's seed our database. Create a file <code>seed.ts</code> in the <code>prisma</code> folder</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PrismaClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'@prisma/client'</span>

<span class="hljs-keyword">const</span> db = <span class="hljs-keyword">new</span> PrismaClient()

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">seed</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.all(
    createUsers().map(<span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
      <span class="hljs-keyword">return</span> db.user.create({ data: user })
    })
  )
}

seed()

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createUsers</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> [
    {
      email: <span class="hljs-string">'adam@gmail.com'</span>,
      name: <span class="hljs-string">'Adam'</span>,
      username: <span class="hljs-string">'adamIsAwesome'</span>,
      hashedPassword: <span class="hljs-string">'123456'</span>,
      birthday: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'1945-01-01'</span>),
    },
    {
      email: <span class="hljs-string">'bob@gmail.com'</span>,
      name: <span class="hljs-string">'Bob'</span>,
      username: <span class="hljs-string">'bob'</span>,
      hashedPassword: <span class="hljs-string">'asoidf'</span>,
      birthday: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'1965-01-01'</span>),
    },
    {
      email: <span class="hljs-string">'charlie@gmail.com'</span>,
      name: <span class="hljs-string">'charlie'</span>,
      username: <span class="hljs-string">'charlie'</span>,
      hashedPassword: <span class="hljs-string">'pjioas'</span>,
      birthday: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'1985-01-01'</span>),
    },
    {
      email: <span class="hljs-string">'dan@abc.com'</span>,
      name: <span class="hljs-string">'Dan'</span>,
      username: <span class="hljs-string">'DanTheMan'</span>,
      hashedPassword: <span class="hljs-string">'1234'</span>,
      birthday: <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(<span class="hljs-string">'1996-07-01'</span>),
    },
  ]
}
</code></pre>
<p>Let's sync our database with our Prisma schema:</p>
<pre><code class="lang-bash">yarn prisma db push
</code></pre>
<p>Let's seed the database. First, we need a way to compile this <code>seed.ts</code> file. We can run the typescript compiler using <code>tsc</code> and then point Prisma to that compiled file location or we can use <code>ts-node</code></p>
<p>I like using ts-node so I'll use that</p>
<pre><code class="lang-bash">yarn add -D ts-node
</code></pre>
<p>Now let's add the command to the <code>package.json</code></p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"apollo-prisma-pothos-next"</span>,
  <span class="hljs-attr">"version"</span>: <span class="hljs-string">"0.1.0"</span>,
  <span class="hljs-attr">"private"</span>: <span class="hljs-literal">true</span>,
  <span class="hljs-attr">"scripts"</span>: {
    <span class="hljs-attr">"dev"</span>: <span class="hljs-string">"next dev"</span>,
    <span class="hljs-attr">"build"</span>: <span class="hljs-string">"next build"</span>,
    <span class="hljs-attr">"start"</span>: <span class="hljs-string">"next start"</span>,
    <span class="hljs-attr">"lint"</span>: <span class="hljs-string">"next lint"</span>
  },
  <span class="hljs-attr">"prisma"</span>: {
    <span class="hljs-attr">"seed"</span>: <span class="hljs-string">"ts-node --compiler-options {\"module\":\"CommonJS\"} prisma/seed.ts"</span>
  },
  <span class="hljs-attr">"dependencies"</span>: {
    <span class="hljs-attr">"@next/font"</span>: <span class="hljs-string">"13.1.1"</span>,
    <span class="hljs-attr">"@prisma/client"</span>: <span class="hljs-string">"^4.8.1"</span>,
    <span class="hljs-attr">"@types/node"</span>: <span class="hljs-string">"18.11.18"</span>,
    <span class="hljs-attr">"@types/react"</span>: <span class="hljs-string">"18.0.26"</span>,
    <span class="hljs-attr">"@types/react-dom"</span>: <span class="hljs-string">"18.0.10"</span>,
    <span class="hljs-attr">"eslint"</span>: <span class="hljs-string">"8.31.0"</span>,
    <span class="hljs-attr">"eslint-config-next"</span>: <span class="hljs-string">"13.1.1"</span>,
    <span class="hljs-attr">"next"</span>: <span class="hljs-string">"13.1.1"</span>,
    <span class="hljs-attr">"react"</span>: <span class="hljs-string">"18.2.0"</span>,
    <span class="hljs-attr">"react-dom"</span>: <span class="hljs-string">"18.2.0"</span>,
    <span class="hljs-attr">"typescript"</span>: <span class="hljs-string">"4.9.4"</span>
  },
  <span class="hljs-attr">"devDependencies"</span>: {
    <span class="hljs-attr">"prisma"</span>: <span class="hljs-string">"^4.8.1"</span>
  }
}
</code></pre>
<p>Now we can seed the database</p>
<pre><code class="lang-bash">yarn prisma db seed
</code></pre>
<p>Now we can check out our data!</p>
<pre><code class="lang-bash">yarn prisma studio
</code></pre>
<p>Go to the URL specified and you should see this</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673134928724/c336f8ed-fdb6-4dcc-8888-c7dd18c6fc97.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-export-the-prisma-client">Export the Prisma Client</h3>
<p>We will want to share the Prisma instance with the other parts of the app, so let's make that accessible!</p>
<p>Create a file called <code>index.ts</code> in the prisma folder with the following contents:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { PrismaClient } <span class="hljs-keyword">from</span> <span class="hljs-string">'@prisma/client'</span>

<span class="hljs-keyword">let</span> db: PrismaClient

<span class="hljs-keyword">declare</span> <span class="hljs-built_in">global</span> {
  <span class="hljs-keyword">var</span> __db: PrismaClient | <span class="hljs-literal">undefined</span>
}

<span class="hljs-comment">// this is needed to stop creating a new instance of Prisma everytime the server restarts</span>
<span class="hljs-keyword">if</span> (process.env.NODE_ENV === <span class="hljs-string">'production'</span>) {
  db = <span class="hljs-keyword">new</span> PrismaClient()
} <span class="hljs-keyword">else</span> {
  <span class="hljs-keyword">if</span> (!<span class="hljs-built_in">global</span>.__db) {
    <span class="hljs-built_in">global</span>.__db = <span class="hljs-keyword">new</span> PrismaClient()
  }
  db = <span class="hljs-built_in">global</span>.__db
}

<span class="hljs-keyword">export</span> { db }
</code></pre>
<p>Awesome! Now we can access the client from other places in our app.</p>
<h2 id="heading-setting-up-apollo-server">Setting up Apollo Server</h2>
<p>Let's add the stuff required for the Apollo Server</p>
<pre><code class="lang-bash">yarn add @apollo/server graphql @as-integrations/next
</code></pre>
<p>We're using "@as-integrations/next" to have Apollo Server work seamlessly with Next.</p>
<p>The API folder is where all of the server code runs. We're going to set up the GraphQL server to run at the <code>api/graphql</code> endpoint so make a file called <code>graphql.ts</code> in the API folder. In that file, we are going to init the Apollo Server with the schema from Pothos. Then we'll hook up the Next / Apollo Server integration package.</p>
<p>We'll define a schema later so don't worry about that for now. It will look something like this:</p>
<p><code>graphql.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { ApolloServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/server'</span>;
<span class="hljs-keyword">import</span> { startServerAndCreateNextHandler } <span class="hljs-keyword">from</span> <span class="hljs-string">'@as-integrations/next'</span>;

<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> ApolloServer({});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> startServerAndCreateNextHandler(server);
</code></pre>
<p>Now we need to pass a resolver and schema to the ApolloServer instance.</p>
<p>We could use SDL to create the schema and manually create resolvers but we lose the typesafety that a tool like Pothos offers.</p>
<p>So for now let's leave the graphql.ts as is - we'll return after we setup Pothos</p>
<h2 id="heading-setting-up-pothos">Setting up Pothos</h2>
<p>Real quick: Pothos supports a Prisma plugin that makes things like defining Prisma object types and solving n+1 issues easier and most importantly shares the types Prisma auto generates to our schemas and resolvers.</p>
<p>To start, install the Pothos package, the Prisma plugin, and graphql-scalars which we will use to create a Date scalar:</p>
<pre><code class="lang-bash">yarn add @pothos/core @pothos/plugin-prisma graphql-scalars
</code></pre>
<h3 id="heading-integrate-pothos-with-prisma"><strong>Integrate Pothos With Prisma</strong></h3>
<p>To get Pothos and Prisma to share types we need to add the following to the top of the <code>schema.prisma</code> file:</p>
<pre><code class="lang-typescript">generator pothos {
  provider = <span class="hljs-string">"prisma-pothos-types"</span>
}
</code></pre>
<p>Now every time the Prisma types get re-generated it will create the pothos types.</p>
<p>To regenerate the Prisma types and create the pothos types run:</p>
<pre><code class="lang-bash">yarn prisma generate
</code></pre>
<h3 id="heading-setup-the-schema-builder"><strong>Setup the Schema Builder</strong></h3>
<p>Ok, now we're ready to setup our schema through the <code>SchemaBuilder</code> API!</p>
<p>Let's create a folder called <code>graphql</code> in the root directory. Add a file, <code>builder.ts</code> inside of which we will need to import the <code>SchemaBuilder</code> to build our schema for GraphQL. From there we can hook it up to Prisma and define our custom scalar to support a date scalar.</p>
<p><code>builder.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> SchemaBuilder <span class="hljs-keyword">from</span> <span class="hljs-string">'@pothos/core'</span>
<span class="hljs-keyword">import</span> PrismaPlugin <span class="hljs-keyword">from</span> <span class="hljs-string">'@pothos/plugin-prisma'</span>
<span class="hljs-keyword">import</span> { DateResolver } <span class="hljs-keyword">from</span> <span class="hljs-string">'graphql-scalars'</span>

<span class="hljs-comment">// This is the default location for the generator, but this can be</span>
<span class="hljs-comment">// customized as described above.</span>
<span class="hljs-comment">// Using a type only import will help avoid issues with undeclared</span>
<span class="hljs-comment">// exports in esm mode</span>
<span class="hljs-keyword">import</span> <span class="hljs-keyword">type</span> PrismaTypes <span class="hljs-keyword">from</span> <span class="hljs-string">'@pothos/plugin-prisma/generated'</span>

<span class="hljs-keyword">import</span> { db <span class="hljs-keyword">as</span> prisma } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../prisma/index'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> builder = <span class="hljs-keyword">new</span> SchemaBuilder&lt;{
<span class="hljs-comment">// The types used here will be used for the resolvers</span>
  Scalars: {
    <span class="hljs-built_in">Date</span>: { Input: <span class="hljs-built_in">Date</span>; Output: <span class="hljs-built_in">Date</span> }
  }
  PrismaTypes: PrismaTypes
}&gt;({
  plugins: [PrismaPlugin],
  prisma: {
    client: prisma,
  },
})

<span class="hljs-comment">// in GraphQL the Query type and Mutation type can each only be called once. So we call it here and will add fields to them on the go </span>
builder.queryType();
builder.mutationType();

<span class="hljs-comment">// This is where we've created the new date scalar</span>
builder.addScalarType(<span class="hljs-string">'Date'</span>, DateResolver, {})
</code></pre>
<p>Now let's define some custom types and set up the resolvers.</p>
<h3 id="heading-defining-our-first-custom-object-type-user"><strong>Defining Our First Custom Object Type - User</strong></h3>
<p>Create a folder called <code>schema</code> and in it create a file called <code>user.ts</code></p>
<p>Now we'll use the SchemaBuilder to generate our custom object. This is where the Prisma plugin will really shine &amp; we'll begin getting some auto-completion.</p>
<p>This user type will be the first of 2 types we will generate using the Pothos builder.</p>
<p>Let's import our builder and use the prismaObject method available that exposes the types Prisma generated. The first argument is the name of this custom type, followed by the fields. The keys in the field can be anything we want but the arguments passed to the exposeString, for example, are literally our Prisma types and has auto-completion.</p>
<p>One quick note: for the birthday field we want to use our custom date scalar and the syntax is just a little different than the rest of them.</p>
<p>So in <code>user.ts</code> we'll have:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { db } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../prisma/index'</span>
<span class="hljs-keyword">import</span> { builder } <span class="hljs-keyword">from</span> <span class="hljs-string">'../builder'</span>

builder.prismaObject(<span class="hljs-string">'User'</span>, {
  fields: <span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> ({
    id: t.exposeInt(<span class="hljs-string">'id'</span>),
    name: t.exposeString(<span class="hljs-string">'name'</span>),
    email: t.exposeString(<span class="hljs-string">'email'</span>),
    pass: t.exposeString(<span class="hljs-string">'hashedPassword'</span>),
    isOnline: t.exposeBoolean(<span class="hljs-string">'isOnline'</span>),
    username: t.exposeString(<span class="hljs-string">'username'</span>),
    birthday: t.expose(<span class="hljs-string">'birthday'</span>, {
      <span class="hljs-keyword">type</span>: <span class="hljs-string">'Date'</span>,
    }),
  }),
})
</code></pre>
<h3 id="heading-add-user-field-to-query-type-and-provide-resolver">Add User Field to Query Type and Provide Resolver</h3>
<p>Now that we have our custom type for users defined let's add a field to the root query type for it!</p>
<p>I mentioned earlier that the root query type can only be defined once (which we already did) so we will add fields to it by calling the builder and using the <code>queryFields</code> method. If we wanted to just have one massive root query we could use the builder's <code>queryType</code> method which would create an instance of a root query for us.</p>
<p>Ok, so now we know that we need to use a queryField. We'll need to provide the field a name, we'll call it retrieveUser, and then connect it to the Prisma type and have the resolver return some useful data. Every query can have n number of arguments so we will require an id to be passed as an argument. We'll take that id and search for a user using Prisma.</p>
<p>So continuing <code>user.ts</code>:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Adding this code to user.ts</span>

<span class="hljs-comment">// Ok, using the queryField like we mentioned</span>
builder.queryFields(<span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> ({
  <span class="hljs-comment">// Here we name our field for the root query</span>
  retrieveUser: t.prismaField({
    <span class="hljs-comment">// We are using the 'User' model from Prisma types</span>
    <span class="hljs-keyword">type</span>: <span class="hljs-string">'User'</span>,
    <span class="hljs-comment">// We want the user to pass an argument of the type int </span>
    args: {
      id: t.arg.int({ required: <span class="hljs-literal">true</span> }),
    },
    <span class="hljs-comment">// Now we can defined what the resolver returns</span>
    resolve: <span class="hljs-function">(<span class="hljs-params">query, root, args, ctx, info</span>) =&gt;</span> {
      <span class="hljs-comment">// We find the user with that id using Prisma</span>
      <span class="hljs-keyword">return</span> db.user.findUniqueOrThrow({
        where: {
          id: args.id,
        },
      })
    },
  }),
}))
</code></pre>
<h3 id="heading-add-root-mutation-andamp-resolver-for-user-type">Add Root Mutation &amp; Resolver for User Type</h3>
<p>Now let's define a field to the Mutation type and implement a resolver to create a user. Instead of expecting one single arg (id) we will require all the fields that are required in the Prisma User model.</p>
<p>Same syntax as the <code>queryFields</code> but instead, it will be <code>mutationFields</code>.</p>
<p>Remember that the args are what the user will pass through GraphQL - which we can call whatever we want! Since the fields are required I'm going to add the syntax to make them required.</p>
<p>Add this to <code>user.ts</code></p>
<pre><code class="lang-typescript">builder.mutationFields(<span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> ({
  createUser: t.prismaField({
    <span class="hljs-keyword">type</span>: <span class="hljs-string">'User'</span>,
    args: {
      name: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      email: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      pass: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      username: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      birthday: t.arg({ <span class="hljs-keyword">type</span>: <span class="hljs-string">'Date'</span>, required: <span class="hljs-literal">true</span> }),
    },
    resolve: <span class="hljs-function">(<span class="hljs-params">query, root, args, ctx, info</span>) =&gt;</span> {
      <span class="hljs-keyword">return</span> db.user.create({
        data: {
          name: args.name,
          email: args.email,
          hashedPassword: args.pass,
          username: args.username,
          birthday: args.birthday,
        },
      });
    },
  }),
}));
</code></pre>
<p>Ok, I'm excited to go try these out in the Apollo Server sandbox but first, we will need the builder to generate this into a schema using the <code>toSchema</code> method!</p>
<p>So at the end of <code>user.ts</code> do a named export for that under whatever name you want, I'm just going to call it schema!</p>
<pre><code class="lang-typescript">
<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> schema = builder.toSchema()
</code></pre>
<h3 id="heading-import-schema-in-apollo-server">Import Schema in Apollo Server</h3>
<p>Now back in Apollo Server we can import this schema to get this thing running!</p>
<p><code>graphql.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { ApolloServer } <span class="hljs-keyword">from</span> <span class="hljs-string">'@apollo/server'</span>;
<span class="hljs-keyword">import</span> { startServerAndCreateNextHandler } <span class="hljs-keyword">from</span> <span class="hljs-string">'@as-integrations/next'</span>;
<span class="hljs-keyword">import</span> { schema } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../graphql/schema/user'</span>

<span class="hljs-keyword">const</span> server = <span class="hljs-keyword">new</span> ApolloServer({});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> startServerAndCreateNextHandler(server);
</code></pre>
<h3 id="heading-interact-with-apollo-server-playground">Interact with Apollo Server Playground</h3>
<p>Now we can start the server by running</p>
<pre><code class="lang-bash">yarn dev
</code></pre>
<p>Now visit http://localhost:3000/api/graphql to begin the Apollo Server playground - it should look like this!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673155160223/e1eb6ce1-7784-4f8d-b04f-993b96bb80d6.png" alt class="image--center mx-auto" /></p>
<p>Now if you remove that id with the red squiggly line and type ctrl+space (Windows) / command+space (mac) you'll see the one type we've defined on our Query type. Select that and it will autocomplete the query with the required arguments!</p>
<p>Now inside the braces for the retrieveUser type we can extract all of the fields we defined in our User schema. Hit ctrl+space / command+space to select some fields.</p>
<p>At the bottom of the screen in the variables section set the value of "retrieveUserId" to 1.</p>
<p>Now, depending on what fields you've requested, you should see it's the user "Bob"</p>
<p><strong>Mutations</strong></p>
<p>Let's run a mutation now by running createUser field.</p>
<p>Remove all the code and type <code>mutation {}</code> and inside of the curly braces type command+space and select the createUser field. Select whatever fields you want to return.</p>
<p>Be sure your variables match the the names in the arguments. It should look like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673156168034/91caf47d-9c77-4553-ae19-7636d1d4133c.png" alt class="image--center mx-auto" /></p>
<p>Now let's check our database and see the new user via Prisma studio!</p>
<pre><code class="lang-bash">yarn prisma studio
</code></pre>
<p>If everything worked it should be there in the User table!</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1673156282364/97a25043-946a-4dbf-ae6a-80a6f5c49464.png" alt class="image--center mx-auto" /></p>
<p><strong>Defining Our Second Custom Object Type - Post</strong></p>
<p>Now in the <code>schema</code> folder let's add <code>post.ts</code> to create the Post type.</p>
<p>We'll be doing the same thing that we did in user.ts but with different fields to match the Post model.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { db } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../prisma/index'</span>;
<span class="hljs-keyword">import</span> { builder } <span class="hljs-keyword">from</span> <span class="hljs-string">'../builder'</span>;

builder.prismaObject(<span class="hljs-string">'Post'</span>, {
  fields: <span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> ({
    id: t.exposeInt(<span class="hljs-string">'id'</span>),
    title: t.exposeString(<span class="hljs-string">'title'</span>),
    content: t.exposeString(<span class="hljs-string">'content'</span>),
    createdAt: t.expose(<span class="hljs-string">'createdAt'</span>, {
      <span class="hljs-keyword">type</span>: <span class="hljs-string">'Date'</span>,
    }),
    updatedAt: t.expose(<span class="hljs-string">'updatedAt'</span>, {
      <span class="hljs-keyword">type</span>: <span class="hljs-string">'Date'</span>,
    }),
    url: t.exposeString(<span class="hljs-string">'url'</span>),
    isPublished: t.exposeBoolean(<span class="hljs-string">'isPublished'</span>),
    author: t.relation(<span class="hljs-string">'author'</span>),
  }),
});
</code></pre>
<h3 id="heading-add-post-fields-to-query-and-mutation-type">Add Post Fields to Query and Mutation Type</h3>
<p>Now let's define some fields on the Query and Mutation Type. It will be extremely similar to what we did back in <code>user.ts</code> so I won't walk through the steps this time.</p>
<p><code>post.ts</code></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Add this to the post.ts file </span>

builder.queryFields(<span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> ({
  post: t.prismaField({
    <span class="hljs-keyword">type</span>: <span class="hljs-string">'Post'</span>,
    args: {
      id: t.arg.int({ required: <span class="hljs-literal">true</span> }),
    },
    resolve: <span class="hljs-keyword">async</span> (query, root, args, ctx, info) =&gt; {
      <span class="hljs-keyword">return</span> db.post.findUniqueOrThrow({
        where: {
          id: args.id,
        },
      })
    },
  }),
}))

builder.mutationFields(<span class="hljs-function">(<span class="hljs-params">t</span>) =&gt;</span> ({
  createPost: t.prismaField({
    <span class="hljs-keyword">type</span>: <span class="hljs-string">'Post'</span>,
    args: {
      title: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      content: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      url: t.arg.string({ required: <span class="hljs-literal">true</span> }),
      isPublished: t.arg.boolean({ required: <span class="hljs-literal">true</span> }),
      authorId: t.arg.int({ required: <span class="hljs-literal">true</span> }),
    },
    resolve: <span class="hljs-keyword">async</span> (query, root, args, ctx, info) =&gt; {
      <span class="hljs-keyword">return</span> db.post.create({
        data: {
          title: args.title,
          content: args.content,
          url: args.url,
          isPublished: args.isPublished,
          authorId: args.authorId,
        },
      });
    },
  }),
}));
</code></pre>
<h3 id="heading-generating-schema-with-schemabuilder-for-multiple-files">Generating Schema with <code>SchemaBuilder</code> For Multiple Files</h3>
<p>Now we've got multiple places that are used for defining our schema: <code>user.ts</code> and <code>post.ts</code> . The SchemaBuilder needs to import all the different components to generate the schema for us.</p>
<p>To do this let's first: remove the call to generate the schema at the bottom of <code>user.ts</code> (don't forget to remove the imported builder too.) The line at the bottom was this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> schema = builder.toSchema();
</code></pre>
<p>Create an <code>index.ts</code> file inside of the <code>schema</code> folder and import our two files in the schema folder that represent our custom object types, User and Post, and the fields that we added to the Query and Mutation types with their respected resolvers. We'll also need to import the SchemaBuilder to combine it all.</p>
<p>You should have this in <code>index.ts</code> :</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { builder } <span class="hljs-keyword">from</span> <span class="hljs-string">'../builder'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./user'</span>;
<span class="hljs-keyword">import</span> <span class="hljs-string">'./post'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> schema = builder.toSchema();
</code></pre>
<p>Now we'll need to go back to the <code>graphql.ts</code> file to adjust where the schema for ApolloServer lives. Change the path for the import so it looks like this:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { schema } <span class="hljs-keyword">from</span> <span class="hljs-string">'../../graphql/schema/index'</span>;
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Now we've got our server in a really good place. Feel free to play around in the Apollo Server Playground to create some new posts and view them!</p>
<p>In Part 2 we'll be setting this up to the Next Client and generating the types so we can get typesafety and auto-complete!</p>
<p>If you have any questions / problems def reach out by either commenting or DM'ing me on Twitter <a target="_blank" href="https://twitter.com/reillyjodonnell">@reillyjodonnell</a></p>
<p>github repo link: <a target="_blank" href="https://github.com/reillyjodonnell/apollo-prisma-pothos-next">https://github.com/reillyjodonnell/apollo-prisma-pothos-next</a></p>
]]></content:encoded></item><item><title><![CDATA[6 Code Smells In React I Look Out For]]></title><description><![CDATA[I've recently undergone analyzing and improving a React application's performance and have noticed some pretty serious code smells that affect both code…]]></description><link>https://blog.reilly.dev/6-code-smells-in-react-i-look-out-for</link><guid isPermaLink="true">https://blog.reilly.dev/6-code-smells-in-react-i-look-out-for</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Fri, 06 Jan 2023 03:28:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/rrX4SWCyJQ8/upload/1a5d537f09eb685b556503496b63afac.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I've recently undergone analyzing and improving a React application's performance and have noticed some pretty serious code smells that affect both code quality and performance.</p>
<p>Here are some code smells that I watch out for in a React application:</p>
<ol>
<li><p>A massive component (500+ LOC) - I hesitate to write a specific number of LOC because there are always exceptions but 500 begins to become TOO large. Components should be small and practice <a target="_blank" href="https://reactjs.org/docs/thinking-in-react.html#step-1-break-the-ui-into-a-component-hierarchy:~:text=But%20how%20do,into%20smaller%20subcomponents">Individual Responsibility</a>.</p>
</li>
<li><p>Business logic and UI are intertwined - components should only contain the UI and not have complex business rules intertwined in the component. I suggest abstracting away business rules either into a helper function or into a custom hook.</p>
</li>
<li><p>No tests for business logic - each set of business logic rules should be tested to document the expected outcome. Tests add <strong>confidence</strong> to the software that other programmers can use to be certain that they didn't break something pre-existing. It is extremely helpful to have tests when you need to refactor to get immediate feedback through the testing framework.</p>
</li>
<li><p>Massive amounts of props are being passed - if there are a lot of props being passed through the component I check two things:</p>
<ol>
<li><p>Can we compose this component better with composition (see smell 5)</p>
</li>
<li><p>If we're prop drilling certain props, like a user object or some international translation function that doesn't change that often, let's put it into Context.</p>
</li>
</ol>
</li>
<li><p>Lack of use of composition - If a codebase or a section of code isn't taking advantage of composition it points to a lack of understanding of React. Using composition results in fewer unnecessary rerenders and less prop drilling.<br /> Two fantastic resources if you're unfamiliar with composition: an article by Kent C. Dodds <a target="_blank" href="https://epicreact.dev/one-react-mistake-thats-slowing-you-down/">https://epicreact.dev/one-react-mistake-thats-slowing-you-down/</a> and a video by Michael Jackson (no not that one) <a target="_blank" href="https://www.youtube.com/watch?v=3XaXKiXtNjw&amp;t=592s">https://www.youtube.com/watch?v=3XaXKiXtNjw&amp;t=592s</a></p>
</li>
<li><p>Incorrect usage of hooks - the most commonly misused I've seen are useEffect - which should <strong>not</strong> be used to adjust state or props when a certain value changes, or replicate what componentDidMount/ other lifecycle methods did. Instead use it to sync an external system to React (network, DOM, etc.) These days with how awesome React-Query/SWR are you don't even need it.  </p>
<p> Also, stop putting useCallbacks everywhere - <a target="_blank" href="https://www.explainxkcd.com/wiki/images/d/d5/optimization.png">premature optimization is the root of all evil</a>.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[⚛ React Tips - You're misusing the React useEffect hook (probably)]]></title><description><![CDATA[This is def one of the most common mistakes I've seen in both personal and enterprise applications. The useEffect hook exists to sync an external system…]]></description><link>https://blog.reilly.dev/react-tips-youre-misusing-the-react-useeffect-hook-probably</link><guid isPermaLink="true">https://blog.reilly.dev/react-tips-youre-misusing-the-react-useeffect-hook-probably</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Fri, 06 Jan 2023 03:21:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/cEeEtjedNls/upload/ab75474b96260a91fb836ba5d5ec8674.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is def one of the most common mistakes I've seen in both personal and enterprise applications.  </p>
<p>The useEffect hook exists to sync an external system (i.e. network, DOM) to your React application. That means when you're useEffect'ing to:<br />1. Adjust state or props when a certain value changes (in state or props)<br />2. Replicate legacy class based lifecycle methods  </p>
<p>you're just doing it wrong.  </p>
<p>With awesome packages like TanStack Query (React Query) &amp; SWR you don't even need a useEffect to fetch data.  </p>
<p>If you want to learn more about useEffect check out the new beta documentation on it: <a target="_blank" href="https://beta.reactjs.org/learn/you-might-not-need-an-effect">https://beta.reactjs.org/learn/you-might-not-need-an-effect</a></p>
]]></content:encoded></item><item><title><![CDATA[What I learned from Extreme Programming: Explained by Kent Beck]]></title><description><![CDATA[I walk through the principles and practices of Extreme Programming (XP) by Kent Beck and share my thoughts.]]></description><link>https://blog.reilly.dev/what-i-learned-from-extreme-programming-explained-by-kent-beck</link><guid isPermaLink="true">https://blog.reilly.dev/what-i-learned-from-extreme-programming-explained-by-kent-beck</guid><category><![CDATA[xp]]></category><category><![CDATA[agile]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Tue, 03 Jan 2023 19:11:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/65427d8ba662d988e6382dfe8ed968f9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-goodbye-waterfall-hello-agile">Goodbye Waterfall hello Agile</h2>
<p>This book, when it came out in the 90s, was extremely controversial. Agile was beginning to take serious hold as companies and programmers were fed up with the shortcomings of the Waterfall* methodology.</p>
<p>* Waterfall was characterized by a lengthy planning period where the project is planned from start to finish. It was extremely costly and inflexible when business requirements changed (which they often do)</p>
<p>There are two main flavors of Agile - Scrum and XP. Scrum of course is the more popular and is being used by many companies.</p>
<h2 id="heading-what-is-extreme-programming-xp">What is Extreme Programming (XP)?</h2>
<p>To start what even is Extreme Programming (XP)? In short, it takes all of the best practices that we know work - to the EXTREME. Here's an excerpt to highlight some of the ideas behind it:</p>
<blockquote>
<ul>
<li><p>If code reviews are good, we’ll review code all the time (pair programming).</p>
</li>
<li><p>If testing is good, everybody will test all the time (unit testing), even the customers (functional testing).</p>
</li>
<li><p>If design is good, we’ll make it part of everybody’s daily business (refactoring).</p>
</li>
<li><p>If simplicity is good, we’ll always leave the system with the simplest design that supports its current functionality (the simplest thing that could possibly work).</p>
</li>
<li><p>If architecture is important, everybody will work defining and refining the architecture all the time (metaphor).</p>
</li>
<li><p>If integration testing is important, then we’ll integrate and test several times a day (continuous integration).</p>
</li>
<li><p>If short iterations are good, we’ll make the iterations really, really short - seconds and minutes and hours, not weeks and months and years (the planning game).</p>
</li>
</ul>
</blockquote>
<p>Some of these ideas are as old as programming itself but Kent warns that the XP response to these ideas WILL be counterintuitive and "extreme."</p>
<h2 id="heading-4-values-of-xp">4 Values of XP</h2>
<p>XP is defined by its 4 values:</p>
<ul>
<li><p><strong>Communication</strong> - since failures in projects are typically linked to under-communication let's communicate as much as possible with pair programming, unit testing, and task estimation.</p>
</li>
<li><p><strong>Simplicity</strong> - instead of building something complicated today that's potentially never going to be used - opt to keep things simple today and change things that need to be changed tomorrow.</p>
</li>
<li><p><strong>Feedback</strong> - there is a constant feedback loop - every minute when programmers are writing unit tests they get responses from the system. Customers are writing functional tests. The progress of the team is tracked constantly. Most importantly programmers get constant feedback from pair programming and reviewing code together.</p>
<p>  🔥 Fav quote from this section:</p>
<blockquote>
<p><em>Writing the test gives you a focus for just how simple the system can be—until the tests run, you're not done, and when the tests all run, you're done.</em></p>
</blockquote>
</li>
<li><p><strong>Courage</strong> - Acting on Simplicity, constant Feedback, and Simplicity, teams are very close-knit and make courageous decisions together. One person may have a crazy idea that takes courage to implement. The team may decide that a certain decision they made needs to be scrapped - it takes courage to recognize and act on it.</p>
</li>
</ul>
<h2 id="heading-12-practices-of-xp">12 Practices of XP</h2>
<p>Based on the 4 principles from above we get these 12 practices that help maintain these 4 principles:</p>
<ul>
<li><p><strong>Rapid Feedback</strong> - the faster you get stimulus to an action the quicker you can judge and adapt accordingly. For programmers let's do this as quickly as possible: let's get feedback, respond, and put it back into the project to make it better.</p>
</li>
<li><p><strong>Assume Simplicity</strong> - <em>"Treat every problem as if it can be solved with ridiculous simplicity."</em> This is where things get counterintuitive though! We're taught to prepare for the future. But we have to solve today's problems to the best of our ability (with testing, refactoring, and communication) and trust that we can handle complexity in the future.</p>
</li>
<li><p><strong>Incremental Change</strong> - Do everything in small steps! Adoption of TDD, designing, adapting team for growth, plans, etc.</p>
</li>
<li><p><strong>Embracing Change</strong> - <em>"The best strategy is the one that preserves the most options while actually solving your most pressing problem."</em></p>
</li>
<li><p><strong>Quality Work</strong> - Do your damnedest and you'll get a lot out of it. If there's no quality - "... you don't enjoy your work, you don't work well, and the project goes down the drain."</p>
</li>
<li><p><strong>Teach learning</strong> - There's a lot of room for flexibility - some practices will be forced and certain, and others are looser as the team tries to find the best solution. Teach individuals strategies to find solutions.</p>
</li>
<li><p><strong>Small initial investment</strong> - You can't throw a ton of money into a project initially and expect it to take off. Things need to start slow. There need to be clearly defined responsibilities where productivity is high and people feel that they're killing it.</p>
</li>
<li><p><strong>Play to win</strong> - Kent claims that most software development he sees is played "Not to lose." Losing is characterized by a lot of meetings, and development "by the book" where people are following practices that inevitably fail but are covering their asses to avoid being blamed.</p>
<p>  <em>"Software development played to win does everything that helps the team to win and doesn't do anything that doesn't help to win."</em></p>
</li>
<li><p><strong>Concrete experiments</strong> - XP is characterized by a lot of experimentation - tweaking the design, changing team dynamic, etc. - if there is no baseline testing and performance measurement there's a chance the team is hurting itself.</p>
</li>
<li><p><strong>Open, honest communication</strong> - Teams should be prepared for honest, open feedback and handle it well. They need to be able to discuss problems in the code written by people on the team, they need the freedom to express fears, frustrations, and anger, and get total support. There should also be an open discussion between the business and management with no fear of delivering bad news.</p>
</li>
<li><p><strong>Work with people's instincts, not against them</strong> - XP works with people's short-term interests by heavily involving them on a winning team, with tons of interactions with other members, and the freedom to create and develop kickass software. This is what makes XP work.</p>
</li>
<li><p><strong>Accepted responsibility</strong> - Instead of being told what to do on the team, team members willingly accept responsibility for things that benefit the team.</p>
</li>
<li><p><strong>Local adaptation</strong> - Kent emphasizes that XP doesn't mean that he gets to decide how your team develops - that's up to you! It's up to you to be scientific about the processes you implement, measure, tweak and adjust over and over.</p>
<p>  i.e. Remote teams would look very different doing XP than a full-time in-office team</p>
</li>
<li><p><strong>Travel light</strong> - Kent compares the team to intellectual nomads. They're constantly shifting directions when business requirements change, or when the team moves in a new direction. They only carry what produces value for customer - "tests and code."</p>
</li>
<li><p><strong>Honest measurement</strong> - Choose measurements that best benefit everyone. LOC is a useless measurement.</p>
</li>
</ul>
<h2 id="heading-4-basic-activities">4 Basic Activities:</h2>
<p>Kent explores the basic activities of software engineering: coding, testing, listening and designing.</p>
<p>He says:</p>
<blockquote>
<p><em>So you code because if you don't code, you haven't done anything. You test because if you don't test, you don't know when you are done coding. You listen because if you don't listen you don't know what to code or what to test. And you design so you can keep coding and testing and listening indefinitely. That's it. Those are the activities we have to help structure:</em></p>
</blockquote>
<ul>
<li><p><em>Coding</em></p>
</li>
<li><p><em>Testing</em></p>
</li>
<li><p><em>Listening</em></p>
</li>
<li><p><em>Designing</em></p>
</li>
</ul>
<h2 id="heading-practices-of-xp">Practices of XP</h2>
<ul>
<li><p><strong>The Planning Game</strong> - Quickly determine the scope of the next release by combining business priorities and technical estimates. As reality overtakes the plan, update the plan.</p>
</li>
<li><p><strong>Short Releases</strong> - Ship the "most valuable business requirements" in small releases.</p>
</li>
<li><p><strong>Metaphor</strong> - A "10,000-meter view of the system." Every XP project is guided by a metaphor to quickly understand the relationship between elements in the project.</p>
</li>
<li><p><strong>Simple Design</strong> - The right design is one that:</p>
<ul>
<li><p>Runs all the tests.</p>
</li>
<li><p>Has no duplicated logic. Be wary of hidden duplication like parallel class hierarchies.</p>
</li>
<li><p>States every intention important to the programmers.</p>
</li>
<li><p>Has the fewest possible classes and methods.</p>
<p>  Kent mentions the modern advice "Implement for today, design for tomorrow." He emphasizes - knowing the future is quick to change - from business requirements to team ideas evolving - writing functionality because we think we might need it is crazy. The XP approach is simple: "put in what you need when you need it."</p>
</li>
</ul>
</li>
<li><p><strong>Testing</strong> - Since programmers and customers write tests, unit and functional respectively, the confidence these tests produce become a part of the program they're creating. This makes it more capable of handling change.</p>
<p>  He emphasizes you have to begin with tests but not to test every minutia - like every method and other small details- but instead the production methods and things susceptible to break. Let your experimentation and then subsequent intuition guide you.</p>
</li>
<li><p><strong>Refactoring</strong> - Knowing that things change quickly - we want to be able to go into the code and rapidly change things when the time comes. To make things easy to change we constantly are refactoring - making things simpler while keeping tests green. Avoiding writing quick, messy code we instead focus on writing simple code, even though it may take longer to implement.</p>
</li>
<li><p><strong>Pair Programming</strong> - People on the team will constantly pair with different people depending on tasks and who's avaiable. One person is typing the code and the other is thinking strategically - considering the system as a whole, a future test case, and constantly thinking about simplification of the system.</p>
</li>
<li><p><strong>Collective Ownership</strong> - There are two other models of code ownership:</p>
<ul>
<li><p>1. No ownership - people changed whatever part of the code they wanted to suit their needs. This results in a massive codebase that quickly becomes unstable.</p>
</li>
<li><p>2. Individual ownership - sections, or the entire codebase, are owned by one person. Teams had to wait for that person's availability and then were screwed when that person leaves the company because no one understands it.</p>
<p>  Contrastly, in XP everyone owns the code. If a paired team sees an opportunity for improvement they take action and improve everyone's experience.</p>
</li>
</ul>
</li>
<li><p><strong>Continuous Integration</strong> - The team should constantly be integrating their changes into the current release and merge it when tests fully pass (100%) If the tests aren't passing it's time to start over with where it's broken.</p>
</li>
<li><p><strong>40-Hour Week</strong> - Our brains are constantly going to be creative and running, so we need to be fully rested. There shouldn't be 2 weeks of overtime in a row. If there are - that's a symptom of some serious problems that can't be solved with overtime.</p>
</li>
<li><p><strong>On-site customer</strong> - Bring someone into the project who will be the end user of the system being developed. They will be available for questions, resolving disputes, priorities, and testing. This person will result in the project being built quicker. There's an obvious objection from companies with this idea: "We can't afford to dedicate one extra person to your team for this" to which you should respond: "If having the system doesn't bring more value than that one person's productivity then that system shouldn't be built."</p>
</li>
<li><p><strong>Coding Standards</strong> - With constant changes being implemented in code there's a serious risk for problems in the code like different patterns and practices. To combat this XP teams implement standards which are adopted by every team member.</p>
</li>
</ul>
<h2 id="heading-the-case-for-pair-programming">The case for Pair Programming</h2>
<p>Kent emphasizes that pair programming is <strong>not</strong> one person coding while the other just watches, or one person tutoring the other. It's a dynamic interaction with constant communication.</p>
<p>One person strategically views the code based on the bigger picture of the system and actively offers suggestions and comments. The other is implementing the tests first and then coding for the feature at a micro level.</p>
<p>He suggests that the reader view pair programming as two people simultaneously programming. Both people are analyzing, designing and testing. "It is a conversation at many levels, assisted by and focused on a computer."</p>
<p><strong><em>But what about productivity? I can't afford two programmers to work on one task!</em></strong></p>
<p>Kent notes that a pair is more productive than two individuals with their separate work. The resulting code quality is so much higher - it's incomparable.</p>
<p><strong><em>Why Pair Program?</em></strong></p>
<p>It results in a higher code quality that works with the overall system. It often results in code that is dead simple. It helps everyone on the team take ownership of the codebase - understanding how everything works together. It protects the code from external stress. In times of stress, people skip testing (this one time), write a pile of shit just to get a feature in, don't change complex code into simpler code. You think you can do any of that with a partner watching? Not a chance.</p>
<h2 id="heading-testing-the-xp-way">Testing - the XP way</h2>
<p>Everyone knows that they should write more tests (hopefully) but nobody likes doing it - me included!</p>
<p>I love Kent's analogy for XP testing:</p>
<blockquote>
<p><em>Here's what XP testing is like. Every time a programmer writes some code, they think it is going to work. So every time they think some code is going to work, they take that confidence out of the ether and turn it into an artifact that goes into the program. The confidence is there for their own use. And because it is there in the program, everyone else can use that confidence, too.</em></p>
</blockquote>
<p>The idea of confidence becoming a part of the program itself is beautiful.</p>
<p>This confidence enables us to constantly refactor and create without worry of things breaking. When tests are failing it gives insight into a part of the system that is broken and should immediately be resolved by the team!</p>
<p><strong>Why test first before coding?</strong></p>
<p>XP focuses on simplicity. When you write code to make a test pass - the code's direct purpose for it existing - you are forced to keep that code simple into tested chunks.</p>
<p>Testing first ensures that programmers don't make mistakes. When you're building a feature without testing first - you're logically approaching that problem and figuring out how it ties to the business requirements all at once! It works but can lead to messy code. When testing first you lay out your thought process and how it corresponds to the requirements - in the form of tests - that you can complete one manageable piece at a time.</p>
<p>The testing software gives you immediate feedback to indicate your status and how your code is doing in the system: <strong><em>greenlight</em></strong> - "ok I know it works." <strong><em>Red</em></strong> - "okay I need to continue until this passes."</p>
<p><strong>What do you test?</strong></p>
<blockquote>
<p>You should test things that might break. If code is so simple that it can't possibly break, and you measure that the code in question doesn't actually break in practice, then you shouldn't write a test for it. If I told you to test absolutely everything, pretty soon you would realize that most of the tests you were writing were valueless, and, if you were at all like me, you would stop writing them. "This testing stuff is for the birds.</p>
</blockquote>
<p>Kent states that testing is a bet. You assert that the code works a certain way and when it doesn't you have to figure out why it's working unexpectedly because the code is smarter than you.</p>
<p><strong>Who tests?</strong></p>
<ul>
<li><p>Programmers - with unit tests that always run at 100%</p>
</li>
<li><p>Customers - with functional/ acceptance tests, story by story, for the features of the application.</p>
</li>
</ul>
<h2 id="heading-how-to-adopt-xp">How to adopt XP?</h2>
<p>Kent suggests that teams adopt one practice at a team - typically starting with "Testing" and the "Planning Game" due to most projects being plagued with quality and imbalance of power between business and devs.</p>
<p>Here's a guide to adopt XP (from the book):</p>
<ol>
<li><p>Pick your worst problem.</p>
</li>
<li><p>Solve it the XP way.</p>
</li>
<li><p>When it's no longer your worst problem, repeat.</p>
</li>
</ol>
<p><strong>Can XP be adopted for existing teams?</strong></p>
<p>Certainly but it's going to be challenging. Kent says:</p>
<blockquote>
<p>Adopting XP with a new team is a challenge. Adopting it with an existing team and existing code base is even harder.</p>
</blockquote>
<p>Not only do teams have to work on implementing XP one practice at a team, constantly adjust their approach to best fit their team, and get management on board with this new practice, but <strong>also</strong> keep deliverables at an acceptable rate. It's an uphill battle.</p>
<h2 id="heading-my-thoughts">My Thoughts</h2>
<p>I want to create the very best team that I possibly can. I want all of my team members to feel fulfilled in their work, truly enjoying the tight-knit team dynamic, where they can spend more time with their loved ones (40-hour work week), writing scalable code that is quick to adapt to constantly changing business requirements. Ultimately I want to build a team that has the perfect balance between kick-ass, fulfilled, and creative. Practicing XP leads to all of these being fulfilled. Going forward I am adopting XP.</p>
<p>I truly think this book is with your time!</p>
]]></content:encoded></item><item><title><![CDATA[SSR Demystified]]></title><description><![CDATA[tldr; it's not complicated at all 🤫]]></description><link>https://blog.reilly.dev/ssr-demystified</link><guid isPermaLink="true">https://blog.reilly.dev/ssr-demystified</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Fri, 25 Nov 2022 18:52:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/FWhTeWRCeis/upload/v1669398323729/qCW9NeLF7.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Don't let lingo like SSR/ CSR confuse you -- there's really just two <strong>major</strong> ways to serve HTML over an HTTP server in JS - either the server sends the HTML to the client (ssr) or the client generates the HTML for itself (csr/ spa) by using the Web API.</p>
<p>To demystify SSR we are going to look at the world's simplest dynamic SSR example:</p>
<pre><code><span class="hljs-comment">// Let's create a server</span>
<span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;

<span class="hljs-keyword">const</span> app = express();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">generateHTML</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> date = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>();
  <span class="hljs-keyword">const</span> localTime = date.toLocaleTimeString();
  <span class="hljs-keyword">const</span> localDate = date.toLocaleDateString();
  <span class="hljs-keyword">const</span> doc = <span class="hljs-string">`
&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;meta http-equiv="X-UA-Compatible" content="ie=edge"&gt;
    &lt;title&gt;Wow&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;span&gt;Hello World!&lt;/span&gt;
    &lt;span&gt; The date is <span class="hljs-subst">${localDate}</span>&lt;/span&gt;
    &lt;span&gt; It's currently: <span class="hljs-subst">${localTime}</span> &lt;/span&gt;
  &lt;/body&gt;
&lt;/html&gt;
`</span>;
  <span class="hljs-keyword">return</span> doc;
}

<span class="hljs-comment">// Every get request to the '/' page will send the current date and time to the client</span>
app.get(<span class="hljs-string">'/'</span>, <span class="hljs-function">(<span class="hljs-params">req, res</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> doc = generateHTML();
  res.send(doc);
});

<span class="hljs-keyword">const</span> port = process?.env?.PORT ?? <span class="hljs-number">3000</span>;

app.listen(<span class="hljs-number">3000</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`🚀 Live on http://localhost:<span class="hljs-subst">${port}</span>`</span>);
});
</code></pre><p>That's it. </p>
]]></content:encoded></item><item><title><![CDATA[Understanding React ⚛ - ep.1]]></title><description><![CDATA[tldr; it's costly to define components inside other components]]></description><link>https://blog.reilly.dev/understanding-react-ep1</link><guid isPermaLink="true">https://blog.reilly.dev/understanding-react-ep1</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Mon, 19 Sep 2022 17:10:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/r3XvSBEQQLo/upload/v1662950089098/I8EmhTOah.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Take a look at this code below. It's a contrived example where we want the user to be able to enter some data into the email and password fields. But something isn't quite right. Can you spot the mistake?</p>
<pre><code><span class="hljs-keyword">import</span> <span class="hljs-title">React</span>, { <span class="hljs-title">useState</span> } <span class="hljs-title"><span class="hljs-keyword">from</span></span> <span class="hljs-string">"react"</span>;

const Parent <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
  const [email, setEmail] <span class="hljs-operator">=</span> useState(<span class="hljs-string">""</span>);
  const [password, setPassword] <span class="hljs-operator">=</span> useState(<span class="hljs-string">""</span>);

  const Child <span class="hljs-operator">=</span> ({ value, onChange, <span class="hljs-keyword">type</span> }) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
    <span class="hljs-keyword">return</span> (
      <span class="hljs-operator">&lt;</span>input
        value<span class="hljs-operator">=</span>{value}
        <span class="hljs-keyword">type</span><span class="hljs-operator">=</span>{<span class="hljs-keyword">type</span>}
        placeholder<span class="hljs-operator">=</span><span class="hljs-string">"Email"</span>
        onChange<span class="hljs-operator">=</span>{(e) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> onChange(e.target?.<span class="hljs-built_in">value</span>)}
      <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
    );
  };

  <span class="hljs-keyword">return</span> (
    <span class="hljs-operator">&lt;</span>form<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>label<span class="hljs-operator">&gt;</span>
        Email
        <span class="hljs-operator">&lt;</span>Child value<span class="hljs-operator">=</span>{email} <span class="hljs-keyword">type</span><span class="hljs-operator">=</span>{<span class="hljs-string">"email"</span>} onChange<span class="hljs-operator">=</span>{setEmail} <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span>label<span class="hljs-operator">&gt;</span>
        Password
        <span class="hljs-operator">&lt;</span>Child value<span class="hljs-operator">=</span>{password} <span class="hljs-keyword">type</span><span class="hljs-operator">=</span>{<span class="hljs-string">"password"</span>} onChange<span class="hljs-operator">=</span>{setPassword} <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
      <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>label<span class="hljs-operator">&gt;</span>
    <span class="hljs-operator">&lt;</span><span class="hljs-operator">/</span>form<span class="hljs-operator">&gt;</span>
  );
};

export default Parent;
</code></pre><p>Still not seeing what's wrong? Check out the example on this <a target="_blank" href="https://codesandbox.io/s/hardcore-hamilton-ej18vo?file=/src/App.js">React playground</a> to demo it. </p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>I've create a component inside of another component and that's a <strong>BIG</strong> no-no in React &amp; it's created some unexpected behavior (a bug) in this application.</p>
<p>To understand WHY this bug exists let's take a step back and make sure we're on the same page about the fundamentals of React:</p>
<h2 id="heading-jsx-andamp-reactcreateelement">JSX &amp; React.createElement</h2>
<p>Thanks to JSX, we're able to use some really familiar syntax to describe our UI, like in the example above. But behind the scenes we know that the JSX becomes React.createElement (which is why we always need to import React from 'react' in every file that uses JSX). </p>
<p>Here's what the return value of React.createElement is for our Parent component from the example above: </p>
<pre><code><span class="hljs-attr">type:</span> <span class="hljs-string">ƒ</span> <span class="hljs-string">Parent()</span> {}
<span class="hljs-attr">key:</span> <span class="hljs-literal">null</span>
<span class="hljs-attr">ref:</span> <span class="hljs-literal">null</span>
<span class="hljs-attr">props:</span> <span class="hljs-string">Object</span>
<span class="hljs-attr">_owner:</span> <span class="hljs-literal">null</span>
<span class="hljs-attr">_store:</span> <span class="hljs-string">Object</span>
</code></pre><p><em>Keep a close eye on the type property here - React will use this later</em></p>
<h2 id="heading-initial-render-fiber">Initial Render / Fiber</h2>
<p>On the initial render React begins at the entry point defined in the application (typically index.js) and recursively goes through each component and creates a component tree. </p>
<p>The first time React encounters a component React keeps a record of all of the information that the component needs - i.e. props, state, &amp; the <strong>type</strong> - in a data object called a <em>fiber</em>. This allows the important data like props and state to persist through every render.</p>
<p>When the component instance no longer exists React will destroy the fiber instance.</p>
<h2 id="heading-the-re-rendering-process">The re-rendering process</h2>
<p>On every re-render React iterates over the fiber instances (which is each component instance) and returns a component tree - which describes the UI changes that will happen. </p>
<p>A couple important notes: </p>
<ul>
<li><p>A React component can re-render because of a change in state / update to context value/ change in props</p>
</li>
<li><p>When a React component re-renders it will cause ALL of the children components to re-render also.</p>
</li>
</ul>
<h2 id="heading-reconciliation">Reconciliation</h2>
<p>On the first render React has to paint the entire UI described by the component tree to the DOM, there is no choice. </p>
<p>On subsequent renders, React recursively travels through the component tree and checks if the same element is being rendered at that exact spot (through the Fiber object.) If the element at a given spot is the same (by checking the type of that element using strict equality ===) the element does not change. However, if an element's types are different React will destroy that component and all its children in component tree (which removes the fiber instances, unmounts the components, and destroys the DOM nodes) and create a new tree with new component instances and re-paint the DOM with the new calculate UI - this process is costly but essential for React.</p>
<h2 id="heading-back-to-the-example">Back to the example</h2>
<p>Now that we've covered what React is doing let's look through the code example from above one step at a time:</p>
<p>Our entry point is defined in index.js. React renders the App component - meaning that it goes through the exported component defined in App.js. We are aliasing Parent as App but they are the exact same component.</p>
<p>The JSX in the Parent component is converted into React.createElement calls. React creates fibers for each of the components: Parent and Child in this case. </p>
<p>On the first render React goes through the parent component line by line. Since this is the first time this component is rendered React creates a fiber for that component and keeps track of important things like the state and type (the type is literally <em>type: ƒ Parent() {}</em>) On line 8 when it reaches the Child component React does the same for the Child component. It's type is  ƒ Child() {}.</p>
<p>Our parent component describes the UI, in this case a form with a label and then a Child component. Since a Child component is not valid HTML React goes to that Child component to see what it returns (this is done recursively until there's just HTML.) </p>
<p>React paints that to the DOM. </p>
<p>We type our email "d..." Wait it doesn't let us type anymore? The input lost focus?</p>
<p>Since the state for the Parent component was updated React triggers a re-render for both that component and all of it's children. When the parent re-renders React once again travels through the component line by line. React compares the type of the component and sees that the type is the same - since that type is the same in the fiber object. Next on line 8 the Parent component says that it creates a new component called Child. React knows that previously a component called Child exists in this position of the component tree. It compares their types (the one from the newly created component and one from the fiber) which appear to be the same BUT can you catch the issue in the type comparison?</p>
<pre><code>ƒ Child() {} <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> ƒ Child() {}
</code></pre><p>No two functions, or non primitive values, will ever be the same since they're referencing different things.</p>
<p>Since this is false, React will destroy the existing Fiber of the component and recursively destroy all DOM nodes.</p>
<p>The new component instance is passed the new prop value from the parent and since the value of the input is set to the passed prop value it shows that value and the input has no focus. </p>
<p>If you really want to see it for yourself add a useEffect inside like this:</p>
<pre><code>const Child <span class="hljs-operator">=</span> ({ value, onChange, <span class="hljs-keyword">type</span> }) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
   useEffect(() <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> {
      console.log(<span class="hljs-string">"Component instance created"</span>);
    }, []);
    <span class="hljs-keyword">return</span> (
      <span class="hljs-operator">&lt;</span>input
        value<span class="hljs-operator">=</span>{value}
        <span class="hljs-keyword">type</span><span class="hljs-operator">=</span>{<span class="hljs-keyword">type</span>}
        placeholder<span class="hljs-operator">=</span><span class="hljs-string">"Email"</span>
        onChange<span class="hljs-operator">=</span>{(e) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> onChange(e.target?.<span class="hljs-built_in">value</span>)}
      <span class="hljs-operator">/</span><span class="hljs-operator">&gt;</span>
    );
  };
</code></pre><p>That useEffect will be called every time you type in the input.</p>
<h2 id="heading-the-solution">The Solution</h2>
<p>You can see how costly all of this is! So how do we fix this?</p>
<p>The quickest change is by simply moving the Child component outside of the parent component (either above or below.) This prevents the creation and deletion of both Fiber objects and DOM nodes on every render.</p>
<h2 id="heading-end">End</h2>
<p>Thanks so much for reading this! I really hope that this taught you something new. If you want to reach out I'm on Twitter @reillyjodonnell</p>
<p>Sources used for research &amp; shaped my understanding of this process:</p>
<p>https://reactjs.org/docs/reconciliation.html#elements-of-different-types
https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/
https://www.youtube.com/watch?v=7YhdqIR2Yzo</p>
]]></content:encoded></item><item><title><![CDATA[React Essentials: Props]]></title><description><![CDATA[They're kind of a big deal]]></description><link>https://blog.reilly.dev/react-essentials-props</link><guid isPermaLink="true">https://blog.reilly.dev/react-essentials-props</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Reilly O'Donnell]]></dc:creator><pubDate>Tue, 28 Sep 2021 15:59:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1632843649090/6ese0bjJO.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="props-explained">Props - explained</h2>
<p>The React docs defines props as </p>
<blockquote>
<p>When React sees an element representing a user-defined component, it passes JSX attributes and children to this component as a single object. We call this object “props”.</p>
</blockquote>
<p>They also use the following code snippet as an example</p>
<pre><code><span class="hljs-keyword">const</span> element = <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Welcome</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"Sara"</span> /&gt;</span></span>;
</code></pre><p>Here we see that the "user-defined component" is Welcome and the object, or props, is called name with the value of Sara. </p>
<p>Let's see another example below ⬇️ </p>
<h2 id="props-example">Props - example</h2>
<p>To start we have a functional component as shown below:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> &gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><p>As we can see this component doesn't do anything, yet! </p>
<p>Let's add some magic 🪄  by passing the component properties, or props.</p>
<h3 id="passing-props">Passing Props</h3>
<p>Below we create a variable called message and assign it a string of text.</p>
<p><strong>Now the cool part 😎 </strong></p>
<p>Attach an object with any name (we use "secret" here) to the component as shown below</p>
<pre><code><span class="hljs-keyword">var</span> message = <span class="hljs-string">"Props is now showing! Awesome!"</span>;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> <span class="hljs-attr">secret</span>=<span class="hljs-string">{message}</span> /&gt;</span></span>
</code></pre><p>Now notice here, unlike the example from the React docs above, message is surrounded by curly braces. This is because the value is JavaScript and must be enclosed in curly braces per JSX rules.</p>
<p>Similarly we could have just done</p>
<pre><code><span class="hljs-tag">&lt;<span class="hljs-name">MyComponent</span> <span class="hljs-attr">secret</span>=<span class="hljs-string">"Props is now showing! Awesome!"</span> /&gt;</span>
</code></pre><p>You've just successfully passed props! 🎉 </p>
<p>Now we need to access it within the component, MyComponent.</p>
<h3 id="accessing-props">Accessing Props</h3>
<p>To access the props we need to pass an optional parameter to the functional component</p>
<p>This parameter can be any name you want - but it's HIGHLY advised to use the word props</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> &gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><p><strong>Great - now how do we access it?</strong></p>
<p>if we console.log(props) we get:</p>
<pre><code><span class="hljs-selector-tag">-</span>&gt; {<span class="hljs-attribute">secret</span>: <span class="hljs-string">"Props is now showing! Awesome!"</span>}
</code></pre><p>Just as we expected props is in the form of an object. To access it use the dot notation (props.secret)</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">MyComponent</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> &gt;</span>
      {props.secret}
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}
</code></pre><p><strong>Notice again that we didn't say props.secret - we used {props.secret}</strong></p>
<p><em>Reminder in case you missed it earlier: this is because in React we use JSX and by using curly braces we are saying we want to display JavaScript code.</em></p>
<h4 id="important-to-note">Important to note</h4>
<p>Props is read-only. Meaning when we access props in the component we are not allowed to assign props a new value within the component. </p>
<p>If we want to assign props a new value it MUST be changed outside the component.</p>
<h3 id="recap">Recap</h3>
<p>Now we have successfully passed props and accessed it in the component! 🥳</p>
<p>In the next article we will look at another fundamental topic: State</p>
]]></content:encoded></item></channel></rss>