<?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 Chris Johnson on Medium]]></title>
        <description><![CDATA[Stories by Chris Johnson on Medium]]></description>
        <link>https://medium.com/@chrisjcodes?source=rss-9c4c490a62a8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HtVbJGCFAktgBq2mFUn7Qw.jpeg</url>
            <title>Stories by Chris Johnson on Medium</title>
            <link>https://medium.com/@chrisjcodes?source=rss-9c4c490a62a8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:48:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chrisjcodes/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[What I Learned: Using styled-components in Production]]></title>
            <link>https://medium.com/@chrisjcodes/what-i-learned-using-styled-components-in-production-c64eb41eaf28?source=rss-9c4c490a62a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/c64eb41eaf28</guid>
            <dc:creator><![CDATA[Chris Johnson]]></dc:creator>
            <pubDate>Fri, 10 Feb 2023 20:40:09 GMT</pubDate>
            <atom:updated>2023-02-10T20:40:09.079Z</atom:updated>
            <content:encoded><![CDATA[<p>Styles have come a long way in my time in development and still have plenty of room to improve. On a recent project, I decided to depart from my old friend <a href="http://sass-lang.com/">Sass</a> and take <a href="https://www.styled-components.com/">styled-components</a> for a spin. This article is serving partially as a post-mortem and to provide prospective based on my experience for other folks interested in using styled-components.</p><h3>The Good</h3><ul><li>They were easy to setup and start using</li><li>Using JavaScript in creating styles was fun and refreshingly simple</li><li>Components were more self-contained and portable</li><li>Declarative JSX felt really nice and was easier to parse at a glance</li><li>Fit really well in our <a href="http://bradfrost.com/blog/post/atomic-web-design/">atomic project structure</a></li><li>Helped us spot bad practices</li></ul><h4>Easy to use</h4><p>Styled-components are a drop in solution for styling inline. You add the package, import and start using. No need to have a task runner or bundler (other than what you already need for React) do anything with your styles. It handled building the style sheet, compressing it, prefixing and inlining it in the DOM. I actually was able to pull a bunch of tasks out of our normal build setup because styled components handled those things out of the box. The only configuration I would suggest is using the <a href="https://github.com/styled-components/babel-plugin-styled-components">babel plugin</a> for styled-components. Really helpful when debugging styles to have the styled-component name rather than the randomly generated class.</p><h4>The power of JavaScript, in your styles</h4><p>This was my favorite part of styled components. With Sass you had to learn a special syntax to do anything functional in your styles. Using even just a simple loop or creating dynamic values was a pain in the ass I spent a lot of time consulting Sass docs when I needed to do something like this. Styled components to the rescue, it’s just JavaScript.</p><p>A good example is creating heading styles dynamically. In Sass, you would create a loop to generate each set of styles for the different heading sizes. In styled-components, its just JavaScript so you can call a function from your styles to determine what font size to use, like so:</p><pre>const getFontSize = ({ size }) =&gt; {<br>    /* Calculate sizing or use an object to look one up */<br>}</pre><pre>const styles = css`<br>    font-size: ${getFontSize};<br>`;</pre><pre>const Heading = styled(({ size, children, ...props }) =&gt;<br>     React.createElement(`h${size}`, props, children))`${styles}`</pre><p>How about those times when you need to dynamically set a background image? Now you can just pass it from props to the styles. No more mixing inline style attributes and classes</p><pre>const StyledImageDiv = styled.div`<br>    background-image: url(https://medium.com/$%7Bprops%20=&gt;%20props.backgroundImage%7D);<br>`;</pre><p>I found it really painless to transition into styling because the syntax didn’t change, unlike when I would use Sass and have to remember to switch to $variable: value or remember to use @ symbols for mixins, functions declarations/returns, extends, etc.</p><p>Its also really nice to be able to write utilities as plain old JavaScript functions (and you can unit test them):</p><pre>const baseFontSize = 16;<br>const remify = px =&gt; `${parseInt(px) / baseFontSize}rem`;</pre><pre>const StyledDiv = styled.div`<br>    font-size: ${remify(&#39;32px&#39;)};<br>`;</pre><h4>Self-contained, portable components</h4><p>Before using styled components, I did a few projects with <a href="https://github.com/css-modules/css-modules">CSS modules</a>, which I also really like. However a single component still would have several files it depended on. I found it nice that with styled components, its one file with everything my presentational component needs to render. Less things to have to move/keep track of if I wanted to reuse a component in another project.</p><h4>Declarative JSX</h4><p>JSX has really changed the game. When I first started using it, I hated it. I was coming out of Backbone/Handlebars/Sass land where every piece was separated and seeing markup in my JS just seemed wrong. Now I’ve grown to love it and styled components has only boosted my satisfaction with writing it.</p><p>Previously if I was writing JSX for a Comment component that renders a users avatar, username, and comment body it might have looked something like:</p><pre>&lt;div className=&#39;comment&#39;&gt;<br>    &lt;div className=&#39;user&#39;&gt;<br>        &lt;div<br>            className=&#39;user--avatar&#39;<br>            style={{ backgroundImage: `url(https://medium.com/$%7Bprops.avatar%7D)` }}<br>        /&gt;<br>        &lt;div className=&#39;user--username&#39;&gt;{props.username}&lt;/div&gt;<br>    &lt;/div&gt;<br>    &lt;div className=&#39;comment--body&#39;&gt;{props.commentBody}&lt;/div&gt;<br>&lt;/div&gt;</pre><p>Now with styled-components:</p><pre>&lt;Comment&gt;<br>    &lt;User&gt;<br>        &lt;Avatar imageSrc={props.avatar} /&gt;<br>        &lt;Username&gt;{props.username}&lt;/Username&gt;<br>    &lt;/User&gt;<br>    &lt;CommentBody&gt;{props.commentBody}&lt;/CommentBody&gt;<br>&lt;/Comment&gt;</pre><p>At just a quick glance, I can immediately tell a lot more about structure of the second snippet. Even if you knew nothing about web development you could figure out what is going on to some degree. The first example, you can’t easily tell what closing tags belong to what class names and its just not as easy to parse.</p><h4>Atomic pattern friendly</h4><p>For many of the projects I work on, I use the <a href="http://bradfrost.com/blog/post/atomic-web-design/">atomic approach</a> for organizing components. Styled-components works really nicely with this pattern. What would have been global element styles become atoms and so you end up with things like:</p><pre>const StyledAnchor = styled.a`<br>    color: black;</pre><pre>    &amp;:hover {<br>        color: gray;<br>    }<br>`;</pre><pre>const StyledRouterLink = StyledAnchor.withComponent(RouterLink);</pre><pre>const Link = ({...props}) <em>=&gt;</em> {<br>    if (props.to) {<br>        return &lt;StyledRouterLink {...props} /&gt;;<br>    }<br>    <br>    return &lt;StyledAnchor {...props} /&gt;;<br>};</pre><p>This atom is now your source to globally style links <em>and</em> acts as a nice facade over regular anchor tags and router link components you might be using. In my project we ended up with atoms for inputs, paragraphs, headings, buttons, etc.</p><p>I didn’t typically create components for low level elements before using styled-components and doing so now makes fitting components into the atomic pattern a lot simpler, in my opinion.</p><h3>The Not So Good</h3><ul><li>Patterns were not intuitive, we made a lot of naive mistakes</li><li>Some component files became very long and daunting to edit</li><li>Interpolated functions using props to generate rules were often too complex and cause bloated stylesheets</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c64eb41eaf28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Its not React vs. Vue, its React or Vue]]></title>
            <link>https://medium.com/@chrisjcodes/its-not-react-vs-vue-its-react-or-vue-4a6c8b88346?source=rss-9c4c490a62a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a6c8b88346</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Chris Johnson]]></dc:creator>
            <pubDate>Sun, 03 Jun 2018 23:25:49 GMT</pubDate>
            <atom:updated>2018-07-12T03:06:48.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZzJd5jmY97LEHUi9tfO8BA.jpeg" /><figcaption>Courtesy of Unsplash</figcaption></figure><p>For as long as I can remember in my development career, there has been a framework battle. When I started writing JS it was primarily in jQuery because it a had a low bar to entry. Then I got curious and learned vanilla. Then my job required more complex features where those weren’t quite cutting it and moved into Backbone and Marionette. Now I <em>primarily</em> use React.</p><p>When I chose jQuery, other devs would sometimes ask, “Why not (MooTools|Dojo|etc.)?”. And when I chose Backbone, “Why not (Angular|Ember|etc.)?” Through every iteration of the language, development standards, and stack there has been a new battle over what to use. Now its React and Vue.</p><p>As I said, I primarily use React. I have however, and still do frequently, use Vue when it suits the project better than React. Which brings me to the point of this article, its not React vs Vue its <strong>what suits your situation better.</strong></p><h3>Why React</h3><h4>You’re building an application.</h4><p>I personally find React’s component based architecture better for building large scale apps. I’ve built a few large applications using React and compared to larger ones I built in Backbone, it is just easier to work in at scale. If you’re building good, reusable, dumb components you can surgically slice out pieces to replace/refactor/etc and quarantine issues without that code leaking into your application.</p><p>Not saying its not entirely possible to write large scale apps in Vue, but <em>I</em> just don’t see it as being the best tool. Vue has components but to me they weren&#39;t as easy to work with as in React. You have to register them globally in the app or per use and I stumbled a lot trying to use them to create business logic wrappers or extendable/compose-able pieces.</p><h4>You want to write JavaScript</h4><p>For me, one of the biggest reasons I like React is it feels very thin over the language. There is not a ton of magic happening outside of VDOM/Rendering. I’m using ES6, native language features and I still have to be aware of binding/scope/context, etc. My language experience is applicable and the knowledge I gain while writing apps in React is transferable</p><p>Vue leans more on directives, similarly to Angular. You have to do things the Vue way which requires learning proprietary ways of doing things that already exist in the language like looping, mapping, binding, etc. which means a lot of things you do in Vue are not transferable knowledge. Frankly I can look at compiled React and figure out whats going on, I have no idea how Vue parses things into runtime code, but to be fair I haven’t dug into it much.</p><h4>You like functional programming</h4><p>React promotes, and in some cases requires, a lot of concepts from functional programming. It encourages the use of pure functions, render() has to be pure for instance. As well, state and prop changes must be done in a pure way. It leans heavily on composition in common patterns like Higher Order components. Facebook is also authoring <a href="https://reasonml.github.io/">ReasonML</a>, which is a functional meta language over OCAML. You can use Reason to <a href="https://reasonml.github.io/reason-react/">write React now</a>.</p><p>Vue handles data changes under the hood with its reactivity system and it seems to observe the same instance and fire off renders for mutations, so mutation is a preferred pattern in Vue. Additionally, from my experience, things like currying and functional composition are more difficult to reason about, because Vue handles so much under the hood. I’m sure there are plenty of things you could do in a functional way with Vue but not quite as encouraged or as intuitive as it is in React.</p><h4>You like React</h4><p>Look, if you like writing in React, you should whenever it makes sense. There are plenty of tools for using it to build static sites, server-rendered apps, native apps, what-the-fuck-ever apps. Thats their whole motto, “Learn once, write anywhere”. The biggest reason I write React is because I like to and it fits into what my needs are most of the time.</p><h3>Why Vue</h3><h4>You are building a website</h4><p>If I just need a straight up, nearly static, small scale website, I’m using Vue. You can just build out static markup and CSS and sprinkle in Vue for some interactivity here and there. At the risk of getting blown up for saying this, Vue feels like amped up jQuery mixed with Angular.</p><p>React is more involved to get going as you need to compile it where as Vue can be attached via CDN without any other dependency and it just works. If I just want to pump out a quick simple site, thats a pretty attractive aspect. React does have tools to create static/simple sites but still not as simple as writing plain markup and attaching a script.</p><h4>You are building a widget</h4><p>I have used Vue has a alternative for jQuery a lot. On a few projects I have used <a href="http://www.contentful.com/">Contentful</a> as my CMS/Backend. Contentful allows you to create custom UI widgets for data entry you can deploy to your space using a single HTML file or a hosted widget which they load into an iframe. Their docs recommend using jQuery from a CDN but I typically use Vue because it gives me a lot of things for free that jQuery doesn’t and Vue is actually smaller, 😱.</p><p>I <em>could</em> host a React-based widget on a third party but the same issue applies here as before. React doesn’t scale down as well as Vue does. Its far too easy to build a little one page widget with Vue for me to ever consider using React.</p><h4>You are upgrading an old app</h4><p>If you have an app built in an older framework like Backbone or that is primarily plain HTML/CSS/JS, Vue is vastly easier to migrate to than React. You can pretty much copy and paste your old templates into a Vue app and update the bindings and you’re off and running. Plus, in these legacy code scenarios, since Vue scales down so well you can make the shift more incrementally.</p><p>React is a bit of a commitment and porting over old code wont be as quick. Sure you <em>could</em> copy and paste markup into components and wire them up as well but you’re not really leveraging what React is great for if you do that which is building atomic compose-able components. If I’m re-writing an app, I’m going React but if I have to preserve even a percentage of old UI, Vue wins.</p><h4>You like Vue</h4><p>Look, if you like writing in Vue, you should whenever it makes sense. I use Vue for a lot of things that I just dont feel like I <strong>need</strong> React for. There are plenty of apps using Vue out there as well so you can build large scale apps using it if you want. I choose to use Vue more sparingly but when I do, its because I think its the best choice.</p><h3>Summary</h3><p>So I’m sure there are a ton of arguments to be had about bundle sizes, render speed/diffing, etc. etc. I’m sure you can tweet at anyone working on either Vue or React and they will give you plenty of convincing stats about performance, scalability, whatever. If those things matter for your project and the features of the framework are indifferent, pick your poison that way.</p><p>To me, the battle over which is better is apples to oranges. They are both great, they both have strengths, weaknesses, opinionated approaches etc. Lets remember our job as developers is to build the best thing possible. Hammers are great for nails but not so great for screws. <strong>Use what makes sense.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a6c8b88346" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Appropriately using setTimeout]]></title>
            <link>https://medium.com/@chrisjcodes/appropriately-using-settimeout-2f49d4df11d5?source=rss-9c4c490a62a8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f49d4df11d5</guid>
            <category><![CDATA[settimeout]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async]]></category>
            <category><![CDATA[beginner-javascript]]></category>
            <dc:creator><![CDATA[Chris Johnson]]></dc:creator>
            <pubDate>Fri, 09 Jun 2017 01:50:26 GMT</pubDate>
            <atom:updated>2017-06-10T00:37:24.559Z</atom:updated>
            <content:encoded><![CDATA[<p>If you just read that title and you’re saying “Man, fuck this guy. I know how to use freakin setTimeout”, this article isn’t for you <em>(or you’re a 💩-bag who hates knowing things)</em>. The idea to write this spawned from seeing this method abused by junior/new developers and I realized there isn’t much guidance as to how, when and why to use it.</p><h3>What happens when you call setTimeout?</h3><p>Understanding how setTimeout works requires you to have some understanding of what the call stack, queue and the event loop are. If you’re not familiar with it here is a <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">great talk you should watch</a> that also explains a few things about how setTimeout works.</p><p>When you call setTimeout, it pushes your function to a WebAPI which then waits for the specified delay to push your function into the queue. As soon as there is room in the call stack, the event loop pushes your function on the stack to be called.</p><p>You may have seen people call setTimeout like so:</p><pre>setTimeout(()=&gt; {/* some code to execute */}, 0);</pre><p><em>(You can actually omit the delay argument to get the same call) </em>This pushes the function to our setTimeout WebAPI which adds it to the queue. The function will run as soon as the queue is cleared and there is room on the call stack. This is commonly used as a quick fix for long-running functions that are blocking the call stack.</p><h3>What are some reasonable uses of setTimeout?</h3><ul><li>To set a <em>minimum</em> delay before execution of a function</li><li>Remove a blocking function from the call stack (<em>if you can’t use a </em><a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers"><em>web worker</em></a>)</li><li>As a quick mock for an async operation</li></ul><h4>Set a <em>minimum</em> delay before execution of a function</h4><pre>setTimeout(delayedFunction, 2000);</pre><p>Well, duh. You want a function to be called after some period of time. Note that the delay you give is only the <em>minimum</em> time until the function is called. If there are other things blocking the stack it will delay it further. A few other reasons for variance in execution time can be found <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Reasons_for_delays_longer_than_specified">here</a>.</p><p>This is commonly used for animation. This is ok, but with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Animations_API">Web Animations API</a> becoming more mature, there will be less use cases for setTimeout. Additionally many animations can be handled by <a href="https://www.smashingmagazine.com/2016/12/gpu-animation-doing-it-right/">GPU accelerated CSS animations</a>.</p><h4>Remove blocking execution from the call stack</h4><pre>setTimeout(someHeavyFunction);</pre><p>setTimeout can be a quick and easy fix to prevent long-running functions from blocking the call stack. However this shouldn’t be a permanent solution; favor using something like a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">web worker</a> instead. They have<a href="http://caniuse.com/#search=webworker"> pretty wide support</a> if you don’t have to support old versions of Internet Explorer.</p><p>Before using setTimeout, make sure that the function is optimized. Obviously some operations can be complex and heavy no matter what but breaking up a large function into smaller segments and reducing the load on the browser may eliminate the need to use setTimeout. It also has the added benefit of making your code more concise and organized.</p><p><em>Most </em>of the times I have seen setTimeout used this way, it was because there was a long, unnecessarily complex, poorly written function that someone didn’t want to pick apart and rewrite. If you use this and you’re not parsing some massive chunk of data, you probably did something shitty and need to take a step back and rethink.</p><blockquote>“You better check yo self before you wreck yo self”</blockquote><blockquote>— Ice Cube</blockquote><h4>Mocking up async</h4><pre>const randomDelay = (maxDelay = 2000) =&gt; <br>     Math.floor(Math.random() * maxDelay);</pre><pre>setTimeout(sendResponse, randomDelay());</pre><p>This is my most common use case for setTimeout. If I know that a component or view is going to be dependent on some async function or data fetch that is not yet available I will often use something like above to mock up the response with a random delay so I can ensure my view works if the data isn’t immediately available.</p><h3>What is a bad use of setTimeout?</h3><p>A big no-no is using setTimeout to fix a race condition (or a “data isn’t ready” bug for those pedantic readers who don’t like the use of the term <em>race condition</em> in a single threaded language like JavaScript). I see this far too often among new devs (and sometimes some not so new devs, yikes).</p><p>One of the hardest things I had to wrap my head around, and still sometimes get hung up on, is controlling the execution flow in an asynchronous environment. The community as a whole is still trying to iron out a good solution (Callbacks, Deferred/Promises, Async, Generators, etc.) At first glance setTimeout seems like a good solution for functions running out of order: it makes sense on the surface. However, it really is just a bandaid over what may be a larger issue in your code.</p><p>If you find yourself in a situation where you think that something is breaking because functions are not happening in the order you expected them too its fine to use setTimeout to test your theory or to push a quick fix <strong>but you should refactor it later.</strong></p><p>Another solution such as using a promise or async function might be best. Wait for the promise/async to resolve and dispatch an event to let your function(s) know the data is ready. This is going to be:</p><ol><li>A far more solid implementation because the function is running based on the resolution of the promise/async and not some arbitrary timer that doesn’t know if the data is actually available or if there was an error</li><li>Much less painful later when other things also depend on that data being available. Imagine you have dozens of functions that rely on this data (i.e. component/view render methods) that could be called at anytime, setTimeout would be all over the place.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*PNV-Adt-F2gs1YdnaUm5lw.jpeg" /><figcaption>You believing that using setTimeout to fix that race condition was a good idea</figcaption></figure><h3>TLDR;</h3><p>setTimeout is a nifty method in JavaScript and definitely has a place in the language but with all things, it can be used for good and evil.</p><ul><li>Know how it works</li><li>Use it when you need it and it makes sense</li><li>Don’t use it to hide bigger underlying problems</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f49d4df11d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>