readings

Links to some interesting web development blog posts that have helped solve tricky problems.
De-mystifying the V8 Garbage Collector: How Your Code Is Sabotaging Your App’s Memory
The worst memory problems in Node.js aren’t usually big, obvious leaks. They’re subtle patterns that stress the GC in ways it wasn’t designed for. <h3>Mistake 1: “GC Thrashing” in a Hot Path</h3> Let’s look at a subtle performance trap. A “hot path” is a piece of code that runs constantly, like a loop processing data from a large request. This code looks harmless, but it’s quietly hammering your GC every second. <code>//This is an overly simplified code snippet just for understanding // A function to process a large dataset function processData(data: LargeDataObject[]): ProcessedData[] { // This looks innocent, but it's a hot path return data.map(item => { // This creates a new object on EVERY iteration const processedItem = { id: item.id, name: item.name.toUpperCase(), timestamp: Date.now(), // ... 10 other properties }; return processedItem; }); }</code>
Tanmay Bansal @ CodeToDeploy
31 October 2025
The Complete Guide to Self-Hosting Next.js at Scale
This guide covers six critical areas where Next.js needs special configuration for production self-hosting: Dockerfiles, reverse proxies, caching, image optimization, CDNs, and server actions. Get any of these wrong, and your application may not function as expected in production, often in ways that only appear under load.
David Höck @ dlhck.com
24 August 2025
Running a React Web App in an Android App
There are times where you need to run your React web app from a mobile phone locally. That means running it completely without the cloud, 100% offline-first, and absolutely zero remote server calls. This tutorial will show you how you can bundle your Vite and React app into an Android app and load it in a WebView.
Max Alexander, Ben Chatelain @ ditto.live
29 December 2023
On Playwright in GitHub Actions
As you’ll add more and more tests, they can easily take a couple or even tens of minutes to complete. To get the test results faster, we could run the tests in different projects on different machines in parallel. The entire test run will take as much as one of the projects instead of all of them. In GitHub Actions, we can easily do that by specifying a matrix property on our job. It’s a set of fields where every one of them has a list of allowed values. In our case, we’d like to configure the project there, with the three possible values, as defined in Playwright’s config.
Radosław Miernik @ radekmie.dev
31 January 2023
20 Things I’ve Learned in my 20 Years as a Software Engineer
Every system eventually sucks, get over it Bjarne Stroustrup has a quote that goes “There are only two kinds of languages: the ones people complain about and the ones nobody uses”. This can be extended to large systems as well. There is no “right” architecture, you’ll never pay down all of your technical debt, you’ll never design the perfect interface, your tests will always be too slow. This isn’t an excuse to never make things better, but instead a way to give you perspective. Worry less about elegance and perfection; instead strive for continuous improvement and creating a livable system that your team enjoys working in and sustainably delivers value.
Justin Etheredge @ SimpleThread.com
7 October 2021
Is it possible to open developer tools console in Chrome on Android phone?
When you don't have a PC on hand, you could use Eruda, which is devtools for mobile browsers https://github.com/liriliri/eruda It is provided as embeddable javascript and also a bookmarklet (pasting bookmarklet in chrome removes the javascript: prefix, so you have to type it yourself)
trogper @ stackoverflow.com
25 September 2018
React Server Components and Remix
In today's landscape, Remix is uniquely positioned to take full advantage of Suspense, RSC, and SSR Streaming: it already knows everything about a page just from the URL, just what React needs for render as you fetch.
Ryan Florence @ remix.run
8 December 2021
ReactJS — useEffect() & useCallback()
Why is the above code problematic?<br><br> The effect re-runs whenever innerFunction changes. As stated, it is re-created whenever MyComponent re-builds Because functions are objects and objects are reference types, that means that the effect will re-run for every render cycle That might still not be a huge problem, but it is, if innerFunction does something that causes MyComponent to re-build (i.e. if it either does something that changes the props or the state).<br><br> Now, you would have an infinite loop!<br> useCallback() helps you prevent this.
InfinityPaul @ medium.com/@infinitypaul
28 August 2019
React's useReducer vs Redux
Where your state is managed is a crucial difference between Redux and useReducer. While Redux creates one global state container -- which hangs somewhere above your whole application --, useReducer creates a independent component co-located state container within your component. Let this fact sink for a moment before we continue extending useReducer's component co-located state management philosophy.
Robin Wieruch @ robinwieruch.de
13 May 2019
Five practical tips when using React hooks in production
We often resorted to React.useState as the default hook to keep the state in our components. However, over time the component state might need to get more complex, depending on the new requirements like having multiple state values. In certain cases, using a React.useReducer hook can help to avoid multiple state values and simplifies the state update logic.
Tobias Deekens @ techblog.commercetools.com
9 March 2020
Configuring HTTPS to a Web Service on Google Kubernetes Engine
The check MUST be for http. Although theoretically equivalent, if the check is written as if($http_x_forwarded != 'https') as suggested in this Serverfault question, Google Cloud Load Balancer’s automated health checks will end up getting a 301 redirect and the backend will be considered unhealthy. Unhealthy backends get no traffic. This is mentioned right at the bottom of the section on redirecting: <br> Note that the GCLB health checks do not get the 301 because they don't include x-forwarded-proto.
LH Fong @ estl.tech
8 March 2018
Recovering Lost Commits with git reflog and reset
The reflog command will give you a good history of what's been happening on the head of your branches. Run it, then find the line that refers to the state that you want to get back to. <br> <br> In short, you need to switch to the correct branch ("effectif" in my case) and then do a hard reset. The --hard options sets the HEAD of the current branch back to the commit that you specify
Graham Ashton @ Effectif Development
16 April 2008
How and when to use the tabindex attribute
As we have covered, a negative tabindex value will remove the element from tab focus, but can add elements to programmatic focus. <br><br> A great example of when this is useful is modals. Modal containers are typically unfocusable elements like <div> or <section>. When a modal window is open, we may want to move focus to it so that screen readers will read out its content. But, we don’t want the modal container itself to be able to receive tab focus. This can be achieved using a negative tabindex.
Ire Aderinokun @ bitsofcode
29 November 2018
Direct to S3 File Uploads in Node.js
Web applications often require the ability to allow users to upload files such as images, movies and archives. Amazon S3 is a popular and reliable storage option for these files. <br><br> This article demonstrates how to create a Node.js application that uploads files directly to S3 instead of via a web application, utilising S3’s Cross-Origin Resource Sharing (CORS) support. The Express web framework is used to facilitate request-handling in the examples below, but the procedure should be almost identical in any Node.js application.
Heroku @ Heroku Dev Center
11 July 2018
30 Seconds of CSS
<h3>Constant width to height ratio</h3> Given an element of variable width, it will ensure its height remains proportionate in a responsive fashion (i.e., its width to height ratio remains constant). <br><br> <code>.constant-width-to-height-ratio {<br> background: #333; width: 50%; <br>} <br><br>.constant-width-to-height-ratio::before { <br> content: ''; <br> padding-top: 100%;<br> float: left;<br>}<br><br> .constant-width-to-height-ratio::after { <br> content: ''; <br> display: block; <br> clear: both;<br>}</code><br><br> padding-top on the ::before pseudo-element causes the height of the element to equal a percentage of its width. 100% therefore means the element's height will always be 100% of the width, creating a responsive square. This method also allows content to be placed inside the element normally.
staff @ 30-seconds
1 October 2018
TypeScript with Babel: A Beautiful Marriage
Wouldn’t it be nice to have one JavaScript compiler? Whether your code has ES2015 features, JSX, TypeScript, or something crazy custom — the compiler knows what to do. I just described Babel. Cheeky. By allowing Babel to act as the single compiler, there’s no need to manage, configure, or merge two compilers with some convoluted Webpack sorcery. It also simplifies the entire JavaScript ecosystem. Instead of linters, test runners, build systems, and boilerplates supporting different compilers, they just need to support Babel. You then configure Babel to handle your specific needs. Say goodbye to ts-node, ts-jest, ts-karma, create-react-app-typescript, etc, and use the Babel support instead. Support for Babel is everywhere, checkout the Babel setup page.
Matt Turnbull @ medium.com/dailyjs
28 August 2018
How To Debug Jest Tests
Instead, Orta suggested we used the Chrome Node DevTools. Since the Enzyme test is run via yarn jest, yarn is acting as a frontend for running the Enzyme test with Node. This means that we can use the Chrome Node DevTools as a debugger to run the Enzyme test. This was super useful since the one thing we needed was to be able to peek inside certain objects to see what they looked like and how they were failing. It was a much faster, more methodical way to approach debugging this test. Here are the steps we took:
Anson Wang @ Artsy Engineering Blog
24 August 2018
Art of debugging with Chrome DevTools
If all you want is a reference to a DOM element, use $0 shortcut. $0 gives you the reference to the currently selected element in the Elements panel. If $0 is the currently selected element, $1 is the previously selected element. That goes all the way to $4. <br><br> Use $_ to get hold of the result of last evaluated expression in the console. <br><br> getEventListeners(domElement) gives you an object with all the registered event listeners on that DOM element. E.g. if you want a reference to a click handler on a button, remove it or modify it in the runtime in the production environment, this allows you to do so.
Prashant Palikhe @ medium.com/frontmen
24 July 2018
4 CSS tricks I’ve learnt the hard way
<h4>Position an element relatively to its parent</h4> This one is very useful when dealing with dropdowns, tooltips and popovers. <br> This is how it works: <br> The parent element MUST NOT be static: <code>position: relative | fixed | absolute</code> <br> The child MUST have : <code>position:absolute</code> <br> And just like that, using<code> top | left | bottom | right </code>will position the child relatively to its parent.
David Mellul @ itnext.io
8 June 2018
Operationalizing Node.js for Server Side Rendering
HAProxy tracks how many connections are currently open between it and each worker. It has a limit configured via maxconn. Routing is set to static-rr (static round robin), so ordinarily each worker is given a request in turn. With the limit set, the routing proceeds with round robin, but skips over any workers that are currently at their limit of requests. If no workers are below their connection limit, the request is queued and will be dispatched to whichever worker becomes available first. This is the behavior we want.
Ben Hughes @ Airbnb Engineering & Data Science
18 July 2018
15 HTML element methods you’ve potentially never heard of
If you want to play along, and have some browser DevTools at your disposal, you can select an element in the element tree, then type $0 in the console. This gives you a reference to the element you had selected. To see the element as an object, type dir($0).
David Gilbertson @ HackerNoon
5 July 2018
More Unicode Patterns
I recently wrote a post — that was shared here on CSS-Tricks — where I looked at ways to use Unicode characters to create interesting (and random) patterns. Since then, I’ve continued to seek new characters to build new patterns. I even borrowed a book about Unicode from a local library.<br/><br/> It's all up to your imagination to see the possible patterns a Unicode character can make. Although not all characters are good as patterns, the process is a good exercise for me.<br/><br/> And, aside from Unicode itself, the methods to build the patterns may not be so obvious. It usually takes a lot of inspiration and trial and error to come up with new ones.
Yuan Chuan @ css-tricks
14 June 2018
Why You Shouldn’t Use Bright, Saturated Colors for Backgrounds
A bright, saturated background color will draw user attention, but it won’t hold it. Using them is like screaming at users when they’re in front of you. You’ll get their attention, but they’ll soon look away because you’re jarring them.<br><br> You should only use them on interface elements that demand user action such as buttons. The color will draw attention to those elements and make them easy to find when users are ready to act.
anthony @ uxmovement.com
22 May 2018
Sending Web Push Notifications from Node.js
Using service workers, you can send push notifications to Chrome straight from your Node.js app. The excellent web-push npm module lets you send push notifications without going through an intermediary service like PubNub. This article will walk you through setting up a "Hello, World" example of web push notifications using a vanilla JavaScript frontend and Express on the backend.
Valeri Karpov @ thecodebarbarian.com
8 May 2018
Modularizing your GraphQL schema code
As your GraphQL application grows from demo, to proof of concept, to production, the complexity of your schema and resolvers will grow in tandem. To organize your code, you’ll want to split up your schema types and the associated resolvers into multiple files.<br><br> We get this question frequently since there are a lot of different approaches to splitting up your schema code, and it might seem that you need a complex setup to get a good result. But it turns out that we can arrange our schema and resolver code in separate files with just a few simple JavaScript concepts.<br><br> In this post, we present a straightforward method for modularizing schemas built with graphql-tools that you can tweak to match your tastes and your codebase.
Dhaivat Pandya @ dev-blog.apollodata.com
12 April 2018
Contextual Components in React
Contextual Components are one of my favorite features in Ember. They allow you to expose components pre-wired with state and actions as part of a component’s public API, without having to directly expose that state or those actions. This same pattern can be applied to React components using the Render Props pattern. Let’s look at an example to make this more concrete.
David Tang @ thejsguy.com
18 March 2018
Designing Reusable React Components
Imagine your team just deployed a ToDo app, built in React. A month later, another team in your company wants to run your ToDo app within their invoice app, also built in React.<br> To run your React app in multiple spots, you have three options: <ol> <li>iframe — Embed the todo app in the invoice app via an iframe tag.</li> <li>Reusable App Component — Share the entire todo app via npm.</li> <li>Reusable UI Component — Share the todo app’s markup via npm.</li> </ol>
Cory House @ medium.freecodecamp.org
30 December 2017
Deep-copying in JavaScript
One way to copy an object is to use Object.assign(target, sources...). <br> This, however, is merely a shallow copy. If our object contains objects, they will remain shared references, which is not what we want<br> One of the oldest way to create copies of an object is to turn the object into its JSON string representation and then parse it back to an object. It feels a bit heavy-handed, but it does work
Das Surma @ dassur.ma
25 January 2018
Permission UX
First show a fake permission prompt that your website controls, consisting of buttons to allow or ignore the permission request. If the user clicks allows, request permission, triggering the real browser permission prompt. <br><br> With this approach you display a custom permission prompt in your web app which asks the user to enable notifications. By doing this the user can chose enable or disable without your website running the risk of being permanently blocked. If the user selects enable on the custom UI, display the actual permission prompt, otherwise hide your custom pop-up and ask some other time.
Matt Gaunt @ developers.google.com
3 January 2018
Understanding CSS Layout And The Block Formatting Context
You can think of a BFC as like a mini layout inside your page. Once an element creates a BFC, everything is contained inside it. As we have seen, this includes floated elements which no longer poke out of the bottom of the box. The BFC also causes some other useful behavior. <br><br> In addition to using overflow to create a BFC, some other CSS properties create a BFC. As we have seen, floating an element creates a BFC. So your floated item will contain anything inside it:
Rachel Andrew @ smashingmagazine.com
11 December 2017
Take control of your scroll: customizing pull-to-refresh and overflow effects
Turning off the pull-to-refresh action is a single line of CSS. Just prevent scroll chaining on the entire viewport-defining element. In most cases, that's <html> or <body>: <code> body { /* Disables pull-to-refresh but allows overscroll glow effects. */ overscroll-behavior-y: contain; } </code>
Eric Bidelman @ developers.google.com
1 November 2017
Debouncing and Throttling Explained Through Examples
requestAnimationFrame is another way of rate-limiting the execution of a function.<br><br> It can be thought as a _.throttle(dosomething, 16). But with a much higher fidelity, since it's a browser native API that aims for better accuracy.<br><br> We can use the rAF API, as an alternative to the throttle function, considering this pros/cons:
DAVID CORBACHO @ CSS Tricks
6 April 2016
Putting the helmet on – Securing your Express app
In this example you can see that for fonts we only allow them if they are from our own domain or from fonts.gstatic.com aka Google Fonts. Images we’ll only allow from our own domain and not any external domain. For scripts and styles, however, we only allow them if they have a certain nonce. This means we don’t even care about the origin but we care about a very specific value. This nonce has to be specified in a way like below:<br/><br/> When the browser receives the HTML it will make sure to clear out the nonce for security purposes, so other scripts won’t be able to access them to add additional unwanted scripts.
Dominik Kundel @ twilio.com/blog
21 November 2017
Performance-tuning a React application
I started thinking about server-rendering, but that wouldn’t actually fix the problem; the server would still have to make a call to the DB, and then a call to the TV Maze API. Worse, the user would be staring at a white screen while the server did its work.<br/><br/> Why not use local-storage? We can persist all state changes to the browser, and rehydrate from that state when the user returns. The data will be stale, but that’s OK! The real data won’t be far behind, and this will make the initial load feel so much faster.
Joshua Comeau @ codeburst.io
10 November 2017
Performance-tuning a React application.
I started thinking about server-rendering, but that wouldn’t actually fix the problem; the server would still have to make a call to the DB, and then a call to the TV Maze API. Worse, the user would be staring at a white screen while the server did its work.<br/><br/> Why not use local-storage? We can persist all state changes to the browser, and rehydrate from that state when the user returns. The data will be stale, but that’s OK! The real data won’t be far behind, and this will make the initial load feel so much faster.<br/><br/> Because this app uses Redux, persisting/hydrating state is pretty straightforward.
Joshua Comeau @ codeburst.io
10 November 2017
Scaling React Server-Side Rendering
So the way to throttle load was profound in its simplicity: when the server is under high load, skip the server-side render, and force the browser to perform the initial render. In times of great need, our rendering capacity would automatically expand to include every single user’s computer. We would trade a bit of page load speed for the ability to elastically scale on a fixed amount of hardware. Redux is the gift that just keeps on giving!
Robert Arkwrite @ arkwright.github.io
2 October 2017
Implementing A Pure CSS Collapsible
First we set the checkbox element to display: none. The checkbox will be invisible and its label will be used instead to check or uncheck it. Later, you’ll see that we’ll use the CSS :checked pseudo-selector to style things differently when the hidden checkbox is checked. <br><br> By default, the collapsible-content div will have a max-height value of 0px, making it completely hiddenűbr><br> When a collapsible’s checkbox gets checked behind the scenes by clicking its label, we’ll set the content div to a high-enough max-height value so that it can grow to display all its internal content. We make use of the adjacent sibling selector (+) to select our content div when the checkbox is checked
Unknown author @ alligator.io
13 October 2017
Shape your redux store like your database
<pre> categories: { '32o8wafe': {id: '32o8wafe', name: 'abs', exercises: [...]}, 'oaiwefjo': {id: 'oaiwefjo', name: 'arms', exercises: [...]}, '3oij2e3c': {id: '3oij2e3c', name: 'legs', exercises: [...]}, } </pre> <br><br> Notice how the id is both the key for the row, and a property in the row itself. This little bit of duplication affords us great flexibility at access time. It’s also compatible with the normalized (aka flat) shape that the redux docs recommend. <br><br> Now you can loop over the data, and have access to the id while iterating! <pre> Object.values(categories).map(cat => ({id: cat.id, name: cat.name})) </pre> Or access any individual item instantly by id! <pre> categories[‘32o8wafe’].name // 'abs' </pre>
Nick Sweeting @ hackernoon.com
27 July 2017
Using the React Children API
We're using another React.Children method here - map. This works just like Array#map, but has built in logic to handle the cases where children is either a single element or null. We map each child to a TabMenuItem element, and use child.props to generate the props our TabMenuItem needs.
Alex Young @ developingthoughts
4 September 2017
CSS Hex Colors Demystified
And actually, that last question leads us to one more, slightly less huge massive and ginormous but still quite important, epiphany. <br><br> Whenever all three component values are the same, no matter what the value is, the color is some shade of gray.
Dave Gash @ medium.com/dev-channel
10 August 2017
Performant Web Animations and Interactions: Achieving 60 FPS
As composite-level changes are the most performant, the only properties that should ever be changed are those that only trigger compositing. These properties are opacity and transform. Seriously, that’s it. However, this isn’t as limiting as it might first seem — you will just have to get a bit creative.
Emily Hayman @ Milliseconds Matter
9 August 2017
Sharing stateful UI logic in React apps using Render Callback components
A few examples of abstracting shared logic across multiple components using the Render Callback pattern (aka Function as Child components).<br><br> <h2>What about Higher Order Components?</h2> A common way to share stateful logic across React components is using the "Higher Order Components" (HOC) pattern. This post will show an alternative that I feel is simpler and more flexible called "Render Callback components" (AKA Function as Child components).<h2>What is a Render Callback?</h2> A "Render Callback" is a component where the children prop is a function; then shared logic is accessed through the function's arguments. Render Callbacks are just functions - just JavaScript!
trevor miller @ trevordmiller.com
20 August 2017
High Performance React: 3 New Tools to Speed Up Your Apps
Generally, if render runs, and there were no changes to the virtual DOM, it is a wasted render cycle since the render method should be pure and not have any side effects. In a large-scale React app, it can be tricky to detect places where this happens, but luckily, there’s a tool that can help! <br><br> <code>why-did-you-update</code> is a library that hooks into React and detects potentially unnecessary component renders. It detects when a component’s render method is called despite its props not having changed.
Ben Edelstein @ freecodecamp.org
12 July 2017
How to inspect the memory usage of a process in Node.Js
We know what the Resident Set is and we also know that the Heap is what we’re looking for: now we need to find out how much heap is used by a given Node.js process. But how do we access the heap?<br><br> With process! <code>process</code> is a global Node.js object which contains information about the current Node.js process, and it provides exactly what we were searching for: the <code>memoryUsage()</code> method.<br><br> memoryUsage returns an object with various information: <code>rss</code>, <code>heapTotal</code>, <code>heapUsed </code>(and <code>external</code>)
VALENTINO GAGLIARDI @ valentinog.com
9 July 2017
Redux isn't slow, you're just doing it wrong - An optimization guide
When we click on a List Item, an action gets fired with updates a store value - selectedItem. Each list item connects to Redux and gets the selectedItem. <br><br> We’re doing the right thing, we’re connecting the component only to the state that it needs. However when selectedItem gets updated, all the ListItem components re-render, because the object we’re returning from selectedItem has changed. <br><br> Now bear in mind that we’re using the selectedItem value to check whether the current item is selected. So the only thing our component really needs to know is whether it is selected or not - in essence - a Boolean. Booleans are great since there are only two possible states, true or false. So if we return a boolean instead of selectedItem, only the two items for which the boolean changes will re-render, which is all we need. mapStateToProps actually takes in the components props as its second argument, we can use that to check whether this is in fact the selected item. <br><br> <code> const ListItem = connect( ({ selectedItem }, { itemId }) => ({ isSelected: selectedItem === itemId }) )(SimpleListItem);</code>
Julian Krispel @ reactrocket.com
5 July 2017
React Higher Order Components in depth
Inheritance Inversion (II) is implemented trivially like this:<br><br> <code>function iiHOC(WrappedComponent) {<br> return class Enhancer extends WrappedComponent {<br> render() {<br> return super.render()<br> }<br> }<br> }<br> </code><br><br> As you can see, the returned HOC class (Enhancer) extends the WrappedComponent. It is called Inheritance Inversion because instead of the WrappedComponent extending some Enhancer class, it is passively extended by the Enhancer. In this way the relationship between them seems inverse.<br><br> Inheritance Inversion allows the HOC to have access to the WrappedComponent instance via this, which means it has access to the state, props, component lifecycle hooks and the render method.
Fran Guijarro @ medium.com/@franleplant
13 January 2016
Three things to consider before your progressive web app goes standalone
The first thing I noticed is that progress indicators are gone. In a standard browser UI, there is always something telling you that you hit a link and that you are waiting for the responses to come back. In standalone mode, there is no visual indicator anymore. Well developed single page applications have progress indicators implemented, but "normal" websites like my personal one usually haven't. <br><br> A missing progress indicator becomes very noticeable when you're on a slow connection. When I was over in the UK last week, I found myself hitting links on the phone several times because I was not sure if something was going on.
stefan judis @ stefanjudis.de
7 April 2017
Form Validation Part 1: Constraint Validation in HTML
Most JavaScript form validation libraries are large, and often require other libraries like jQuery. For example, MailChimp's embeddable form includes a 140kb validation file (minified). It includes the entire jQuery library, a third-party form validation plugin, and some custom MailChimp code. In fact, that setup is what inspired this new series about modern form validation. What new tools do we have these days for form validation? What is possible? What is still needed?<br><br> In this series, I'm going to show you two lightweight ways to validate forms on the front end. Both take advantage of newer web APIs. I'm also going to teach you how to push browser support for these APIs back to IE9 (which provides you with coverage for 99.6% of all web traffic worldwide).
Chris Ferdinandi @ css-tricks
26 June 2017
The Illusion of Speed
Good examples of things that seem to complete earlier than they actually do are both lazy loading and video buffering. Showing a skeleton UI before filling in content feels faster than showing it all at once, and progressive images profit from the same phenomenon. When you click on an online video, it starts playing back before the entire video is ready, creating the illusion that it loaded faster.
Paul Bakaus @ paulbakaus.com
17 April 2016
Understanding Higher Order Components: Making sense of the rapidly changing React best practice
It’s “higher order” in the same way as a “higher order function” — a function that builds a function. In fact you can think of React Components as functions that produce UI. This works especially well for functional stateless components, but if you squint, it works for pure stateful presentational components as well. A HOC is exactly a higher order function.<br><br> <strong>Examples of HOCs</strong><br> There are many, but some notable ones: <ul> <li>The most common is probably Redux’s connect function, which our buildReduxContainer function above is just a shabby version of.</li> <li>React Router’s withRouter function which simply grabs the router off the context and makes it a prop for the child.</li> <li>react-apollo's main interface is the graphql HOC, which, given a component and a GraphQL query, provides the results of that query to the child.</li> <li>Recompose is a library that’s full of HOCs that do a variety of small tasks you may want to abstract away from your components.</li> </ul>
Tom Coleman @ freecodecamp.org
31 May 2017
Techniques for decomposing React components
If a component is becoming too complex due to multiple variations or configurations, consider turning the component into a simple “template” component with one or more open “slots”. This allows a dedicated parent component to focus on configuration only.<br><br> For example, a <code>Comment</code> component may have different actions and metadata displayed depending on whether you are the author, whether it was successfully saved, or what permissions you have. Rather than mix the structure of the <code>Comment</code> component — where and how its content is rendered — with logic to handle all the possible variations, these two concerns can be considered independently. Utilise the ability of React to pass elements, not just data, as props, to create a flexible template component.
David Tang @ JS Daily
18 June 2017
Adopting Flow & TypeScript
<code>// @flow<br/>function square(n) {<br/> return n * n;<br/>}<br/>square("oops");<br/></code><br/>Then we'll run Flow and see the results:<br/><code><br/>function square(n) {<br/> return n * n;<br/> ^ ^<br/> Error (x2)<br/>} square("oops");<br/>Error (x2)<br/>string. The operand of an arithmetic operation must be a number.<br/></code><br/>Immediately we have type errors that tell us something has gone wrong. Flow only requires us to type the exports of a file and the external modules. Everything else can be inferred. This makes type coverage go up much faster. With just a few types you can quickly get files with really high type coverage. In my experience, I can get files covered to about 70–90% in just a few minutes.
James Kyle @ thejameskyle.com
7 June 2017
What Is Event Bubbling in JavaScript? Event Propagation Explained
It should also be noted that the branch determination is static, that is, it is established at the initial dispatch of the event. Tree modifications occurring during event processing will be ignored.<br><br> The propagation is bidirectional, from the window to the event target and back. This propagation can be divided into three phases:<br> <ol> <li>From the window to the event target parent: this is the <i>capture phase</i></li> <li>The event target itself: this is the <i>target phase</i></li> <li>From the event target parent back to the window: the <i>bubble phase</i></li> </ol> <br> What differentiates these phases is the type of listeners that are called.
Giulio Mainardi @ sitepoint.com
24 May 2017
Node.js Streams: Everything you need to know
When a client asks for that big file, we stream it one chunk at a time, which means we don’t buffer it in memory at all. The memory usage grew by about 25 MB and that’s it.<br><br> You can push this example to its limits. Regenerate the <code>big.file</code> with five million lines instead of just one million, which would take the file to well over 2 GB, and that’s actually bigger than the default buffer limit in Node.<br><br> If you try to serve that file using <code>fs.readFile</code>, you simply can’t, by default (you can change the limits). But with <code>fs.createReadStream</code>, there is no problem at all streaming 2 GB of data to the requester, and best of all, the process memory usage will roughly be the same.
Samer Buna @ medium.freecodecamp.com
23 May 2017
Debugging Node.js with Chrome DevTools
Open <code>about:inspect</code> in Chrome<br><br> You’ll want to click the <b>Open dedicated DevTools</b> for Node link. You’ll get a popup window for debugging your node session.<br><br> But better than that, when you kill and restart node, the window will automatically reconnect to it.
Paul Irish @ medium.com/@paul_irish
24 June 2016
CSS Poly Fluid Sizing using calc(), vw, breakpoints and linear equations
When working with creative designers on web page designs, it’s fairly common to receive multiple Sketch or Photoshop artboards/layouts, one for each breakpoint.<br><br> This is good, but it’s a little bit jolting when you resize your browser window. At each breakpoint, the text size instantly jumps up/down in size. It would be great if the resizing of fonts between layouts was completely fluid. Your layout is fluid. Why not your <code>font-sizes</code> too?<br><br> The answer is CSS <code>calc()</code>! Once again, a fairly new CSS technology that is very well supported.
Jake Wilson @ medium.com/@jakobud
24 April 2017
CSS Animations vs the Web Animations API: A Case Study
As with everything, whether to use CSS or JavaScript animations, depends very much on the particulars of the animation. As a general rule, CSS animations should be used for small, UI-related animations such as showing a tooltip. The Web Animation API should be reserved for more advanced effects that need fine-tuned control. That said, here was my comparison between the two methods for this animation.
Ire Aderinokun @ bitsofcode
3 May 2017
45% Faster React Functional Components, Now
Directly calling functional components as functions instead of mounting them using <code>React.createElement</code> is much faster. <br><br> To measure the change, I created this benchmark, the results are quite staggering! From just converting a class-based component to a functional one, we get a little 6% speedup. But by calling it as a simple function instead of mounting, we get a <b>~45﹪ total speed improvement</b>.
Philippe Lehoux @ medium.com/missive-app
3 May 2017
Exploiting Buffer
When using the <code>number</code> constructor of <code>Buffer</code>, it will allocate the memory, but will not fill it with zeros. Instead, the allocated buffer holds… whatever was in memory at the time.<br><br> You can see this behaviour yourself by running Node in a terminal and repeatedly creating a Buffer of a given size, and seeing each one holds different values, as it points to some other portion of previously used memory.
Guy Podjarny @ snyk.io/blog
5 April 2016
Twitter Lite and High Performance React Progressive Web Apps at Scale
On slower devices, we noticed that it could take a long time for our main navigation bar to appear to respond to taps, often leading us to tap multiple times, thinking that perhaps the first tap didn’t register. <br><br> Notice in the image below how the Home icon takes nearly 2 seconds to update and show that it was tapped:<br><br> No, that wasn’t just the GIF running a slow frame rate. It actually was that slow. But, all of the data for the Home screen was already loaded, so why is it taking so long to show anything?<br><br> It turns out that mounting and unmounting large trees of components (like timelines of Tweets) is very expensive in React.
Paul Armstrong @ medium.com/@paularmstrong
11 April 2017
Use all the Databases
Ever wanted to use a few different databases to build your app? Different types of databases are meant for different purposes, so it often makes sense to combine them. You might be hesitant due to the complexity of maintenance and coding, but it can be easy if you combine Compose and GraphQL: instead of writing a number of complex REST endpoints, each querying multiple databases, you set up a single GraphQL endpoint that provides whatever data the client wants using your simple data fetching functions.<br/><br/> This tutorial is meant for anyone who provides or fetches data, whether it’s a backend dev writing an API (in any language) or a frontend web or mobile dev fetching data from the server. We’ll learn about the GraphQL specification, set up a GraphQL server, and fetch data from five different data sources. The code is in Javascript, but you’ll still get a good idea of GraphQL without knowing the language.
Loren Sands-Ramshaw @ compose.com
2 March 2017
Reusable State with Higher Order Components
Higher-order components are a great way to do some next-level refactoring to your React code. If you have repeated state or lifecycle methods that you’d like to deduplicate, HOCs can help you extract that code into reusable functions. But they can be a little gnarly to wrap your head around at first. Functions returning functions returning components?!<br/><br/> But first: what exactly is a “higher-order component” (or HOC)?<br/><br/> The name comes from “higher-order function,” which is a fancy name for a function that accepts another function as an argument, and/or returns a function. You probably already use them without thinking about it. <code>Array.forEach</code> is a higher-order function, as is <code>Array.map</code>, <code>setTimeout</code>, and many more.
Dave Ceddia @ daveceddia.com
28 March 2017
webpack bits: Getting the most out of the CommonsChunkPlugin()
So what if you want to have more control? There are scenarios where you don’t want to have a single shared bundle because not every lazy/entry chunk may use it. The minChunks property also takes a function!! This can be your “filtering predicate” for what modules are added to your newly created bundle.<br/><br/> <code> new webpack.optimize.CommonsChunkPlugin({<br/> filename: "lodash-moment-shared-bundle.js",<br/> minChunks: function(module, count) {<br/> return module.resource && /lodash|moment/.test(module.resource) && count >= 3<br/> }<br/> }) </code><br/><br/> The example above says:<br/><br/> Yo webpack, when you come across a module whos absolute path matches lodash or momentjs, and occurs across 3 separate entries/chunks, then extract those modules into a separate bundle.
Sean T. Larkin @ medium.com/webpack
25 March 2017
CORS — a guided tour
Say, our API lives at <b>good.com/public</b> and our client is hosted on <b>thirdparty.com</b>, the client might run the following code:<br/><br/> <code>fetch('http://good.com:3000/public')<br/> .then(response => response.text())<br/> .then((result) => {<br/> document.body.textContent = result<br/> })</code><br/><br/> But that doesn’t work!<br/><br/> The reason why we won’t get the response in JavaScript is the Same-Origin Policy. This policy was aimed at making sure that a website can’t read the result from a request made to another website.
Martin Splitt @ medium.com/statuscode
28 February 2017
React is Slow, React is Fast: Optimizing React Apps in Practice
What makes a React app slow is usually not a single slow component (that would translate in the flamegraph as one large pit). What makes a React app slow is, most of the time, useless rerenders of many components.<br/><br/> You may have read that the React VirtualDom is super fast. That’s true, but in a medium size app, a full redraw can easily render hundreds of components. Even the fastest VirtualDom templating engine can’t make that in less than 16ms.
François Zaninotto @ dailyjs
5 February 2017
Introducing React Loadable Component-centric code splitting and loading in React
A common piece of advice you will see is to break your app into separate routes and load each one asynchronously. This seems to work well enough for most apps, clicking on a link and loading a new page is not a terrible experience.<br/>But we can do better than that.<br/><br/> Using most routing tools for React, a route is simply a component. There’s nothing particularly special about them. So what if we optimized around components instead of delegating that responsibility to routes? What would that buy us?<br/><br/>It turns out quite a lot. There are many more places than just routes where you can pretty easily split apart your app. Modals, tabs, and many more UI components hide content until the user has done something to reveal it.
james kyle @ medium.com/@thejameskyle
12 March 2017
Low effort, high value. Integration tests in Redux apps
The kind of integration tests that will give the most confidence in the correct functioning of the app are those that take the perspective of the user. The goal is to verify that once the user interacts with the application by clicking buttons, filling form elements etc., the app responds by modifying itself or performing side effects as expected.
Maciek Pekala @ Hacker Noon
26 February 2017
One webpack config to rule them all — environments that is
There are plenty of examples out there demoing separate webpack.config files for each of your environments e.g. dev, production etc. Personally I prefer to avoid creating multiple files and handle everything in one config file, which I feel really helps simplify things. Some PROS for single config file Much easier to decipher what’s happening in a build when you can look in a single file instead of piecing together many files. Avoiding duplication becomes much more straight forward Same config is used in all environments — no need to serve different files based on environment
Ryan Johnson @ medium.com/@ryandrewjohnson
12 February 2017
Redux best practices
How to organise your files is a complicated thing as it is more art and style than anything set in stone. I have found that there are two separate concerns in a Redux app, and I organise my files around them. One concern is data. Your actions (which generate requests for changes in data) can be called from anywhere (normally SmartComponents). Your reducers (which perform the change in data) however, are tied to your actions. On the other hand, you have the view centric layout of your app — the Routes to different views, the SmartComponents that gather the data and handle interactions and the DumbComponents that render these.
Will Becker @ lexical-labs-engineering
28 September 2015
The Right Way to Test React Components
Here are three rules of thumb I use to determine that something is not worth testing:<br />1. Will the test have to duplicate exactly the application code? This will make it brittle.<br />2. Will making assertions in the test duplicate any behavior that is already covered by (and the responsibility of) library code?<br />3. From an outsider’s perspective, is this detail important, or is it only an internal concern? Can the effect of this internal detail be described using only the component’s public API?
Stephen Scott @ freecodecamp
4 February 2017
Code Smells in CSS Revisited
Where should <code>.modal .btn {}</code> live? It should live in the <code>.btn</code> file.<br />We should do our best to group our styles based on the subject (i.e. the key selector). In this example, the subject is <code>.btn</code>: that’s the thing we actually care about. <code>.modal</code> is purely a context for <code>.btn</code>, so we aren’t styling it at all. To this end, we shouldn’t move <code>.btn</code> styling out into another file.
Harry Roberts @ Css Wizardry
8 February 2017
6 Great Uses of the Spread Operator
Thanks to ES6 and the likes of Babel, writing JavaScript has become incredibly dynamic, from new language syntax to custom parsing like JSX. I've become a big fan of the spread operator, three dots that may change the way you complete tasks within JavaScript. The following is a listing of my favorite uses of the spread operator within JavaScript!
David Walsh @ David Walsh Blog
30 January 2017
Source Maps with webpack in Chrome
Warning: Mixing and Matching webpack CLI flags and webpack configs will result in fire. Make sure you either Provide one of the CLI shortcut flags -p or -d for production and development respectively OR Set a valid devtool option on your config.devtool. If you attempt to do both, then you'll end up like me: Fool me once, shame on you
Erik Aybar @ erikaybar.name
23 January 2017
Instrumentation: The First Four Things You Measure
The idea is to be able to quickly identify which components are affected and/or responsible for All The Things Being Broken. The purpose isn’t to shift blame, it’s just to have all the information you need to see who’s involved and what’s probably happening in the outage.
Antoine Grondin @ honeycomb.io/blog
9 January 2017
DOM elements with ID's are global variables
As it turns out, the HTML specification actually documents this functionality. Although it seems major browsers are not implementing it uniformly at all. If you define more than one element with the same ID (you evil person), then Chrome will actually return an array of Element objects whilst Firefox returns the first element it saw.
Andrew Buntine @ dev.to/buntine
12 January 2017
Why Design
At a minimum, we meet her expectations. There are no frowns, no flickers of irritation. She sails through those doors and continues with her life. At best, we catch her attention. She pauses and allows herself a moment of wonder for our work. It’s more than she expects, and so she will remember it with fondness.To design is to be intentional about the outcome we want.
Julie Zhuo @ medium.com/the-year-of-the-looking-glass
6 December 2016
How to get a performance boost using WebAssembly
I want to demonstrate you today how to create and use WebAssembly modules and later on consume them from the browser like they were js modules. In order to do so I will take the Fibonacci algorithm, which we already discussed here and we will compare its performance running it as a normal javascript function vs a WebAssembly module.
Hector Zarco @ medium.com/@devlucky
12 January 2017
How I Write Tests
Encode every single bug you find as a test, to ensure that you’ll notice if you ever encounter it again. This doesn’t have to just mean “bugs reported by a user” or anything similar; Any bug you find in the course of development is worth writing a test for. Even if you find yourself half way into typing a line of code, realize you’ve made a mistake, and backspace half the line: Pause, and ask yourself “If I had made that mistake, is there a test I could have written to demonstrate it?”
Nelson Elhage @ Made of Bugs
29 December 2016
9 Security Tips to Keep Express from Getting Pwned
While there is no defined standard for handling multiple parameters with the same name the defacto standard across frameworks is to treat the values as an array. This can be tricky since Express behavior for a single name is to return it as a String, when multiple are pass the type is changed to an Array. If this isn't accounted for in query handling, an application will emit an uncaughtException event that can bring the whole thing down, making this problem a potential DoS vector if not appropriately addressed.
Tierney Coren @ nodesource.com
9 September 2016
Logging Errors in Client-Side Applications
There are a number of SaaS solutions for logging. These include Loggly, track.js, ErrorCeption, Airbrake and New Relic. Loggly is one of a number of these SaaS solutions. I’m going to use it as an example because it’s easy and free to get started. With the free plan you can log up to 200MB per day, and the data is stored for 7 days.
Lukas White @ sitepoint.com
8 November 2016
Next.Js Is it the next big thing in JavaScript?
Doing the right thing: Building around a router. A lot of modern JavaScript app frameworks didn’t get this correct. A framework should have a router, and it should do more than just client side routing. Next.js has its own router, and it builds on top of it. Most importantly, you don’t really need to know about the router at all.