<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Greg Banks on Medium]]></title>
        <description><![CDATA[Stories by Greg Banks on Medium]]></description>
        <link>https://medium.com/@gbanks1438?source=rss-526395afb84b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*u3zaMUEBJCQ2WoNC</url>
            <title>Stories by Greg Banks on Medium</title>
            <link>https://medium.com/@gbanks1438?source=rss-526395afb84b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 11:52:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gbanks1438/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scaffolding a React/RoR Monorepo]]></title>
            <link>https://medium.com/@gbanks1438/scaffolding-a-react-ror-monorepo-7303a0f65a06?source=rss-526395afb84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7303a0f65a06</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[github]]></category>
            <dc:creator><![CDATA[Greg Banks]]></dc:creator>
            <pubDate>Tue, 03 Jan 2023 16:42:30 GMT</pubDate>
            <atom:updated>2023-01-03T16:55:55.840Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlMurvm4GKGEzNQL4pyK8Q.jpeg" /></figure><p>Setting up a React &amp; Ruby on Rails monorepo scaffold can make spinning up your next project easier and faster. You’ll be able to jump right into coding and spend less time setting everything up.</p><p>This instructional uses PostgreSQL as the relational database manager instead of MySQL. There are also other Gem files that can be enabled to use dev tools like Pry, or to add site authentication with bCrypt.</p><p>It’s very important to ensure your environment is set up before getting started. You should run the CLI commands below to confirm what versions are installed before proceeding.</p><p>$ruby --version</p><p>$rails --version</p><p>$postgres --version</p><p>Walkthrough:</p><ol><li>open Terminal and navigate to desired directory</li><li>$mkdir project-scaffold {*to create a project subdirectory}</li><li>$cd project-scaffold {*go into the project-scaffold folder}</li><li>$npx create-react-app frontend-name</li><li>$rails new backend-name - -database postgresql</li><li>$code . {*to open in VSC}</li><li>in VSC, add an “images” folder inside the src folder</li><li>confirm in config/database.yml and Ruby Gemfiles that all dependencies are installed and enabled (*bcrypt, spring, Rspec, etc)</li><li>$cd frontend-name {*go into the React folder}</li><li>$ls -la {*to check for git files and use [$rm -rf] to clear them if present}</li><li>$npm start {*to start the React app on local host port 3000}</li><li>in VSC, edit the React welcome message by navigating to src/App.js</li><li>open a new Terminal window</li><li>$cd ./project-scaffold/backend-name {*go back into the main project folder, then into the Rails folder}</li><li>$ls -la {*to check for git files and use [$rm -rf] to clear them if present}</li><li>$bundle exec rails db:prepare {*to create the application database and initialize the schema}</li><li>$rails generate controller Welcome index {*to create a welcome page}</li><li>edit the config/routes.rb file to add the line from inside the bracket [root ‘welcome#index’]</li><li>change ports in the config/puma file to 3001</li><li>$bundle exec rails server {*to start the rails app on local host port 3001}</li><li>in VSC, edit the Rails welcome message by navigating to app/views/welcome/index.html.erb</li><li>open a third Terminal window</li><li>$cd ./project-scaffold {*go to the main project folder}</li><li>make a new GitHub repository for your project and initialize it</li><li>use git commands to add files, commit the changes with a comment, and then push</li></ol><p>Project workflow &amp; goals:</p><ul><li>Work on the backend database formatting and relationships</li><li>db:create, db:migrate, &amp; db:seed</li><li>Use Postgres as the object-relational database manager</li><li>Set up the Models, Views, &amp; Controllers</li><li>Set up config/routes.rb</li><li>Edit config/database.yml as needed</li><li>Change favicon.ico if desired</li><li>Move on to the frontend and work on a landing page</li><li>Build out a functional website or application using React, HTML, CSS, and Javascript</li></ul><p>Visit my GitHub page to clone down this repository and skip forward to coding your own full-stack project, or edit the scaffold to meet your needs and then use it as a template for future projects!</p><p><a href="https://github.com/Gbanks1438/scaffold-template">https://github.com/Gbanks1438/scaffold-template</a></p><p>Additional Resources:</p><p><a href="https://reactjs.org/docs/create-a-new-react-app.html">https://reactjs.org/docs/create-a-new-react-app.html</a></p><p><a href="https://docs.bitnami.com/aws/infrastructure/ruby/get-started/create-rails-app/">https://docs.bitnami.com/aws/infrastructure/ruby/get-started/create-rails-app/</a></p><p><a href="https://guides.rubyonrails.org/getting_started.html">https://guides.rubyonrails.org/getting_started.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7303a0f65a06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[‘Etsy moves to Preact’ - and other sentences I know how to say in Italian.]]></title>
            <link>https://medium.com/@gbanks1438/etsy-moves-to-preact-and-other-sentences-i-know-how-to-say-in-italian-6bf2cc204735?source=rss-526395afb84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf2cc204735</guid>
            <category><![CDATA[preact]]></category>
            <category><![CDATA[etsy]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Greg Banks]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 17:00:55 GMT</pubDate>
            <atom:updated>2022-02-03T17:00:55.184Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncIBkRAVof2qRVEJdOwxhw.png" /></figure><p>Actually, that’s a bit of a lie because the first parts not even Italian, and I also don’t even know how to speak Italian…but I did learn that the company recently upgraded their seller facing pages to use Preact version 10. Some context for the reader: Etsy maintains two major product stacks overall. One stack is for the buyers using PHP on the server with jQuery/vanilla JS on the client, and the other has the seller pages and some internal tools using React SPAs with a little html for the front-end.</p><p>Ben Sangster, an Etsy Software Engineer, detailed reasons for their decision <a href="https://github.com/mq2thez/blog/blob/main/upgrade-react-etsy/preact-vs-react.md"><em>on his github page</em></a>. He explains <em>‘Upgrading React from v15.6.2 brings significant performance and bundle size improvements while also providing a lot of new features. Migrating from React v15 to React v16 is a major undertaking. There are a number of backwards incompatible changes which must occur within the codebase in order to enable these improvements’.</em> Their other choice was to upgrade from React Version 15.6 to a modern 16.x version, complete several large migrations, and do a lot more work to find and update the required dependencies and then also fix issues with the codebase from things that had to be rolled back or replaced. Overall, it was obviously decided that it would be faster and easier to modernize the stack with Preact than update what they had, have QA throughly test it, and then patch issues, and hopefully not create a very bad day for the customers and CS team.</p><p>He goes on to say <em>‘At the same time, there is a growing recognition within the web development community that the large JS bundle size of React’s libraries negatively impacts users, for all that it can make code significantly easier to understand and maintain over time. The FES team has already adopted </em><a href="https://preactjs.com/"><em>Preact</em></a><em>, a tiny drop-in alternative to React which is API compatible and would not involve a major rewrite to adopt in our seller tools’ . </em>This supports that moving over codebase for these seller-facing pages to Preact would end the need for managing a fragmented stack. It’s a practical gain for the company logistically since it’s easier to manage shared concerns. This is especially helped by the fact that Preact is lighter and can be ‘dropped in’ as they say in such a flexible manner to make it an efficient and clean way to manage their stack.</p><h3>Benefits for Etsy’s decision:</h3><blockquote><strong>Smaller library size </strong>— “The Preact v10.4.2 bundle is 6KB gzipped, vs 38.5KB gzipped for React v16.13.1.”</blockquote><blockquote><strong>Consistency with Etsy’s front-end team</strong> — “The <a href="https://github.com/mq2thez/blog/blob/main/upgrade-react-etsy/preact-vs-react.md#fes">FES</a> team has already moved forward with a decision to investigate Preact-based development in the buyer-side of Etsy’s codebase with SSR. Choosing React over Preact for seller tools would increase the fragmentation of our development environment and make our lives harder.”</blockquote><blockquote><strong>Lowered risk associated with migrating</strong> — “The migration to Preact v10.4.2 would be significantly easier and require far fewer steps to complete, due to Preact’s emphasis on compatibility with both React v15 and React v16.”</blockquote><blockquote><strong>Less time spent developing older code and fixing issues </strong>— “There do not seem to be any major obstacles from a developer tooling perspective to adopting Preact.”</blockquote><h3>What is Preact?</h3><p>Ben states — <em>‘Preact is an alternate implementation of the React API. Migrating from React to Preact is a fairly straightforward process — this would not entail a huge rewrite or significant work from any other teams’.</em></p><p>According to the Preact website, they aim to provide the same type of experience as using React, however achieving it in a different way. The motto to remember is “Small and focused”, so it should work with everything you need without loading the app down with stuff you won’t be using. This means that it is not a 1:1 comparison, some features work differently, or they may not be available. They post <em>‘Preact is not intended to be a reimplementation of React. There are differences. Many of these differences are trivial, or can be completely removed by using preact/compat, which is a thin layer over Preact that attempts to achieve 100% compatibility with React.’</em></p><p><a href="https://preactjs.com/guide/v10/differences-to-react">Differences to React - Preact Guide</a></p><p>It’s important to note how there are different concerns for each development team and that this approach may not necessarily be the best for all companies. Reviewing the specific differences between the versions of each stack and completing any company documentation, like Etsy’s ‘Orange Docs’ for peer review, are really important steps to take first. As Ben shows in his blog, there had to be considerations even with React for replacing incompatible dependencies and then needing to find, update, or uninstall different libraries to prevent conflicts if they modernized the codebase to v16. That could understandably take a lot of time. Changing over to Preact still had to be carefully considered for each of the versions that could apply and how they change compatibility with everything else in use. As we find, they settled on Preact v10 as the best suited replacement.</p><h3>Weighing the tradeoffs</h3><p>It seems this change was not necessarily an easy unanimous ‘Yes’ decision among the team. There are some realistic concerns over using Preact vs React, specifically because React is so prevalent in development, and it’s backed by Facebook, that we know it has plenty of support given it’s size. A strength that is also in this case part of it’s weakness.</p><p><em>‘Because React is the “standard” tool and Preact is responsible for maintaining its own compatibility, a lot of the discussion around Preact involves compatibility with existing libraries and code. In general a lot of discussion of “Preact compatibility” is somewhat complicated. There are two types of Preact development — one in which the React compatibility layer is not added, and one in which it is.</em></p><p><em>Preact v10 merged the compatibility layer into the main Preact stack, and a lot of React-based libraries appear to have gained significant improvements in compatibility because of this.’</em></p><p>Yet that very last part shows that the chance paid off and the Preact v10 stack improved the overall compatibility, thus less that had to be changed in development. Ben states, <em>‘Preact emphasizes compatibility with both the v15 and v16 React APIs’. </em>That’s certainly great news to learn from research when you know the alternative is going to involve migrating several packages and needing to make significant changes to the codebase.</p><p>This doesn&#39;t change the fact that you still need to plan for the future, so is the dollar they saved worth it in the long run if Preact can’t survive? We see that Ben discusses the aspects of what would remain compatible with future updates and reflects on Preact’s untested underdog origins as a publicly funded project, one that might not necessarily establish itself as a powerhouse rival in the end.</p><h3>Future Compatibility</h3><p><strong>Typescript support</strong> — not expecting any issues based on the blog documentation.</p><p><strong>Suspense</strong> — While this is experimental within React, it does have even less support in Preact. That said, since adoption would require significant changes to the codebase, Ben makes it clear that it’s not possible to support it without a large-scale efforts.</p><p><strong>GraphQL:</strong></p><p>@apollo/client might have some support for Preact. Nothing specific is mentioned in the blog.</p><p>urql has explicit support for Preact.</p><p>Ben writes<em> ‘As true clientside GraphQL support is not available, it&#39;s not yet possible to say definitively that we would have full support. That said, having identified two libraries which would provide what we need (depending on what route we eventually choose in terms of using GraphQL on the client) seems sufficient to say that this is not a blocker’.</em></p><h3>On reflection of the business end of things</h3><p>Ben seems to be fully aware of Preacts less mature business platform and views it as one potential pitfall in the long term. This is wise since companies trend to go with the tried and true methods, and doing something new can be a risk that should be well thought out. He’s calculated how Preact could have a very bright future, but right now it’s only speculation as to how long the project could be viable considering it functions off donations. He writes <em>‘One concern with choosing a library is whether we can rely on it to remain supported. React is actively supported by Facebook, and that seems unlikely to change in the next few years. Preact is actively supported by donations and maintained by a passionate group of developers, but if we choose Preact we also need to be prepared to migrate from Preact to React if the library stops receiving new development or if we find a showstopping feature which requires React to implement’.</em></p><h3>Final reflection</h3><ul><li>Preact is API compatible with React —meaning that any changes using Preact would not be incompatible if migrating to React at a later date.</li><li>Thanks to Preact’s compatibility there are less code updates that would need to be done.</li><li>Refactoring while on Preact would make it easy to move the codebase to an entirely React v16-compatible API at a later time, if needed.</li><li>Migrating the codebase to Preact and updating all of the API to then move to React would cause unnecessary churn with low-level libraries.</li></ul><p>It’s probably not going to start a big trend in companies moving away from React, especially just given it’s wide adoption of use, but it’s very interesting to see how major companies are using these libraries. It’s also really cool to know this is a direct parallel to things I’ve learned while studying at FlatIron School since the workflow wouldn&#39;t really change for a Software Engineer on a full stack team that’s adopted Preact. And, as the internet works to become less centralized and more balanced to fair use, projects like Preact could become stronger backbones of our daily use of the internet by reshaping some of the biggest sites we use everyday.</p><p>I think that it also shows how important it is for developers to remain part of a community and to consider how even a side project can grow into a larger idea that can be developed and managed in a shared way and have a very real and positive impact. As that community grows and the idea gains traction, more funding can be gained to push development and support even further. Now with a big name like Etsy signing on and committing to full stack adoption, it is less far fetched to think Preact could survive the 3–4–5 years that they were envisioning when considering this library over React and the cost and effort trade off to do all this work.</p><p>I’ll be sticking to React for my own projects for now, but always interested to see how things are changing in the industry. Thanks for reading my blog! Check the original post on Github for a more in depth analysis of the changes and considerations that the Etsy made.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf2cc204735" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Request-Response Cycle]]></title>
            <link>https://medium.com/@gbanks1438/request-response-cycle-5ad33cd42122?source=rss-526395afb84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad33cd42122</guid>
            <category><![CDATA[http-response]]></category>
            <category><![CDATA[http-request]]></category>
            <dc:creator><![CDATA[Greg Banks]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 15:44:09 GMT</pubDate>
            <atom:updated>2022-01-10T15:44:09.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*smLrriyaHX1vEzVTtNZU2A.png" /></figure><p>We’ve all heard the term HTTP, and many of us are now familiar with how it is the backbone of the internet, but what exactly is <strong>Hypertext Transfer Protocol </strong>and how do we use it to help webpages communicate with our devices? Firstly, we need a webpage for consideration. You will need to reference this website using its URL/URI, the <strong>Uniform Resource Locator/Identifier.</strong> We are all familiar with typing into our browsers everyday a clean and abbreviated form (ex: Twitter.com) in order to point to an IP address. while we could go and grab the full URL, our modern web browsers know to fill in the important details like “https://www.” before loading the site.</p><p>A <strong>DNS,</strong> Domain Name System, converts our human words into a valid IP address if a site is registered with that keyword (think about it, you never type an IP address to visit Twitter, you use their shorthand website name). The HTTP protocol can be used for fetching documents of course, but it can fetch other resources as well, or do other actions like post data to another server. These actions are <strong>HTTP Verbs</strong>, which describe the ability to Create, Read, Update, and Delete data. In specific to HTTP, we can program our site with the ability to <strong>POST, GET, PUT, PATCH, </strong>and<strong> DELETE</strong>.</p><p>The website itself is being hosted on a server so you can access it from anywhere with internet connectivity. The device you are using to view the website is known as the client. As you interact with a website, especially if you log into an account, you become a user. Changes you make on the site reflect specifically onto your screen by rendering changes locally to the Document Object Model, <strong>DOM</strong>, so of course when you log in to see your account it is only happening on the one client you are using. As a user makes changes on the DOM by interacting with the site through buttons or forms, etc, this sends requests to the server, the function and relevant data are processed and it sends a response back to complete the cycle.</p><p>It is important to remember that the requests are made by the browser and are then handled on the server and sent back as a response to the client. These requests and responses are <em>stateless</em>, so any two consecutive requests may not necessarily relate to each other. This also brings in the issue of persisting data on the site, such as a shopping cart feature. Websites use <strong>cookies</strong>, locally stored files with data relevant to that site, to help the site speed up interactions, store user profile details, or even website settings. This also allows a user to stay logged into an authentication session while navigating between pages. Without accounting for this, a user could be interacting with the site in a meaningful way, but the results would not necessarily be reflecting the expected results. We as programmers have to take this into account as we build our sites.</p><p>The structure of an HTTP Request:</p><p>An HTTP request includes a method, path, version of HTTP protocol, optional headers, and optional body.</p><p><em>Method:</em> These are our CRUD actions for <strong>POST, GET, PUT, PATCH, </strong>and<strong> DELETE.</strong></p><p><em>Path: </em>Is where the HTTP request should be directed for a specific resource.</p><p><em>Version: </em>The version of HTTP protocol being used.</p><p><em>Headers:</em> May provide additional information.</p><p><em>Body: </em>This is typically included with POST requests to include the client resource being sent to the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*lx3H57LNAp4TlF5-nsY45w.png" /></figure><p>Some sites may also use a middleman of sorts between its server and your client, this is known as a Proxy. The HTTP proxy operates between the server and client. This can be used as a security feature to potentially stop harmful content before sending it to a client. It also protects against harmful Web clients through compliance and it can mitigate or prevent buffer overflow attacks on the server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad33cd42122" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks & ‘customHook(s)’]]></title>
            <link>https://medium.com/@gbanks1438/react-hooks-usehook-with-custom-hooks-e932f41d6e8b?source=rss-526395afb84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e932f41d6e8b</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[hooks]]></category>
            <dc:creator><![CDATA[Greg Banks]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 02:56:28 GMT</pubDate>
            <atom:updated>2021-12-13T03:20:47.458Z</atom:updated>
            <content:encoded><![CDATA[<p>One of React’s biggest strengths is in allowing developers the ability to write clean and simple code through its use of modularity. It accomplishes this by breaking off segments of repeating functionality and then importing that into other files as components when needed. Hooks are part of the newest addition in React version 16.8 which will allow you to use state and other predesigned React features without writing a class. You can also build your own Custom Hooks in order to extract reusable component logic into their own functions to then use across your React application.</p><p>“<em>A Hook is a special function that lets you ‘hook into’ React features.</em>” — <a href="https://reactjs.org/docs/hooks-reference.html">https://reactjs.org/docs/hooks-reference.html</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*3d0jsQppieVP5XL6KGK6YA.png" /></figure><p>As developers, we may already be familiar with some of the Basic Hooks in React such as ‘useState’, ‘useEffect’, and ‘useContext’. The first two of which in particular are vital to the deployment of useful and robust app features and they will be the most commonly utilized React Hooks. The React documentation helps us to better understand:</p><p><strong>useState</strong> — ‘Lets you add React state to function components. It‘s set to a variable as a reference to the current state value, and is also set to a function to update the state value.’</p><p><strong>useEffect</strong> — ‘Lets you perform side effects in function components. Examples of side effects include Data Fetching, setting up a Subscription, or manually changing the DOM in React components. By using this Hook, you tell React that your component needs to do something.’</p><p><strong>useContext </strong>—’Allows your components to access some global data and re-render when that global data is changed. You can hold global state, theme, user settings, language settings, or other services inside the context. Using context adds an additional level of complexity in your application.’</p><p>React also has several additional predefined Hooks to make coding easy without the need to write in a class. These examples include:</p><p><strong>useReduced</strong> — ‘An alternative to useState. Accepts a reducer of type: (state, action) =&gt; newState, and returns the current state paired with a dispatch method. It’s usually preferable when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one. It also lets you optimize performance for components that trigger deep updates because you can pass dispatch down instead of callbacks.’</p><p><strong>useCallback </strong>— ‘Returns a memoized value. Pass an inline callback and an array of dependencies. It will return a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.’</p><p><strong>useMemo </strong>— ‘Returns a memoized value. Pass a “create” function and an array of dependencies. It will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render. Remember that the function passed to useMemo runs during rendering. If no array is provided, a new value will be computed on every render. <strong>NOTE:</strong> <strong>You may rely on </strong><strong>useMemo as a performance optimization, not as a semantic guarantee. React may choose to “forget” some previously memoized values and recalculate them on next render.</strong>’</p><p><strong>useRef</strong> — ‘Returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component. A common use case is to access a child imperatively. Under the hood, it creates a plain JavaScript object and gives the same ref object on every render.’</p><p><strong>useImperativeHandle </strong>— ‘Customizes the instance value that is exposed to parent components when using ref. It should be used with <a href="https://reactjs.org/docs/react-api.html#reactforwardref">forwardRef</a>. <strong>NOTE: Imperative code using refs should be avoided in most cases.</strong>’</p><p><strong>useLayoutEffect</strong> — ‘The signature is identical to useEffect, but it fires synchronously after all DOM mutations. Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside useLayoutEffect will be flushed synchronously, before the browser has a chance to paint. NOTE: Prefer the standard useEffect when possible to avoid blocking visual updates.’</p><p><strong>useDebugValue</strong> — ‘Can be used to display a label for custom hooks in React DevTools. Its most valuable for custom Hooks that are part of shared libraries. It accepts a formatting function as an optional second parameter. This function is only called if the Hooks are inspected. It receives the debug value as a parameter and should return a formatted display value.’</p><p><strong>“Custom Hooks are a convention that naturally follows from the design of Hooks, rather than a React feature.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IbfsXCPT4v6z4_v_VHLxOQ.jpeg" /></figure><p>As you build out your next program, you may start to encounter the need for a specific repeated function, or set of functionality, across your components. You can take that logic out as it’s own component and then import it as a <strong>Custom Hook</strong> into the components that would then call on it. This leaves you with cleaner code in your top level files, which is always easier for you or other developers to read and manage later on for updates.</p><p>A Custom Hook is a JavaScript function which by convention has a name that starts with ”use” (in order to signal to other developers that this code is meant to be used as a Hook) then camelCase some meaningful function name, it stores some modular aspect of a larger set of complex code as a function, and it may even call other React Hooks <em>(as long as we called our custom hook from within a React component)</em>. We can select the arguments and the return just like a function. A custom Hook does not need to have a specific signature. It’s also very important to make sure to only call other Hooks unconditionally at the top level. You can find out more about Reacts <a href="https://reactjs.org/docs/hooks-rules.html">rules of Hooks</a> on the documentation page.</p><p>Custom Hooks help us to reuse <em>stateful logic </em>in our applications<em>. </em>However,<em> </em>any state and effects inside of it remain fully isolated. Every call<em> </em>to a Hook returns isolated state, so if we made repeated calls to these hooks, each return would be independent. They offer the flexibility to cleanly handle use cases like form handling, animation, declarative subscriptions, and timers because you can package the complex code into another function as a component, and then import it to the other components in the app.</p><p>Custom Hooks makes the completed versions of App components significantly shorter and it also makes accessing similar functionality across components appreciably easier.</p><p>Check out these libraries of prebuilt Hooks to make your React applications modular, more functional, and cleaner to code:</p><p><a href="https://reactjs.org/docs/hooks-reference.html#additional-hooks">React API Documentation</a></p><p><a href="https://react-redux.js.org/api/hooks">React Redux</a></p><p><a href="https://reactrouter.com/web/api/Hooks">React Router</a></p><p><a href="https://github.com/rehooks/awesome-react-hooks">Community generated custom hooks</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e932f41d6e8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Callback Functions]]></title>
            <link>https://medium.com/@gbanks1438/javascript-callback-functions-738c75501933?source=rss-526395afb84b------2</link>
            <guid isPermaLink="false">https://medium.com/p/738c75501933</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[callback-function]]></category>
            <dc:creator><![CDATA[Greg Banks]]></dc:creator>
            <pubDate>Mon, 22 Nov 2021 14:30:09 GMT</pubDate>
            <atom:updated>2021-11-22T14:30:09.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*iNqmIOuYBg-hNgaJioda_g.png" /></figure><p>It’s rare in my own life that I’m ever doing just one thing at a time. I’m usually trying to prioritize what needs to be handled, so I might have a list to work off. Yet, I still end up reorganizing and juggling the big things while pushing off the smaller and easier tasks; of course the goal is to try to quickly get back to those small tasks in the end so I can wrap up my day. Ultimately, failing to manage the chaos and properly organize how my day will go causes delays and other major issues. Coding in Javascript can be a lot like that as well. We expect our code to do a lot of things to make our lives easier, but it has to process the functions in a certain way and then often ‘call-back’ other functions to successfully deliver the experience we planned as developers in the correct sequence.</p><p><strong>The Callback Function</strong></p><p>When JavaScript reads through the code it moves down sequentially from the top. However, functions are executed in the sequence they’re called, and not in the sequence they’re defined. A callback function is specifically when a function gets passed as an argument into another function. This process works in our code because, in Javascript, functions have the properties of first class objects. The callback does not use its own set of parenthesis when being set as an argument because we do not want to invoke it ourselves directly, we are allowing the function it is nested within to handle the call. The functions that take callbacks as arguments are called higher-order functions. Using callbacks are great when using simple code statements, such as working to get a welcome String to be instantly logged into the console.</p><p><strong>Synchronous Callback Example 1:</strong></p><pre>function hello<strong>(</strong>name<strong>)</strong> <strong>{</strong><br>    console.log(`Hi my name is ${name}`);<br><strong>}</strong><br><br>hello(&#39;Greg&#39;); // Hi my name is Greg</pre><p>Notice the bolded characters above help show how we can recognize the Callback function syntax even if we were to write it as an arrow function:</p><p>() =&gt; {}</p><p>This is the structure you will find inside of advanced functions such as Event Listeners. Remembering this structure is an excellent way to identify callbacks in more concisely written code.</p><p><strong>Synchronous Callback Example 2:</strong></p><p>We could look at another type of synchronous callback function that is hiding in plain sight. While working with arrays, we often will use .forEach() to iterate through the index of elements and perform some action. The array.prototype.forEach() function takes in another function, which is then processed for each index in order, one at a time, without waiting for other code to run.</p><pre>const months = [&#39;January&#39;, &#39;February&#39;, &#39;March&#39;, &#39;April&#39;, &#39;May&#39;, &#39;June&#39;, &#39;July&#39;, &#39;August&#39;, &#39;September&#39;, &#39;October&#39;, &#39;November&#39;, &#39;December&#39;];</pre><pre>months.forEach(<strong>(</strong>eachMonth, index<strong>) =&gt; {</strong></pre><pre>console.log(`${index+1}` + &#39;. &#39; + eachMonth);</pre><pre><strong>}</strong>);</pre><pre>// Returns all 12 months with the corresponding month numerals</pre><p>We will more immediately recognize the function when we write this out in a more verbose way:</p><pre>...<br>months.forEach(<strong>function</strong>(eachMonth, index){</pre><pre>console.log(index + &#39;. &#39; + eachMonth);</pre><pre>});</pre><p><strong>Javascript Under The Hood</strong></p><p>The Javascript language is single threaded, so it can only process one event at a time and the remaining events are blocked in that moment. The call-stack keeps track of the events and the event-loop processes the current function before moving on to the remaining code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SvTxMIEudVv8YRW_ELRamw.png" /><figcaption><a href="https://www.webdevolution.com/blog/Javascript-Event-Loop-Explained"><strong>https://www.webdevolution.com/blog/Javascript-Event-Loop-Explained</strong></a></figcaption></figure><p>Asynchronous Callbacks are one way to tell JavaScript to wait to call functions until after some other function has occurred in order to prevent problems of blocking code from running and to ensure the correct sequence of events. It’s even a great way to log something in the console to confirm when it finally does get called as part of troubleshooting. The callback function is put into the callback queue while the currently running functions are completed, then after the call stack is cleared, the communication to the DOM or server can happen for the processed function, and then the event loop will grab the remaining callback functions in the queue and add them into the call stack.</p><p>It’s important to consider how the execution sequence is impacted when using asynchronous callbacks, because one function has to wait for another function before it’s called, otherwise you could cause a blockage. Asynchronous functionality is one reason why Javascript’s is able to be responsive and can often deliver fast results when code is written properly. You can ensure some functions occur before others as you develop your code to avoid the program from getting stuck working on just one function before it can even touch any others, otherwise you could create a poor user experience with slow or broken functionality. Exploring more advanced concepts such as setTimeout, using Event Listeners, and handling Promises can help further improve your code.</p><p><strong>Asynchronous Callback Example:</strong></p><pre>btn.addEventListener(&#39;click&#39;, () =&gt; {<br>  alert(&#39;You clicked me!&#39;);</pre><pre>let pElem = document.createElement(&#39;p&#39;);<br>  pElem.textContent = &#39;This is a newly-added paragraph.&#39;;<br>  document.body.appendChild(pElem);<br>});<br>// developer.mozilla.org: <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing#async_callbacks">Async callbacks</a></pre><p>The btn.addEventListener() function above takes in the event type ‘click’ that it is listening for, then a callback function as its second parameter. It performs the corresponding action of displaying the alert box and text on the DOM as well as creating and appending the new p elements and text. These actions do not occur immediately, but only happen when the callback gets invoked by clicking the button on the page.</p><p><strong>Callback Function Hell: a.k.a. the ‘Pyramid of Doom’</strong></p><p>Callbacks had been an early way to create asynchronous javascript functions. They are great for limited situations where you need to run code without causing a blockage and then return the value needed when the callbacks have also run. There are some drawbacks to overusing them however. It’s possible in some situations one callback could be nested into another and that may be a bit awkward, but it would still work. The trouble starts when you start nesting too many callbacks into one structure because it soon becomes a real mess to read and it’s more difficult to manage. The wedge shape below is a good indicator that you’ve relied too heavily on the callback function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*GNfiR0XGXdnJlJ4KsjA2bw.jpeg" /><figcaption><a href="https://dev.to/koladev/a-simple-guide-to-asynchronous-javascript-callbacks-promises-async-await-4m03">https://dev.to/koladev/a-simple-guide-to-asynchronous-javascript-callbacks-promises-async-await-4m03</a></figcaption></figure><p><strong>Re-calling What I’ve Learned</strong></p><p>I’ve learned how callbacks are a great way to organize the sequence of events, and help streamline functionality. They can have a function wait for the completion of other resource intensive actions like downloading things, reading files, or talking to databases. In my own life I can see how this type of asynchronous organization is more natural and it makes a lot more sense when I write my code. As an example, when I call ahead to a restaurant for my to-go order and then let them cook it and wait for the confirmation email for my pickup time before I take the action to go to pick it up I end up with hot food out of the kitchen as soon as I arrive, but if I just went straight to the restaurant as soon as I was hungry and then ordered I would have to sit down and wait for the food to be made before it can even be served. I found callbacks to be a good introduction to asynchronous functionality and I’m excited to explore more about other advanced functions.</p><p>Thanks for reading my blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738c75501933" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>