<?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 Michael Thiessen on Medium]]></title>
        <description><![CDATA[Stories by Michael Thiessen on Medium]]></description>
        <link>https://medium.com/@michaelnthiessen?source=rss-8231a20d92db------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*sv0adAxWEF38hWuD.jpg</url>
            <title>Stories by Michael Thiessen on Medium</title>
            <link>https://medium.com/@michaelnthiessen?source=rss-8231a20d92db------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:54:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michaelnthiessen/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[Props vs Data in Vue]]></title>
            <link>https://medium.com/hackernoon/props-vs-data-in-vue-b619b06ae526?source=rss-8231a20d92db------2</link>
            <guid isPermaLink="false">https://medium.com/p/b619b06ae526</guid>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Michael Thiessen]]></dc:creator>
            <pubDate>Tue, 27 Nov 2018 14:08:09 GMT</pubDate>
            <atom:updated>2019-05-07T07:17:21.518Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qtyqd_6ZEtXgu-k2" /><figcaption>Photo by <a href="https://unsplash.com/@timswaanphotography?utm_source=medium&amp;utm_medium=referral">Tim Swaan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Vue comes with two different ways of storing variables, <strong>props</strong> and <strong>data</strong>.</p><p>These can be confusing at first, since they seem like they do similar things, and it’s not clear when to use one vs the other.</p><p>So what’s the <a href="https://hackernoon.com/tagged/difference">difference</a> between props and data?</p><p><strong>Data is the private memory of each component where you can store any variables you need. Props are how you pass this data from a parent component down to a child component.</strong></p><p>In this article you’ll learn:</p><ul><li>What props are, and why <strong>this data only flows down</strong>, not up</li><li>What the data option is used for</li><li>What <strong>reactivity</strong> is</li><li>How to avoid <strong>naming collisions</strong> between props and data</li><li>How to use <strong>props and data together</strong> for fun and profit 💰</li></ul><h3>What are props?</h3><p>In Vue, <a href="https://vuejs.org/v2/guide/components-props.html">props</a> (or properties), are the way that we pass data from a parent <a href="https://hackernoon.com/tagged/component">component</a> down to it’s child components.</p><p>When we build our applications out of components, we end up building a <a href="https://en.wikipedia.org/wiki/Tree_(data_structure)">data structure called a tree</a>. Similar to a family tree, you have:</p><ul><li>parents</li><li>children</li><li>ancestors</li><li>and descendants</li></ul><p>Data flows down this tree from the root component, the one at the very top. Sort of like how genetics are passed down from one generation to the next, <strong>parent components pass props down to their children</strong>.</p><p>In Vue we add props to components in the &lt;template&gt; section of our code:</p><pre>&lt;template&gt;<br>  &lt;my-component cool-prop=&quot;hello world&quot;&gt;&lt;/my-component&gt;<br>&lt;/template&gt;</pre><p>In this example, we are passing the prop cool-prop a value of &quot;hello world&quot;. We will be able to access this value from inside of my-component.</p><p>However, when we access props from inside of a component, we don’t own them, <strong>so we can’t change them</strong> (just like you can’t change the genes your parents gave you).</p><blockquote><em>Note: While it’s possible to change properties in a component, it’s a really bad idea. You end up changing the value that the parent is using as well, which can cause lots of confusion.</em></blockquote><p>But if we can’t change variables, we’re kind of stuck.</p><p>This is where data comes in!</p><h3>What is data?</h3><p><a href="https://vuejs.org/v2/guide/instance.html#Data-and-Methods">Data</a> is the <em>memory</em> of each component. This is where you would store data (hence the name), and any other variables you want to track.</p><p>If we were building a counter app, we would need to keep track of the count, so we would add a count to our data:</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    {{ count }}<br>    &lt;button @click=&quot;increment&quot;&gt;+&lt;/button&gt;<br>    &lt;button @click=&quot;decrement&quot;&gt;-&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>export default {<br>  name: &#39;Counter&#39;,<br>  data() {<br>    return {<br>      count: 0,<br>    };<br>  },<br>  methods: {<br>    increment() {<br>      this.count += 1;<br>    },<br>    decrement() {<br>      this.count -= 1;<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><p>This data is private, and <strong>only for the component itself</strong> to use. Other components do not have access to it.</p><blockquote><em>Note: Again, it is possible for other components to access this data, but for the same reasons, it’s a really bad idea to do this!</em></blockquote><p>If you need to pass data to a component, you can use props to pass data down the tree (to child components), or events to pass data up the tree (to parent components).</p><h3>Props and data are both reactive</h3><p>With Vue you don’t need to think all that much about when the component will update itself and render new changes to the screen.</p><p><strong>This is because Vue is reactive.</strong></p><p>Instead of calling setState every time you want to change something, you just change the thing! As long as you’re updating a <strong>reactive property</strong> (props, computed props, and anything in data), Vue knows to watch for when it changes.</p><p>Going back to our counter app, let’s take a closer look at our methods:</p><pre>methods: {<br>  increment() {<br>    this.count += 1;<br>  },<br>  decrement() {<br>    this.count -= 1;<br>  }<br>}</pre><p>All we have to do is update count, and Vue detects this change. It then re-renders our app with the new value!</p><p>Vue’s reactivity system has a lot more nuance to it, and I believe it’s really important to understand it well if you want to be highly productive with Vue. Here are <a href="https://vuejs.org/v2/guide/reactivity.html">some more things to learn</a> about Vue’s reactivity system if you want to dive deeper.</p><h3>Avoiding naming collisions</h3><p>There is another great thing that Vue does that makes developing <em>just a little bit nicer</em>.</p><p>Let’s define some props and data on a component:</p><pre>export default {<br>  props: [&#39;propA&#39;, &#39;propB&#39;],<br>  data() {<br>    return {<br>      dataA: &#39;hello&#39;,<br>      dataB: &#39;world&#39;,<br>    };<br>  }<br>};</pre><p>If we wanted to access them inside of a method, we don’t have to do this.props.propA or this.data.dataA. Vue let’s us omit props and data completely, leaving us with cleaner code.</p><p>We can access them using this.propA or this.dataA:</p><pre>methods: {<br>  coolMethod() {<br>    console.log(this.propA);<br>    console.log(this.dataA);<br>  }<br>}</pre><p>Because of this, if we accidentally use the same name in both our props and our data, we can run into issues.</p><p>Vue will give you a warning if this happens, because it doesn’t know which one you wanted to access!</p><pre>export default {<br>  props: [&#39;secret&#39;],<br>  data() {<br>    return {<br>      secret: &#39;1234&#39;,<br>    };<br>  },<br>  methods: {<br>    printSecret() {<br>      console.log(this.secret);<br>    }<br>  }<br>};</pre><p>The real magic of using Vue happens when you start using props and data together.</p><h3>Using props and data together</h3><p>Now that we’ve seen how props and data are different, let’s see why <strong>we need both of them</strong>, by building a basic app.</p><p>Let’s say we are building a social network and we’re working on the profile page. We’ve built out a few things already, but now we have to add the contact info of the user.</p><p>We’ll display this info using a component called ContactInfo:</p><pre>// ContactInfo<br>&lt;template&gt;<br>  &lt;div class=&quot;container&quot;&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br>      Email: {{ emailAddress }}<br>      Twitter: {{ twitterHandle }}<br>      Instagram: {{ instagram }}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>export default {<br>  name: &#39;ContactInfo&#39;,<br>  props: [&#39;emailAddress&#39;, &#39;twitterHandle&#39;, &#39;instagram&#39;]<br>};<br>&lt;/script&gt;</pre><p>The ContactInfo component takes the props emailAddress, twitterHandle, and instagram, and displays them on the page.</p><p>Our profile page component, ProfilePage, looks like this:</p><pre>// ProfilePage<br>&lt;template&gt;<br>  &lt;div class=&quot;profile-page&quot;&gt;<br>    &lt;div class=&quot;avatar&quot;&gt;<br>      &lt;img src=&quot;user.profilePicture&quot; /&gt;<br>      {{ user.name }}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;script&gt;<br>export default {<br>  name: &#39;ProfilePage&#39;,<br>  data() {<br>    return {<br>      user: {<br>        name: &#39;John Smith&#39;,<br>        profilePicture: &#39;./profile-pic.jpg&#39;,<br>        emailAddress: &#39;john@smith.com&#39;,<br>        twitterHandle: &#39;johnsmith&#39;,<br>        instagram: &#39;johnsmith345&#39;,<br>      },<br>    }<br>  }<br>};<br>&lt;/script&gt;</pre><p>Our ProfilePage component currently displays the users profile picture along with their name. It also has the user data object.</p><p>How do we get that data from the parent component (ProfilePage) down into our child component (ContactInfo)?</p><p><strong>We have to pass down this data using props.</strong></p><p>First we need to import our ContactInfo component into the ProfilePage component:</p><pre>&lt;script&gt;<br>import ContactInfo from &#39;./ContactInfo.vue&#39;;</pre><pre>export default {<br>  name: &#39;ProfilePage&#39;,<br>  components: {<br>    ContactInfo,<br>  },<br>  data() {<br>    return {<br>      user: {<br>        name: &#39;John Smith&#39;,<br>        profilePicture: &#39;./profile-pic.jpg&#39;,<br>        emailAddress: &#39;john@smith.com&#39;,<br>        twitterHandle: &#39;johnsmith&#39;,<br>        instagram: &#39;johnsmith345&#39;,<br>      },<br>    }<br>  }<br>};<br>&lt;/script&gt;</pre><p>Second, we have to add in the component to our &lt;template&gt; section:</p><pre>// ProfilePage<br>&lt;template&gt;<br>  &lt;div class=&quot;profile-page&quot;&gt;<br>    &lt;div class=&quot;avatar&quot;&gt;<br>      &lt;img src=&quot;user.profilePicture&quot; /&gt;<br>      {{ user.name }}<br>    &lt;/div&gt;<br>    &lt;contact-info<br>      :email-address=&quot;user.emailAddress&quot;<br>      :twitter-handle=&quot;user.twitterHandle&quot;<br>      :instagram=&quot;user.instagram&quot;<br>    /&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;</pre><p>Now all the user data that ContactInfo needs will flow down the component tree and into ContactInfo from the ProfilePage!</p><p>The reason we keep the data in ProfilePage and not ContactInfo is that other parts of the profile page need access to the user object.</p><p>Since <strong>data only flows down</strong>, this means we have to put our data high enough in the component tree so that it can flow down to all of the places it needs to go.</p><p><em>If you enjoyed this article or have any comments, let me know by replying to </em><a href="https://twitter.com/MichaelThiessen/status/1050425430963052546"><em>this tweet</em></a><em>!</em></p><p><em>Originally published at </em><a href="http://michaelnthiessen.com/vue-props-vs-data/"><em>michaelnthiessen.com</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b619b06ae526" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/props-vs-data-in-vue-b619b06ae526">Props vs Data in Vue</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The correct way to force Vue to re-render a component]]></title>
            <link>https://medium.com/hackernoon/the-correct-way-to-force-vue-to-re-render-a-component-bde2caae34ad?source=rss-8231a20d92db------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde2caae34ad</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Michael Thiessen]]></dc:creator>
            <pubDate>Thu, 11 Oct 2018 20:11:14 GMT</pubDate>
            <atom:updated>2019-05-07T07:17:23.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NwVsSu4YRU-BqLTv" /><figcaption>“body of water under white sky” by <a href="https://unsplash.com/@clement_gerbaud?utm_source=medium&amp;utm_medium=referral">Clément Gerbaud</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometimes Vue’s reactivity system isn’t enough, and you just need to re-render a component.</p><p>Or maybe you just want to blow away the current <a href="https://hackernoon.com/tagged/dom">DOM</a> and start over.</p><p>So how do you get Vue to re-render a component <strong>the right way?</strong></p><p><strong>The best way to force Vue to re-render a component is to set a </strong><strong>:key on the component. When you need the component to be re-rendered, you just change the value of the key and Vue will re-render the component.</strong></p><p>It’s a pretty simple solution, right?</p><p>You’ll be happy to know that there are lots of others ways to do it:</p><ul><li>The horrible way: <strong>reloading</strong> the entire page</li><li>The terrible way: using the <strong>v-if hack</strong></li><li>The better way: using Vue’s built-in <strong>forceUpdate</strong> method</li><li>The best way: <strong>key-changing</strong> on your component</li></ul><p>Except here is where I’m going to ruin it for you.</p><p><strong>If you need to force a reload or force an update, there’s probably a better way</strong>.</p><p>It’s likely that you’re misunderstanding one of the following tricky things:</p><ol><li>Vue’s <strong>reactivity</strong></li><li>Computed props</li><li>Watched props (sometimes)</li><li>Not using a :key attribute with v-for</li></ol><p>Now, there <em>are</em> valid use cases for forcing an update. Most of these will be <strong>solved using the key-changing technique</strong> that’s at the bottom of this article.</p><h3>Horrible way: reload the entire page</h3><p>This is one is equivalent to <strong>restarting your computer every time you want to close an app</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*TMy21a5CKzGY_DX6.gif" /></figure><p>I <em>guess</em> it would work some of the time, but it’s a pretty bad solution.</p><p>There isn’t really much more to say about this. Don’t do it.</p><p>Let’s look for a better way.</p><h3>Terrible way: the v-if hack</h3><p>Vue comes with the v-if <a href="https://hackernoon.com/tagged/directive">directive</a> that will only render the component when it’s true. If it’s false, the component will not exist at all in the DOM.</p><p>Here’s how we set it up for the v-if hack to work.</p><p>In your template you’ll add the v-if directive:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*xT6E3ziYxNDJKGQ_DjWsDg.png" /></figure><p>In your script you’ll add in this method that uses nextTick:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*WIpc3rH-Tz2T34XpDvqvHQ.png" /></figure><p>This is what’s going on here:</p><ol><li>Initially renderComponent is set to true, so my-component is rendered</li><li>When we call forceRerender we immediately set renderComponent to false</li><li>We stop rendering my-component because the v-if directive now evaluates to false</li><li>On the next tick renderComponent is set back to true</li><li>Now the v-if directive evaluates to true, so we start rendering my-component again</li></ol><p>There are two pieces that are important in understanding how this works.</p><p>First, we have to <strong>wait until the next tick</strong> or we won’t see any changes.</p><p>In Vue, a tick is a single DOM update cycle. Vue will collect all updates made in the same tick, and at the end of a tick it will update what is rendered into the DOM based on these updates. If we don’t wait until the next tick, our updates to renderComponent will just cancel themselves out, and nothing will change.</p><p>Second, <strong>Vue will create an entirely new component</strong> when we render the second time. Vue will destroy the first one and create a new one. This means that our new my-component will go through all of its lifecycles as normal — created, mounted, and so on.</p><p><em>On a side note, you can use </em><em>nextTick with promises if you prefer that</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*-N3VaGZEp9qxbyCe0nsRgQ.png" /></figure><p>Still, this isn’t a great solution. I call it a hack because we’re hacking around what Vue wants us to do.</p><p>So instead, <strong>let’s do what Vue wants us to do</strong>!</p><h3>Better way: You can use forceUpdate</h3><p>This is one of the two best ways to solve this problem, both of which are <strong>officially supported by Vue</strong>.</p><p>Normally, Vue will react to changes in dependencies by updating the view. However, when you call forceUpdate, you can force that update to occur, even if none of the dependencies has actually changed.</p><p>Here is where most people make the <strong>biggest mistakes</strong> with this method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*y1USfHK6CtMwdKLq.gif" /></figure><p>If Vue automatically updates when things change, <strong>why should we need to force an update</strong>?</p><p>The reason is that sometimes Vue’s reactivity system can be confusing, and we <em>think</em> that Vue will react to changes to a certain property or variable, but it doesn’t actually. There are also certain cases where <a href="https://vuejs.org/v2/guide/list.html#Caveats">Vue’s reactivity system won’t detect any changes at all</a>.</p><p>So just like the last methods, if you need this to re-render your component, <strong>there’s probably a better way</strong>.</p><p>There are two different ways that you can call forceUpdate, on the component instance itself as well as globally:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*3MtmK3MzJef_QnxxPKTpLA.png" /></figure><p><strong>Important</strong>: This will not update any computed properties you have. Calling forceUpdate will only <a href="https://github.com/vuejs/vue/issues/7395#issuecomment-355721554">force the view to re-render</a>.</p><h3>The best way: key-changing</h3><p>There are many cases where you will have a legitimate need to re-render a component.</p><p>To do this the proper way, we will supply a key attribute so Vue knows that a specific component is tied to a specific piece of data. If the key stays the same, it won’t change the component, but if the key changes, Vue knows that it should <strong>get rid of the old component and create a new one</strong>.</p><p>Exactly what we need!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/0*NOtLh-szxVhSCxQO.gif" /></figure><p>But first we’ll need to take a <em>very short</em> detour to understand why we use key in Vue.</p><h3>Why do we need to use key in Vue?</h3><p>Once you understand this, it’s a pretty small step to understanding how to force re-renders the proper way.</p><p>Let’s say you’re rendering a list of components that has one or more of the following:</p><ul><li>It’s own <strong>local state</strong></li><li>Some sort of <strong>initialization process</strong>, typically in created or mounted hooks</li><li>Non-reactive <strong>DOM manipulation</strong>, through jQuery or vanilla APIs</li></ul><p>If you sort that list, or update it in any other way, you’ll need to re-render parts of the list. But you won’t want to re-render <em>everything</em> in the list, just the things that have changed.</p><p>To help Vue keep track of what has changed and what hasn’t, we supply a key attribute. <strong>Using the index of an array is not helpful here</strong>, since the index is not tied to specific objects in our list.</p><p>Here is an example list that we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*6cioMEIwZiUsoOsT1gmIdQ.png" /></figure><p>If we render it out using indexes we will get this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*FMRLIYjpQsVrMqjKzfZN8Q.png" /></figure><p>Which displays:</p><pre>Evan - 0<br>Sarah - 1<br>James - 2</pre><p>If we remove Sarah, we will get:</p><pre>Evan - 0<br>James - 1</pre><p>The index associated with James is changed, even though James is still James. James will be re-rendered, even if we don’t want him to be.</p><p>So here <strong>we want to use some sort of unique id</strong>, however we end up generating it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*F-4H0OIVTdz13eYwveT4MA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*3CCDrtrPpFa0TeyTjLSrhQ.png" /></figure><p>Before when we removed Sarah from our list, Vue deleted the components for Sarah and James, and then created a new component for James. Now, Vue knows that it can keep the two components for Evan and James, and all it has to do is delete Sarah’s.</p><p>If we add a person to the list, it also knows that it can keep all of the existing components, and it only has to create a single new component and insert it into the correct place. This is really useful, and helps us a lot when we have <strong>more complex components that have their own state, have initialization logic, or do any sort of DOM manipulation</strong>.</p><p>Maybe that detour wasn’t so short. But it was necessary to explain how keys in Vue work.</p><p>Anyways, let’s get on with the best method of forcing re-renders!</p><h3>Key-changing to force re-renders of a component</h3><p>Finally, here is the <strong>very best way</strong> (in my opinion) to force Vue to re-render a component.</p><p>You take this strategy of assigning keys to children, but whenever you want to re-render a component, you just update the key.</p><p>Here is a very basic way of doing it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*dM_GxYfCfY_h4EfaP2TNkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*quIZLMqlTrn-n8lpzhSR9Q.png" /></figure><p>Every time that forceRerender is called, our prop componentKey will change. When this happens, Vue will know that it has to destroy the component and create a new one.</p><p>What you get is a child component that will re-initialize itself and “reset” it’s state.</p><p>A simple and elegant way to solve our problem!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/0*AhFsL6r1r8zug-_6.gif" /></figure><p>Just remember, if you find yourself needing to force Vue to re-render a component, maybe you aren’t doing something the best way.</p><p>If, however, you do need to re-render something, choose the <strong>key-changing</strong> method over anything else.</p><p><em>Check out my articles as soon as they come out at </em><a href="http://michaelnthiessen.com/"><em>michaelnthiessen.com</em></a><em>! I re-post them here a few weeks later.</em></p><p><em>Originally published at </em><a href="http://michaelnthiessen.com/force-re-render/"><em>michaelnthiessen.com</em></a><em>.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde2caae34ad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/the-correct-way-to-force-vue-to-re-render-a-component-bde2caae34ad">The correct way to force Vue to re-render a component</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Checklist for Writing Highly Reusable Components in React and Vue]]></title>
            <link>https://medium.com/hackernoon/checklist-for-writing-highly-reusable-components-in-react-and-vue-531f963864bd?source=rss-8231a20d92db------2</link>
            <guid isPermaLink="false">https://medium.com/p/531f963864bd</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Michael Thiessen]]></dc:creator>
            <pubDate>Tue, 14 Aug 2018 18:13:23 GMT</pubDate>
            <atom:updated>2019-05-07T07:17:23.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N5vG6PgPa7noEPW-" /><figcaption>Photo by <a href="https://unsplash.com/@krisguico?utm_source=medium&amp;utm_medium=referral">Kris Guico</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There are so many best practices and advanced<em> </em>patterns — the problem is keeping track of them and keeping them in mind as you develop new components.</p><p>I wrote this checklist to help myself remember all of the things I need to be thinking about as I go through building highly reusable components.</p><p>This checklist applies equally to <strong>both Vue and React.</strong></p><p>Really, it doesn’t matter which framework you use, since<strong> </strong>the principles of component composition <strong>are exactly the same</strong>. And the general process for designing a component doesn’t change either.</p><p><strong>Condensed checklist at the end of the post.</strong></p><h3>Avoid speculative generality</h3><p>This one sounds pretty obvious, but I find myself forgetting this all the time.</p><p>You need to fully understand <em>your</em> use case, and only implement that. If you just dive into code without thinking first, you’ll end up writing in a bunch of features that will never be used. That’s a <strong>colossal waste</strong> of your precious time.</p><h3>Jared Forsyth on Twitter</h3><p>Over the past couple years I&#39;ve gotten much more sensitive to the cost of speculative generality. So many bugs could have been avoided by just solving the problem at hand instead of trying to solve a ton of potential future problems.</p><p>When writing a component that is supposed to be reused across many different use cases, the temptation to provide more and more abstraction is easier to justify.</p><p>However, if you write the component well, it should be fairly easy to come back later and add in new use cases you couldn’t anticipate.</p><p>This is where <strong>80/20 thinking</strong> comes in handy. A few of the features you implement will be responsible for handling most of the use cases. Focus on those.</p><p>I’ll leave you with one last tweet about API design:</p><h3>Sebastian Markbåge on Twitter</h3><p>Solved problems need constrained APIs. Unsolved problems need unconstrained APIs.&quot; Paraphrasing @cramforce. This really resonates with how I think about framework design. With time you learn a bit more about the right way of doing things, but constraining too early is fatal.</p><h3>Simplify the API</h3><p>Now that we’ve stopped to think, let’s simplify our API as much as possible.</p><p>You’re also trying to find the sweet spot between simplicity and flexibility. As <a href="https://twitter.com/ken_wheeler">Ken Wheeler</a> said in <a href="https://medium.com/codezillas/a-bitter-guide-to-open-source-a8e3b6a3c1c4">A Bitter Guide to Open Source</a>:</p><blockquote>You want to find the perfect balance of working out of the box, and configuring as necessary. On top of that, you want to keep things clear, explicit and approachable. Don’t be too clever or you will piss everyone off.</blockquote><p>Too simple and it doesn’t cover enough use cases to be helpful. Too flexible and it becomes too difficult to understand how to do anything.</p><p>Just take a look at how many options this <a href="http://api.jqueryui.com/datepicker/">jQuery Datepicker</a> has. It’s terrifying!</p><p>This is where more advanced composition patterns really come in handy.</p><p>Typically you’re making trade offs between simplicity and flexibility. But techniques like <strong>render props</strong> and <strong>compound components</strong> allow you to achieve <strong>more flexibility while reducing complexity.</strong></p><h3>Research prior art</h3><p>We have a pretty good idea of what we we’re building now, but first we need to see what else is out there.</p><p>There are a few reasons for this:</p><p>First, we can <strong>get great ideas</strong> for our implementation.</p><p>If we look at mature open source projects, they will be more or less feature complete. This lets us double-check our assumptions about what we might need to build out.</p><p>We can also see how the API was built, what abstractions were used, and possibly even some implementation details we wouldn’t have considered.</p><p>Second, we can potentially <strong>save ourselves some work</strong>.</p><p>There’s a good chance we’ll find something that we can use to speed up development. We may even find something that ticks all our needs, and end up short-circuiting this whole process.</p><p>In his <a href="https://courses.totalreact.com/p/advanced-react-free">Advanced React.js course</a>, <a href="https://twitter.com/ryanflorence">Ryan Florence</a> mentions that he likes to check out jQuery plugins. They’ve stood the test of time, and likely have all the features that you’d ever consider putting in a UI element.</p><p>A great place to start is in the Awesome repos:</p><ul><li><a href="https://github.com/enaqx/awesome-react">Awesome-React</a></li><li><a href="https://github.com/vuejs/awesome-vue">Awesome-Vue</a></li></ul><h3>Break up components into bite-sized pieces</h3><p>Compositional frameworks use components as their main technique of abstraction (vs. objects in OO or functions in functional programming).</p><p>If you shove everything into one or two giant components, you aren’t taking advantage of this at all!</p><p>Smaller components are better:</p><ul><li>Better abstraction makes your <strong>code cleaner</strong>, easier to understand, and easier to maintain</li><li>Encourages <strong>reusability</strong> of the code</li><li>Necessary in order to use more <strong>advanced</strong> fancy-pants composition techniques</li></ul><p>There are a couple main ways to think about splitting up components:</p><h4><strong>Isolating behaviour from presentation</strong></h4><p>You have <strong>state and logic</strong> in one component, with a separate component responsible for rendering. We would typically do this through render props and stateless functional components.</p><h4>Levels of abstraction</h4><p>It’s often a good idea to keep the level of abstraction consistent within a component. Either the component would deal with native DOM elements, like div, p, span, or it would deal with framework components.</p><p>Just be careful, because you don’t want to go overboard and create <strong>too many components</strong>! <a href="https://twitter.com/kentcdodds">Kent C. Dodds</a> has a great article on <a href="https://blog.kentcdodds.com/when-to-break-up-a-component-into-multiple-components-4ee75ab53bbc">how to know when things should be split up</a>.</p><h3>Use powerful composition patterns — only where needed</h3><p>Render props, provider pattern, higher order components. These patterns are seductive and fun to use.</p><p>But they are not always the right tool for the job. Knowing when to use each one to it’s maximum effect is important. Otherwise <strong>you may use the wrong tool</strong> for the job and dig yourself into a hole.</p><p>If you want to learn more about these, I highly suggest checking out Kent C. Dodd’s article on <a href="https://blog.kentcdodds.com/advanced-react-component-patterns-56af2b74bc5f">advanced patterns in React</a>:</p><h4>Compound components</h4><p>Break up parts of your component into smaller bits that can be recombined in different ways.</p><p>For example, take your Table component and break it down into TableHeader, TableBody, and TableFooter components. Most people will be fine to use the regular Table, but now someone can build their own table and build a custom header for it without too much trouble.</p><h4>Higher order components</h4><p>Take a component and wrap it up inside another component to <strong>add functionality</strong> to it. This concept evolved from the object-oriented idea of mixins, but has largely replaced it (although Vue still has supports mixins).</p><p>When React first came on the scene, mixins gave developers an escape hatch, allowing them to go back to something familiar from the object-oriented world.</p><p>After awhile we figured out that <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750">composition is far better than inheritance,</a> so higher order components became the norm.</p><h4>Render props and renderless components</h4><p>Now we’re seeing another shift. This time away from higher order components, and towards what are called <em>render props</em> (or <em>function as children).</em></p><p>Render props let us <strong>delegate rendering</strong> to the parent component, giving us even cleaner separation between behaviour and presentation. If you combine this pattern with the prop getters and setters pattern, you can build incredibly flexible and expressive components with very few lines of code.</p><h4>Controlled and uncontrolled props</h4><p>Does the component control the state, or does it’s parent control the state? That is the difference between an uncontrolled and a controlled prop.</p><p>Generally, uncontrolled props are used since they allow us to encapsulate complexity and state within the component. However, if you want more flexibility — which we need when writing a highly reusable component — you can allow a prop to be controlled by the parent.</p><h4>State reducer</h4><p>This is a pattern I learned from Kent C. Dodds in his project <a href="https://github.com/paypal/downshift">Downshift</a> (<a href="https://blog.kentcdodds.com/when-to-use-control-props-or-state-reducers-6cd83e42c5b">more explanation here</a>).</p><p>If you’re going to expose a prop to be controlled, why not expose the entire state reducer? Then <strong>you can have extremely fine-grained control</strong> over the behaviour of the component — but you don’t have to re-write any logic.</p><p>Brilliant.</p><h4>Provider pattern</h4><p>If you’ve used Redux or VueX or something similar, you probably know this pattern.</p><p>Instead of passing props around all day long, and passing them down through many many levels of components, you simply “inject” them where they need to be.</p><p>In React this can be done <a href="https://reactjs.org/docs/context.html">using context</a>, or <a href="https://vuejs.org/v2/api/#provide-inject">provide and inject</a> in Vue.</p><h3>Accessibility is not an afterthought</h3><p>I’m not very good at accessibility yet.</p><p>It’s something I’ve been getting better at recently though, because I believe <strong>it’s incredibly important</strong> to making the web a better place.</p><p>Since I’m not an a11y expert, I’ll instead get you to read this article <a href="https://twitter.com/addyosmani">Addy Osmani</a> wrote on <a href="https://medium.com/@addyosmani/accessible-ui-components-for-the-web-39e727101a67">developing accessible web components</a>. You can also check out the great resources of <a href="https://a11yproject.com/">The A11Y Project</a>.</p><p><a href="https://medium.com/@addyosmani/accessible-ui-components-for-the-web-39e727101a67">Accessible UI Components For The Web</a></p><h3>Make it easy to style</h3><p>How easy is it for consumers to <strong>style your component</strong> the way they need?</p><p>The intention is that your component will be used all over the place. In all sorts of wild and various contexts. It will be used in ways <em>you could never have imagined even in your weirdest dreams</em>.</p><p>You need to make sure that other devs can easily style and change the layout of your component without resorting to ugly CSS overrides.</p><p>Renderless components make this super simple. You can just <strong>delegate all rendering</strong> to whoever is using your component.</p><p>However, in many cases it’s useful to render something by default. A good approach here is to <a href="https://medium.com/@GarrettLevine/react-components-b-e-m-168f199f35b">use BEM in your component</a> and provide CSS classes that can be easily overriden.</p><h4>But CSS isn’t Turing complete!</h4><p>Alternatively, you can take the <strong>cool-kid approach</strong> and use CSS-in-JS (it’s not for everyone).</p><p>When this idea started out, most libraries were implemented using inline styles. This caused some performance issues and had some other issues as well.</p><p>Nowadays, most libraries work by <strong>dynamically attaching stylesheets</strong> to the DOM, and the biggest issues have been resolved. I haven’t had a chance to dive into these in awhile, but it’s on my list!</p><p>There’s tons of libraries, talks, and articles out there about this if you want to learn more, but <a href="https://hackernoon.com/all-you-need-to-know-about-css-in-js-984a72d48ebc">here is a good place to start for React</a>, and <a href="https://github.com/styled-components/vue-styled-components">here for Vue</a>.</p><h3>Do you even test, bro?</h3><p>You don’t want tons of people using your beautiful new component, only to have it flake out on edge cases. Or heaven forbid you add a slick new feature — but it breaks everything else.</p><p>When you’re building a reusable component like this you probably won’t do any integration or end-to-end testing. You’ll be writing <strong>unit tests</strong> that focus on testing tricky logic and making sure the component is rendering properly.</p><p>Here are a few great articles on testing React and Vue components if you need to get started:</p><ul><li><a href="https://www.fullstackreact.com/30-days-of-react/day-22/">Fullstack React: Introduction to Testing</a></li><li><a href="https://alexjoverm.github.io/series/Unit-Testing-Vue-js-Components-with-the-Official-Vue-Testing-Tools-and-Jest/">Unit Testing Vue.js Components with the Official Vue Testing Tools and Jest | Alex Jover Morales</a></li></ul><h3>Documentation — It’s what makes all the difference</h3><p>“I’ll write the docs later”, you think to yourself as you push the last beautiful crafted commit to Github. “I mean, even if I don’t get to it <strong>no one will really care</strong>.”</p><p>After all, you’re a professional at writing in <a href="https://hackernoon.com/tagged/javascript"><em>Javascrip</em></a><em>t</em>, not one of these “<a href="https://hackernoon.com/tagged/natural">natural</a>” languages that humans speak.</p><p>But great documentation is what turns a good component into <strong>a great component</strong>.</p><p>You know the feeling when you’re trying to figure out how to get a library to do something, or you get confused about React’s (or Vue’s) lifecycle methods. If you can’t find the answer quickly, it’s super frustrating.</p><p>Sometimes you’ll even get rid of the library because <strong>you can’t figure out</strong> how to get it to work!</p><p>Don’t let your shiny, brand new component to go to waste because of a lack of good documentation.</p><h3>Condensed Checklist</h3><p>Now that we’ve gone through all of that, here is the easy-to-reference version:</p><h4>Avoid speculative generality</h4><h4>Simplify the API</h4><h4>Research prior art</h4><h4>Break up components into bite-sized pieces</h4><ul><li>Separate state + behaviour from presentation</li><li>Split up by level of abstraction</li></ul><h4>Use powerful composition patterns — only where needed</h4><ul><li>Compound components</li><li>Higher order components</li><li>Render props and renderless components</li><li>Controlled/Uncontrolled props</li><li>State reducer</li><li>Provider pattern</li></ul><h4>Accessibility is not an afterthought</h4><h4>Make it easy to style</h4><h4>Do you even test, bro?</h4><h4>Documentation — It’s what makes all the difference</h4><p><em>Check out my articles as soon as they come out at </em><a href="http://michaelnthiessen.com/"><em>michaelnthiessen.com</em></a><em>! I re-post them here a few weeks later.</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Fdde502%3Fas_embed%3Dtrue&amp;dntp=1&amp;url=https%3A%2F%2Fupscri.be%2Fhackernoon%2F&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href">https://medium.com/media/3c851dac986ab6dbb2d1aaa91205a8eb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=531f963864bd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/checklist-for-writing-highly-reusable-components-in-react-and-vue-531f963864bd">Checklist for Writing Highly Reusable Components in React and Vue</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>