<?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[Frontmen - Medium]]></title>
        <description><![CDATA[Frontmen, frontend experts - Medium]]></description>
        <link>https://medium.com/frontmen?source=rss----db21d8172a0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Frontmen - Medium</title>
            <link>https://medium.com/frontmen?source=rss----db21d8172a0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 09:34:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/frontmen" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Boost your React application’s performance by Xstate]]></title>
            <link>https://medium.com/frontmen/boost-your-react-applications-performance-by-xstate-cc7d5588805f?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/cc7d5588805f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[xstate]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Alireza Valizadeh]]></dc:creator>
            <pubDate>Thu, 25 Feb 2021 10:27:55 GMT</pubDate>
            <atom:updated>2021-02-25T15:21:55.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taR9Lsd3KRgUK8-hvdCOeA.jpeg" /></figure><h4>Performance</h4><p>Is one of the important keys in every application to have better UX and make users happier (of course you may not care about users happiness, but it makes yourself happier 😃 Because you want to do something in a best way and you enjoy it). Performance is different on the web based applications it depends on the tools you choose and how you use them specially on low memory devices like TVs and Mobiles.</p><h4>State Management</h4><p>There are a lot of libraries out there that you just install and use them in your project. Some people just using the Context Api it self which is powerful and easy to use, but also has some downsides like unnecessary re-renders, Take a look at this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d539752c1ca92c714a2dd0916ee6bb4/href">https://medium.com/media/5d539752c1ca92c714a2dd0916ee6bb4/href</a></iframe><p>As you can guess, All the nested components get re-render, You are thinking that I’m wrong I can use <em>useMemo() </em>or split the component in two and use <em>memo()</em> , <strong>But everything has a cost so better to avoid them! </strong><a href="https://kentcdodds.com/blog/usememo-and-usecallback">Checkout this interesting article here</a> from <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a> If you see the console.count() results in the console then it means React started the <a href="https://reactjs.org/docs/reconciliation.html">reconciliation</a> process to detect the diffs there in virtual dom. Sometimes this process is not fast enough and you will see the issues and it becomes slow by decreasing frames, sometimes lags in animation like close a Modal. Again checkout this article from <a href="https://medium.com/u/db72389e89d8">Kent C. Dodds</a> to understand better these downsides in React.</p><p>This is just small example and you won’t see the affects but imagine you have thousands of components there. It was really important to me to avoid these kinds of unnecessary re-renders in the application and only update the part that really needs to be update.</p><p>Today going to talk about the Xstate and It benefits to share the state between the application.</p><h4>What is Xstate?</h4><p><a href="https://xstate.js.org/docs/">Based on the documents the definition of Xstate is:</a></p><blockquote>JavaScript and TypeScript <a href="https://en.wikipedia.org/wiki/Finite-state_machine">finite state machines</a> and <a href="https://www.sciencedirect.com/science/article/pii/0167642387900359/pdf">statecharts</a> for the modern web.</blockquote><p>And a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2932779d6f60649657e3c68d2afca1d4/href">https://medium.com/media/2932779d6f60649657e3c68d2afca1d4/href</a></iframe><p>Let’s say we have a music streaming application that user can add/remove items from the library, So the flow will be:</p><ol><li>Authentication</li><li>Getting User Profile Information (also on refreshing page to detect if user is already logged in)</li><li>Getting User Library Information (Musics, Videos, Podcasts and more…- We need this information everywhere not only in one page)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9glz64rTSDNoBJDoiSD3hQ.png" /></figure><p>This sounds really easy and straght forward without Xstate, Isn’t?</p><p>It’s possible but it’s not good and clean enough, So the answer is a <strong>NO</strong>:</p><ol><li>You need to define the states yourself</li><li>You need to define the loadings states yourself</li><li>Your logic and your components getting mixed together, A lots of useEffect(), useState(), useCallback, Promise().then().catch() and callbacks</li><li>You need to create guards in all the actions, For example you need to check if the latest library is loaded then you can add or remove to/from library</li><li>A lots of setState since the datas need to be store somewhere and need to be reactive, <strong>This means a lots of re-renders</strong></li><li>Hard to debugging since you don’t know the states</li><li>Hard to have control on the flow</li></ol><p>I’m sure there are more.</p><p>Behind the state management Xstate gives you powerful control on the flow and different states. If you’re not familiar with the <a href="https://xstate.js.org/docs/">Xstate first take a look at the documents</a> since this post is not about learning Xstate it’s about using it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b21938cf0fba0b945cd1d276b4c7cc14/href">https://medium.com/media/b21938cf0fba0b945cd1d276b4c7cc14/href</a></iframe><p><a href="https://xstate.js.org/viz/">See the result in visiualizer</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*cg1rF1gww2DFBYUzf65dxg.png" /></figure><p><strong>THIS IS REALLY COOL!</strong> You can define all the steps in the machine and transition between them using events or states itself by target key.</p><h4>Using the machine</h4><p>In a normal way there are some helpers from @xstate/react package, like useMachine() :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5245bc07ee1294eddabcddc8bb8e20a/href">https://medium.com/media/c5245bc07ee1294eddabcddc8bb8e20a/href</a></iframe><p>All is good, We have 3 different components:</p><ol><li>LibraryHandler: It doesn’t needs to be update at all since it’s only injected actions.</li><li>LibraryPresent: It only needs to be update when the library.mp3s item has been updated in the store.</li><li>UserProfile: It only needs to be update when user item has been updated in the store.</li></ol><p><strong>But</strong> we didn’t solve the issue yet, We still will get those nasty unnecessary re-renders and we wan’t to avoid using memoize helpers. So we need atomic updates, We need to run the machine without passing the state to provider, Here is the place that interpret and useService hook will shine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c178c205028d4dfbedc17d197ce2aaef/href">https://medium.com/media/c178c205028d4dfbedc17d197ce2aaef/href</a></iframe><p>The appService function will return the service, Eeach service has some useful methods but what we need here are:</p><ol><li>start(): to start a service</li><li>stop(): to stop a service</li><li>send(): to send events</li><li>subscribe(): to listen to changes</li></ol><p>We need to update our AppProvider component and provide the service instead of state directly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40db91be127f238066cf2b15fc3a75c6/href">https://medium.com/media/40db91be127f238066cf2b15fc3a75c6/href</a></iframe><p>So far so good! You see selectors object above that I’ll explain it in a bit.</p><p>Let’s create the subscriber hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea9d47466bbe6806539526002ec068cf/href">https://medium.com/media/ea9d47466bbe6806539526002ec068cf/href</a></iframe><p>This hooks takes two main arguments:</p><ol><li><strong>service: A service that has been started</strong></li><li><strong>selector: A function that receive the state and returns a specific data</strong></li></ol><p>What’s going here?</p><p>It’s easy instead of having one global subscriber we have multiple subscribers, And when the component unmounted we unsubscribe the service. This is kind of same as redux selectors are working.</p><p>Let’s update the components that needs the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40b6d9bbc4a3a881896f838cbab3f2c0/href">https://medium.com/media/40b6d9bbc4a3a881896f838cbab3f2c0/href</a></iframe><p>Yes this is exactly what we need to get out of the re-render hell in React apps with xstate.</p><h4>Summing up</h4><p>xstate is definitely one of the coolest thing that I have ever worked with it in our applications. It’s helpful for managing the complicate states there are a lot of cooler things that you can do with it. shout out to <a href="https://medium.com/u/3b9ee2f9eaa2">David Khourshid</a> for creating it.</p><p>Thanks for reading, If there is anything I have missed or if there is a better way to do something, Then please let me know. I’d be happy 🤓</p><p>You can find me on <a href="https://github.com/alirezavalizade">Github</a> and <a href="https://twitter.com/alirezavlizade">Twitter</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7d5588805f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/boost-your-react-applications-performance-by-xstate-cc7d5588805f">Boost your React application’s performance by Xstate</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React developers will love the Vue Composition API]]></title>
            <link>https://medium.com/frontmen/react-developers-will-love-the-vue-composition-api-91424d221419?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/91424d221419</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[composition]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Steven Straatemans]]></dc:creator>
            <pubDate>Tue, 12 Nov 2019 10:56:21 GMT</pubDate>
            <atom:updated>2019-11-18T21:52:58.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOtzmsQDql4vQ7jEfKCAoQ.jpeg" /><figcaption>Vasily Kandinsky (1866–1944): Composition 8 (Komposition 8)</figcaption></figure><p>Ok, let me be clear first. I’m not really big on Vuejs. I like React. And not just the way of writing Class components. No I like the functional components. Just functions, love it!</p><p>A colleague asked me, last October, to do a meetup talk with him about Vue and especially about it&#39;s Composition-API. It was a new API, still in the RFC status. But you could use it and it looked really promising.<br>I nodded and smiled, when all the while, my head was desperately thinking about a way out of it. Vue? I don’t know anything about Vue. What was he thinking? Sure, I did a small project with it once. But to do a talk about it? And to say I fell in love with Vue at that time? Not really, no. I really liked the reactivity of Vue, but I found it weird to create these component objects and have these options where I can have my functionality.</p><p>While my head was filling with excuses to get out of it, my colleague talked more about this API. At least I think he did. His mouth was moving, I wasn’t really paying attention. I started paying attention when he mentioned that the old RFC for this API was called Vue-hooks. Why didn&#39;t he say that in the first place?</p><p>Because last year, when I was at React Conf 2018 they announced React Hooks. I.was.excited! No more writing classes, no more componentDidMount, componentWillUnmount or componentWillReceiveProps. Just functions. I started using hooks in my projects and never looked back.</p><p>Anyway, I started investigating this Vue API and turns out it works really nice. And on top of that, in some aspects I like it better than the React hooks (but don&#39;t tell the React community).</p><p><strong>But Vue is fine as it is?<br></strong>Ok Vue works really nice. It&#39;s fast. It has that reactivity going for it. But it has it&#39;s problems as well. The same problems that React had to deal with by the way. <br>1. When components become big, it becomes harder to read the code.<br>2. There is no nice way to extract the code from the component and make it re-usable.</p><p>The first problem is this; the standard way that components are written in Vue. It&#39;s an object with some options where you put your functionality, like methods, data, computed, etc. By the way, from now on, I will call this the Option-based API, because…uhh…, well like so many others do.<br>In this API the code is written per option not by functionality. Basically what this means is this. When you have a component, which has some filter functionality in it, it will have some functionality in the methods, in the data, maybe in computed.</p><pre># App.vue</pre><pre>export default {<br>  name: &quot;app&quot;,<br>  data: () =&gt; ({<br>    ...<br>    visibility: &quot;all&quot;<br>    ...<br>  }),<br>  computed: {<br>    filteredTodos: function() {<br>      return filters[this.visibility](this.todos);<br>    },<br>    ...<br>    ...<br>  },<br>  methods: {<br>    ...<br>    ...<br>    filterAll: function() {<br>      this.visibility = &quot;all&quot;;<br>    },<br>    ...<br>  }<br>};</pre><p>In a small component, this is fine, but when the component gets larger, it will be hard to find the forest through the trees. Especially for other developers in your team, who need to change something in your component.<br>The new Composition API will get rid of the options and have all the functionality within one <em>setup</em> method. Here you can order all the functionality next to each other for easy readability.</p><p>The second problem is the issue of reusability. Because all the code is divided in the different options, it&#39;s harder to extract the code from the component and make it reusable.<br>With the Composition-API you can extract all the methods, data, watchers, etc for one specific functionality in to a composition function and save it somewhere in a different file. Ready to be used by whatever component you want. And then call on that composition function in your setup method of your component.</p><p><strong>But what about Mixins?</strong><br>True, mixins, or even Higher-order components, make it possible to extract the code from the component and gives you the ability to reuse the code in other components. There are a couple of downsides though.<br>For example when you import a mixin in your component it&#39;s not clear what the mixin exposes to the component. It just says the name of the mixin.</p><pre># App.vue</pre><pre>export default {<br>  mixins: [filterMixin],<br>  ...<br>};</pre><p>You would have no idea what this filterMixin does for your component, other than what the name of the mixin tells you.<br>This will become an even bigger problem when you have multiple mixins. It makes it really hard to debug a certain property, if you don&#39;t know where it&#39;s coming from.<br>It is also possible that 2 different mixins expose a method with the same name and different functionality.</p><p>The Composition API doesn&#39;t have these problems, because the properties need to be explicitly exposed from the composition function before they can be used. And when 2 of the methods turn out to have the same name, they can be renamed to what ever you want. So no name clashing.</p><p><strong>So I have to learn all these new things?</strong><br>Don&#39;t worry. You don&#39;t have to learn anything new, if you don&#39;t want to. If you want, everything will stay the same in Vue. It&#39;s just an extra tool under your belt. You can even use the Composition API and the Option-based API in the same component. The most important thing is:<br>This is not new functionality. The Composition API just exposes Vue Core functionality. But then as standalone functions. We will see that later when we work with the API.</p><p><strong>Sounds nice. Can I use it?<br></strong>The API will be standard available in the new Vue 3. One small problem though. There is no official release date yet for version 3. At the moment of writing it is still in the Pre-Alpha stage. And on the official roadmap the official release is scheduled for the first quarter of 2020(<a href="https://github.com/vuejs/vue/projects/6?ref=madewithvuejs.com">https://github.com/vuejs/vue/projects/6</a>).</p><p>But the good news is that the Composition API is compatible with Vue 2 as well and can be installed as a plugin.</p><p><strong>I want to see it in action!<br></strong>Sure, lets dive into some code. For the example I customized this Fiddle in the Vue Docs (<a href="https://jsfiddle.net/yyx990803/4dr2fLb7/?utm_source=website&amp;utm_medium=embed&amp;utm_campaign=4dr2fLb7">https://jsfiddle.net/yyx990803/4dr2fLb7/?utm_source=website&amp;utm_medium=embed&amp;utm_campaign=4dr2fLb7</a>). I removed some code to make the project a bit simpeler. And moved some functions to a mixin.<br>What is left is a simple to do list with some nice styling. It fits our needs perfectly. It has something of everything. It has some data, computed values, watchers, methods and a mixin. We are ready to start.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffrontmen-vue-compositionapi-start-3w4cw%3Ffontsize%3D14%26module%3D%252Fsrc%252FApp.vue%26view%3Deditor&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ffrontmen-vue-compositionapi-start-3w4cw%3Ffontsize%3D14%26module%3D%252Fsrc%252FApp.vue%26view%3Deditor&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3w4cw%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/5123ff9b65abad5b2f2f430a533a58b3/href">https://medium.com/media/5123ff9b65abad5b2f2f430a533a58b3/href</a></iframe><p><strong>Lets start at the very beginning. A very good place to start.</strong><br>First we need to install the node package for the composition-API plugin.</p><pre>npm install @vue/composition-api — save</pre><p>after that we just need to add the plugin to our <em>main.js</em></p><pre># main.js</pre><pre>import VueCompositionApi from ‘@vue/composition-api’; Vue.use(VueCompositionApi);</pre><p>That&#39;s all there is to it. Now we are ready to use hooks! uhh…the Composition-API. <br>First thing we need to do is add the setup option to our <em>App.vue</em></p><pre># App.vue</pre><pre>export default {<br>  name: &#39;app&#39;,<br>  setup() {</pre><pre>  },<br>  ...</pre><p><strong>So you add another option?<br></strong>Uhm…yes. I know this was about removing options from the object. But things need to get worse before they get better.<br>In this method all the rest of the action will happen. There are some things you need to know about the setup method.<br>The method is called right after the component instance is created and before the <em>beforeCreate() </em>lifecycle (<a href="https://vuejs.org/v2/guide/instance.html">https://vuejs.org/v2/guide/instance.html</a>).</p><p><strong>Update</strong>: In the first version of this article I stated that the <em>setup</em> method runs after the <em>beforeCreate</em> lifecycle. This is not the case. It runs before the <em>beforeCreate</em> and after the component instance is created. Thanks to <a href="https://medium.com/@PrashantPalikhe">Prashant Palikhe</a> for pointing this out.</p><p>It resolves before other 2.x options like <em>data</em>, <em>computed</em> and <em>methods</em>. So it will have no access to properties defined there.<br>But, because it resolves first, everything the <em>setup</em> method returns is exposed to the <em>this</em> context and therefor they can be used by the 2.x options. <br>This means that the Composition API and the normal Options-based API can be used together in the same component. Which is really useful when refactoring as we will see later.</p><p>The <em>setup</em> method has 2 optional properties:</p><pre>setup(props, context);</pre><p><em>Props</em> are just the properties that are given to the component.<br><em>Context</em> exposes properties previously accessed using <em>this</em> (attrs, slots, parent, root, emit).</p><p>In the setup method we also find the biggest difference with the React hooks. And what I think consider to be an improvement on the Composition API from the hooks from React.<br>And that is in the way that React and Vue work on the inside.<br>React has certain rules that you need to follow when implementing hooks. If you don&#39;t follow these rules strange things can happen during rendering. So much so that they have created an Eslint plugin for this, that they highly recommend you use. Don’t call Hooks inside loops, conditions, or nested functions (<a href="https://reactjs.org/docs/hooks-rules.html">https://reactjs.org/docs/hooks-rules.html</a>).<br>These rules exist because the effects in a React component run every time the component is rendered and re-rendered. If they are in a conditional statement they sometimes exist and sometimes don&#39;t. Which can give really strange side-effects.<br>Because the setup method only runs once, Vue does not have this problem. So if a hook is in a conditional it will be called or it won&#39;t. The effect stays the same in the entire lifespan of the component instance.</p><p><strong>Ok enough about setup. Now what?</strong><br>Now we can start to move functionality from the options to the setup method.<br>Let&#39;s start with the data. There are 2 ways to create state in the Composition API. Let&#39;s import them and take a look.</p><pre>import { ref, reactive } from ‘@vue/composition-api’;</pre><p>There is the ref and the reactive method.<br>What <em>ref</em> does, is taking the given value and turn in into a reactive object. When you would console.log it you would see a getter and setter and a value.<br>This means you can&#39;t do this:</p><pre>const counter = ref(0);<br>counter++; // NaN</pre><p>This will result in <em>NaN</em>, because counter is an object. The correct way would be this:</p><pre>const counter = ref(0);<br>counter.value++; // 1</pre><p>When adding the property to the template you don&#39;t have to use the <em>.value</em>. The template will recognise that this is a reactive object and will add the <em>.value</em> itself.</p><p>Don’t forget to return the object at the end of the setup method. Only the things returned at the end of setup can be used by the template.</p><p>Then there is the second method, <em>reactive</em>.<br>This also creates a reactive object, but the effect goes deep, so every attribute will be reactive as well. The upside of using reactive is that you don&#39;t have to use the .value to get the value of an attribute. This is done by the object itself.<br>Beware, you can&#39;t destructure the object to seperate properties. Because the object takes care of the reactivity, when you destructure all you are left with are the normal values. And used in the template nothing will update.<br>Luckily there is a helper function that will help you to get around this problem. This helper will create ref objects from every property and you can do this. It&#39;s called <em>toRefs</em> and you just need to import it.</p><pre>return {…obj}; // will loose the reactivity</pre><pre>import { toRefs } from ‘@vue/composition-api’;<br>return {...toRefs(obj)}; // will destructure to seperate ref objects</pre><p>Our refactored setup will now look something like this:</p><pre># App.vue</pre><pre>...<br>setup() {<br>  const newTodo = ref(&#39;&#39;);<br>  const visibility = ref(&#39;all&#39;);<br>  const state = reactive({ todos: todoStorage.fetch() });</pre><pre>  return {<br>    newTodo,<br>    visibility,<br>    todos: state.todos,<br>  };  <br>},<br>...</pre><p><strong>So when do I use ref and when reactive?</strong><br>That is a good question and even the Vue team doesn&#39;t have a clear answer when to use what. I would say use <em>ref</em> for primitives and <em>reactive</em> for objects, just like you would normally use them. It feels like you are doing the same as normal.</p><p><strong>Next up, methods</strong><br>It doesn&#39;t matter if the methods are in the methods-option or in a mixin. We can move them to the setup. There is nothing to import from the Composition-API. It&#39;s just functions, but we do need to do some refactoring.</p><pre># App.vue</pre><pre>methods: {<br>  addTodo: function() {<br>    var value = this.newTodo &amp;&amp; this.newTodo.trim();<br>   if (!value) {<br>     return;<br>   }<br>   this.todos.push({<br>     id: todoStorage.uid++,<br>     title: value,<br>     completed: false,<br>   });<br>   this.newTodo = &#39;&#39;;<br> },<br>}<br>...</pre><p>And when we move it to the <em>setup</em> method it will look like this:</p><pre>setup() {<br>  const addTodo = () =&gt; {<br>    let value = newTodo &amp;&amp; newTodo.value.trim();<br>    if (!value) {<br>     return;<br>    }<br>    state.todos.push({<br>      id: todoStorage.uid++,<br>      title: value,<br>      completed: false,<br>    });<br>    newTodo.value = &#39;&#39;;<br>  }<br>}</pre><p>First thing you&#39;ll notice is that we removed the <em>this</em> context. It&#39;s not needed in the <em>setup</em> method. And because <em>setup</em> resolves before other Option-based methods, everything that is returned from the <em>setup</em> method is accessible from <em>this</em>.<br>So we removed <em>this</em>. We also need to remember that the <em>newTodo</em> is now a reactive object, so when we want the value from that object we need to do that by calling the <em>.value</em> property.<br><em>Todos</em> is now also in a reactive object and is part of the <em>state</em>. So we call <em>state.todos</em>.<br>Nothing more to do then to return the method from the setup. And do all the other methods as well. This also means also the methods that are in the mixin. Now we can remove the methods and the mixin option from the component. Bye bye.</p><p><strong>Seems easy. Now do the computed values<br></strong>We have 2 computed values in our component:</p><pre># App.vue</pre><pre>...<br>computed: {<br>  filteredTodos: function() {<br>    return filters[this.visibility](this.todos);<br>  },<br>  remaining: function() {<br>    return filters.active(this.todos).length;<br>  },<br>},<br>...</pre><p>There is nothing more to do than to import the computed method and add them to the setup method. Don&#39;t forget to return them, so we can use the values in the rest of the component.</p><pre># App.vue</pre><pre>import { ref, reactive, computed } from &#39;@vue/composition-api&#39;;<br>...<br>setup() {<br>  const filteredTodos = computed(() =&gt; {<br>    return filters[visibility.value](state.todos);<br>  });<br>  const remaining = computed(() =&gt; {<br>    return filters.active(state.todos).length;<br>  });</pre><pre>...<br>},<br>...</pre><p>Let&#39;s do that small watcher also. Import the watch &#39;hook&#39;:</p><pre># App.vue</pre><pre>import { ref, reactive, computed, watch } from &#39;@vue/composition-api&#39;;<br>...<br>setup(){<br>  watch(() =&gt; todoStorage.save(state.todos));</pre><pre>...<br>},<br>...</pre><p>When the setup runs, the watcher functions will be called once, so that Vue can register the reactive objects that are used in the watcher. Whenever one of those objects change, the registered watchers also run.</p><p>After this, you can remove the watch and computed options from the component and don&#39;t forget to return the computed values. You don&#39;t need to return the watcher. Once that is registered it will do things by itself.</p><p>And now we refactored all the Option-based API stuff into the new Composition-API.</p><pre># App.vue</pre><pre>export default {<br>  name: &#39;app&#39;,<br>  setup() {<br>    ...<br>    return {<br>      ...<br>    };<br>  },<br>};</pre><p>It&#39;s…so beautiful.</p><p><strong>It&#39;s a mess!</strong><br><em>So you moved all the functionality from 4 options to 1. Good job. The setup method is one big pile of junk. It&#39;s a mess!<br></em>True. We are not completely finished yet. Because although we have dumped everything in one big method, you can see that all things can be arranged by functionality. We can have all the things doing with Todo next to each other and all the filter stuff as well.</p><p>Let&#39;s take the filter functionality as an example.</p><pre># App.vue</pre><pre>...<br>const visibility = ref(&#39;all&#39;);  <br>const filterAll = () =&gt; {<br>  visibility.value = &#39;all&#39;;<br>};<br>const filterActive = () =&gt; {<br>  visibility.value = &#39;active&#39;;<br>};<br>const filterCompleted = () =&gt; {<br>  visibility.value = &#39;completed&#39;;<br>};<br>...</pre><p>The great thing of the Composition API is that we can now extract all this functionality to a composition function or &#39;custom hook&#39; :</p><pre># /hooks/useFilter.js</pre><pre>import { ref } from &#39;@vue/composition-api&#39;;</pre><pre>export default () =&gt; {<br>  const visibility = ref(&#39;all&#39;);<br>  const filterAll = () =&gt; {<br>    visibility.value = &#39;all&#39;;<br>  };<br>  const filterActive = () =&gt; {<br>    visibility.value = &#39;active&#39;;<br>  };<br>  const filterCompleted = () =&gt; {<br>    visibility.value = &#39;completed&#39;;<br>  };</pre><pre>  return {<br>    visibility,<br>    filterAll,<br>    filterActive,<br>    filterCompleted,<br>  };<br>};</pre><p>And import it into the component:</p><pre># App.vue<br>import useFilter from &#39;./hooks/useFilter&#39;;</pre><pre>setup(){<br>  const {<br>    visibility,<br>    filterAll,<br>    filterActive,<br>    filterCompleted,<br>  } = useFilter();</pre><pre>  ...</pre><pre>  return {<br>    visibility,<br>    filterAll,<br>    filterActive,<br>    filterCompleted,<br>  }<br>}</pre><p>You can also do this for the todo functionality. And after you do this, the component will look something like this.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ffrontmen-vue-compositionapi-finishedhooks-612p7%3Ffontsize%3D14%26module%3D%252Fsrc%252FApp.vue%26view%3Deditor&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ffrontmen-vue-compositionapi-finishedhooks-612p7%3Ffontsize%3D14%26module%3D%252Fsrc%252FApp.vue%26view%3Deditor&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F612p7%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/6abcbaf54543b708d3d2623e9619abff/href">https://medium.com/media/6abcbaf54543b708d3d2623e9619abff/href</a></iframe><p>Besides the upside of having the code ordered by functionality, you now also have the ability of code reuse. Look at the useFilter hook for example. It should be useful in other parts of your application which needs filter functionality. This was much harder in the normal Option-based API.</p><p><strong>But doesn&#39;t this do the same as a mixin?</strong><br>Well yes, it makes it easier to reason what is going on in the hook. You only imported the mixin, without showing what methods or data it was exposing. Which made it a lot harder to debug, for instance.<br>The hook returns the functionality and is therefore very clear in the component itself.</p><p><strong>So that&#39;s it?</strong><br>Well almost. For example every lifecycle method in the standard Option-based API now has it&#39;s counter part in the Composition API. For example <em>mounted</em> is now called <em>OnMounted</em> and <em>updated</em> will be <em>OnUpdated</em>. But basically they work the same as the watcher. You just call them in the <em>setup</em> method.</p><p><strong>Conclusion<br></strong>I love this new API. I always found the Vue Option-based API a bit weird. Why have all your functionality in an object. I needed to remember all these options I could use. Now I only have to remember the setup option and I’m ready to go.<br>And because of the Reactivity of Vue it’s really simpler to reason about the whole thing than the React hooks.</p><p>I guess if you have been a Vue developer for a while, then the new API needs a little getting used to. But if you give it a chance, I bet you will see the upsides.</p><p><strong>Thanks for reading. If you liked it, don&#39;t forget to 👏. I would really appreciate it.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91424d221419" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/react-developers-will-love-the-vue-composition-api-91424d221419">React developers will love the Vue Composition API</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fronteers conference 2019]]></title>
            <link>https://medium.com/frontmen/fronteers-conference-2019-dc578a896f1e?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/dc578a896f1e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[fronteers]]></category>
            <category><![CDATA[amsterdam]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Little mousey]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 12:22:34 GMT</pubDate>
            <atom:updated>2019-10-31T20:36:02.530Z</atom:updated>
            <content:encoded><![CDATA[<h3>Fronteers 2019</h3><p>This year it was held again in the eye-catching and beautiful Tuschinski theater in Amsterdam on 3 and 4 October. The talks were given in the main hall which has a great traditional atmosphere (and great seats 😉). What makes Fronteers such a nice conference is that the talks are very diverse. The talks are not just technical but can be very broad, for example about the history of the web or how the process of adding a new feature to the web works. The conference, hosted by Phil Hawksworth, was held in two days. There were 18 talks in total, excluding the lightning talks. In this article, I will give an overview of the talks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yawmy1RFgNMvHTmy9dmdcw.jpeg" /><figcaption>The main hall</figcaption></figure><h3>All constraints are beautiful — Charlie Owen</h3><p>Charlie explained that we all have to work and live with constraints, but that is not a bad thing. By adding boundaries and constraints, people just get more creative. For examples haikus and sonnets, where there is a limitation on word usage.</p><p>Technology places many constraints on the web, but also people have many constraints. We should think about our users and make our applications inclusive for everyone, not exclusive to a certain group of people with a good phone and internet connection. We should care about users with disabilities, even though companies do not want to spend time and money on it. We should make time for accessibility, because 15% of the people have disabilities and the people who are not disabled should realize that it is a temporary privilege.</p><p>According to Charlie, performance engineering is nice, but we should change it to <strong>resilience engineering</strong>, which means making websites that are tough. She recommends the usage of <strong>progressive enhancement</strong> and <strong>server-side rendering</strong> to make websites more robust and resilient, but these measures should only be taken into account when a website is important. Some guidelines to measure the importance could be whether someone’s life depends on the application, it will impact a user legally or his/her job or whether it will cost the user money.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87m9qmeOaeZsaSospNvV8w.jpeg" /></figure><h3>Deep dive into images on the web — Chen Hui Jing</h3><p>Chen Hui Jing gave an inspirational talk about rendering images on the web. She gave a historical overview of how images came to be as we know them today and how image data is stored. She also mentioned the Burn all GIFs day on 5 November 1999, which was a result of the company Unisys that had a patent on GIF files and wanted users to pay for usage. Fortunately, Unisys decided to back off on the license payment and we can use GIFs freely on the web today.</p><p>Chen Hui Jing also showed optimization tips for JPG and PNG images.</p><p><strong>Optimizing JPG images</strong></p><ul><li>Use high-quality source material (JPEG)</li><li>Alignment of the image on the 8x8 pixel grid</li><li>Reduce contrast and saturation</li><li>Saving your JPG as a grayscale image and color it in sepia with CSS</li><li>Slight blurring of an image</li></ul><p>(Of course, you can also use JPG encoders)</p><p><strong>Optimizing PNG images</strong></p><ul><li>Reduce the number of colors</li><li>Choose the right pixel format</li><li>Use indexed images</li><li>Optimize fully transparent pixels</li></ul><p>She continued her talk about how images combined with other pixel data are rendered on the screen by the browser. The rendering pipeline paints the parts of the display in layers and combines the layers into one final image through compositing. Also, a rasterization process has to be performed before graphics can be displayed on the screen. This process is repeated when the UI on the page changes, but since only part of the screen changes the invalidation method is used to figure out what changed and only change the relevant pixels.</p><p>Chen Hui Jing explained that the rendering tasks were originally done by the CPU on the main thread and that could take a while. Because of the major development of the GPU, browser engineers moved the rendering tasks to the GPU. With WebRender, the separation between painting and compositing is removed. And because of the GPU’s parallel processing power, painting and compositing can be done in a single step.</p><p>More information on Chen Hui Jing’s talk can be found <a href="https://www.chenhuijing.com/slides/">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Os_KOaamBmha-_Mk3XtNiA.jpeg" /></figure><h3>Fun &amp; Games with ES Proxies — Christophe Porteneuve</h3><p>Christophe Porteneuve explained to us the world of proxies in JavaScript with demo examples. The general idea behind a proxy is that you redefine the semantics of some core language features without altering the original object, it wraps it. Proxies can be explained by traps and handlers.</p><p><strong>Traps</strong> are functions with a pre-defined name that intercepts a language interaction to replace or customize it. It can delegate to the original behavior with the Reflect API. A <strong>handler</strong> is an object that bundles a series of traps. It is usually single-topic. A <strong>proxy</strong> is an object that wraps another object and intercepts some or all of the possible language interactions on that object. It will pass down the interactions defined in the handler to the object.</p><p>Some of the available traps are:</p><ul><li>Get</li><li>Set</li><li>Has</li><li>defineProperty</li><li>setPrototypeOf</li></ul><p>It is better to use the reflect API for methods to use on traps instead of using the Object methods such as in and delete.</p><p>There are also <strong>revocable proxies</strong>. The revocable construction method makes it possible to revoke access to the underlying object which can be useful in some cases.</p><p>Christophe also mentions the library Immer for making usage of immutable states easier. It goes well with React because it makes usage of the … operator unnecessary, which makes the code more readable.</p><p>Some problems with proxies are that the <strong>this</strong> context is affected, it becomes the proxy context. There are issues with identity-based mechanisms such as WeakMap, and there are also issues with built-in objects with methods that use internal slots.</p><p>The slides with code can be found <a href="https://deliciousinsights.github.io/fronteers-es-proxies/">here</a></p><h3>Paint the web: creating art with CSS — Eva Lettner</h3><p>This was a very fun talk to watch. Eva showed us live how to create art with CSS. It was amazing how she made it look so easy. Eva explained which tools she would use to create a floating bee on the screen. It was great to see how much you can do with just rectangles, border-radius, triangles (change 3 border sides to solid transparent and one to color), box-shadow, gradients, and pseudo-elements (before and after). The takeaway of her talk was that we all should make useless stuff to learn and create something fun.</p><h3>Secrets of native-like PWAs —Jad Joubran</h3><p>His talk was about how we should make PWAs more native like. Jad stated that PWAs are successful when they are built with Web Technologies that satisfy and exceed user expectations.</p><p>The pillars of native-like PWAs are:</p><ul><li>UI</li><li>UX</li><li>Reliability</li><li>Performance</li></ul><p>The steps to make a PWA more native like are as follows:</p><p>0. Design &amp; Build an App Shell</p><ol><li>Build an advanced app shell, with a tab bar and possibility to swipe between pages</li><li>Reduce JavaScript footprint by code splitting</li><li>React with fast interactions, every action needs a reaction/feedback</li><li>Make it work offline with caching but be mindful of storage, and don’t forget to clear cache when a user is logged out</li><li>Increase ‘add to homescreen’ conversion, by delaying the prompt for ‘use the app’ until the user is engaged and wants to make more use of the service</li><li>Build a smooth update process. We can learn from native desktop apps how to notify the user there is an update available</li></ol><p>Joubran concluded the talk by stating that we should put more attention to the details.</p><h3>Who designed this? Where web platform features come from, and how to get involved — Rachel Andrew</h3><p>This talk was about how new specifications on de web are designed and evaluated. Fronteers (a volunteer organization) is a member of the W3C (a community that develops open standards). Rachel has been the Fronteers representative to the W3C and Fronteers can cast a vote for whom should be elected for the W3C Advisory Board. Participants on the Advisory Board use their best judgment to find the best solutions for the Web in general. W3C working groups work on specific web standards and Fronteers members can apply if they want to join, because Fronteers is a member of W3C. It does take a while before changes and new features are made, patience is required. Rachel wants to raise awareness that all developers can contribute by reading and commenting on specification issues on <a href="https://github.com/w3c">https://github.com/w3c</a></p><p>Rachel also asked the audience to raise browser bugs, use firefox nightly to help test the web, and to help web platform tests in improving the web.</p><h3>100% CSS Mario Kart — Stephen Cook</h3><p>This talk was just amazing. Stephan wanted to make the statement that even though the code was not optimal for production, he wanted to show what CSS can do and that we should not blindly use JavaScript when CSS is also a powerful tool. In his case, he used box shadows to create a Mario character in Mario Kart. Stephan used animations (negative animation-delay) with keyframes to make Mario move and make the scenery move. In order to listen to the left and right keys on the keyboard to make Mario move, Stephan used the valid and invalid pseudo-classes together with the pattern attribute for input. For changing characters he used radio buttons and the checked attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Q9-ljiiDXy4TUD08JxMcQ.jpeg" /></figure><h3>Custom Web Shadow Elements, or Whatever… — Paul Lewis</h3><p>There are a lot of discussions on frameworks and Web Components. Paul talks about the two camps of web <strong>standards</strong> and the <strong>proprietary</strong> (frameworks and libraries). They bring their own perks and drawbacks to the web. For example, proprietary technology moves faster but often more code is needed and there are breaking changes while businesses are dependent on the library. In the case of web standards, one size does not fit everyone. But the changes are rare so the platform is very reliable and web standards are portable. Paul describes the two worlds as ends in a continuum. Sometimes we are leaning more to the proprietary end and sometimes we are more going towards the web standards. It is a trade-off, because we all have to make choices if we care more about the performance, portability, or features.</p><p>Paul continues about the discussions between the two camps about Web Components, but wants to say that we should always have a conversation about standards and the proprietary and protect this process instead of trying to answer the question who is right. One cannot live without the other. Web standards are known and need the proprietary to investigate the unknown, to try out new things. When the proprietary changes are good enough they could become web standards.</p><h3>How We Built the World Wide Web in Five Days — Jeremy Keith &amp; Remy Sharp</h3><p>In this talk, we were taken back to the history of the internet, from the Big Bang to CERN in WOII up to the point where ARPANET was created and grew into the internet. Then, Tim Berners Lee at CERN built the software he named The World Wide Web in 6 weeks with the NS Builder. Jeremy and Keith were invited to CERN as hackers to recreate the first web browser from 30 years ago. They rebuilt the software on a NeXT machine how it was supposed to work: just content, hyperlinks and editable text.</p><p>Jeremy and Remy emphasized that the web browser was published for free by CERN, which was very generous. Their takeaway was that <em>the web lost its simplicity and resilience if we compare it to how it used to be.</em> Web development is sometimes becoming too complex, where it used to be just to linking pages to each other. ‘If you have something wonderful, defend it otherwise you will lose it’. The world wide web is built by everyone and should be open for everyone to create. We should defend the openness of the web.</p><blockquote><em>“The web lost its simplicity and resilience if we compare it to how it used to be”</em></blockquote><h3>Component API Design and the Developer Experience — Diana Mounter</h3><p>Diana works at Github and explains that it is a difficult task to offer a great developer experience for the 31 million developers they serve. She works on the Primer CSS which takes care of the styling of Github, but it is hard to make changes, there is a slow feedback loop, and there is a risk of unintended side-effects. Diana realizes that there comes a lot of responsibility for Github in serving websites. There is always a <strong>tension</strong> between offering <strong>flexibility</strong> for the developers and <strong>constraints</strong> from the business. Github used to have global CSS styles but that became a mess where it wasn’t clear what changes would have an impact on. That is why Github tried to make separate components for UI elements. These components help them repeat and for encapsulation.</p><h3>Components on the Web — Jack Franklin</h3><p>Jack talked about what approaches we could use to building components on the web. Jack also knows that not everyone has the chance to start over with new technologies in the code stack they use every day. He would suggest to just start adding new reusable components to the code when you have the chance. Once you start it becomes easier to add more components. Jack explained that a component is at the core a box of functionality which provides HTML, CSS, and JavaScript. It should be a black box where you can work in isolation. In the former days, frameworks would divide the application up into the model (data), view (HTML), and controller (business logic). But bugtracing would become hard, you don’t know where to start. When using components, you can fix the bugs in isolation. Jack emphasizes on creating black box components: when using the component you don’t have to worry about its implementation.</p><p>Jack discussed that when you are building components you will have the trade-off between <strong>maintainability</strong> and <strong>configurability</strong>. His takeaway was to <em>always prefer explicit configuration over implicit options</em>. Then, Jack talked about when to consider splitting up components because they are becoming too big. You can consider the following criteria:</p><ul><li>How many lines of code is it?</li><li>How many different HTML elements does it render?</li><li>How hard is the component to understand?</li><li>Is the component hard to name? Would there be an ‘and’ in the name?</li></ul><p>Unfortunately, it is not always possible to put everything in black box components. They do not know about each other or the system, but sometimes it’s required they do (for state and data fetching). Therefore, some components cannot be black boxes.</p><p>Jack states that it is better to incrementally add new features (in this case components) to the code to immediately add value to the project instead of rebuilding the application with new technology from the ground up. Jack’s final takeaway was <em>to try out new technologies even though it might end up being a mistake.</em> With a component based system you can easily revert a mistake, or just not ship it.</p><h3>Learning From Machines — Ashi Krishnan</h3><p>This talk about AI was mind-blowing with amazing visuals. Ashi started the talk off by saying <em>we are all computations and that our world has been created on a powerful ancient computer</em>. Her talk shows the similarities between how AI computers operate and the human brain works. You just have to watch the talk <a href="https://vimeo.com/364387772">yourself</a>.</p><blockquote><em>“We are all computations. Our world has been created on an ancient computer, powerful beyond imagining”</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P8PcS5IY96xzjAHH8vGcfg.jpeg" /></figure><h3>High Performance Web — Peter Müller</h3><p>Peter Müller shows us how users experience a website with non-performing web fonts. Web fonts take more time to be loaded instead of system fonts. 70% of the websites use web fonts mostly for brand recognition, but companies should know how to use web fonts while still serving a good user experience. Peter divides user experience into the first paint on the screen and the first meaningful paint on the screen. Peter shows us 3 fast font loading techniques:</p><ol><li>Use the font-display in CSS or as display attribute</li><li>Self-hosting of fonts</li><li>Preload fonts</li><li>Subsetting (choosing which parts of the font you want to use and create a new file from it)</li></ol><p>The last technique is tricky, you need to know which characters are used on the web page. Aggressive subsetting is seen as an anti-pattern. To make subsetting work you need external dependencies, and a complex workflow (every time content on a page changes the workflow has to rerun). Then, still there are fallback typography flaws (characters have different fonts). Luckily, Peter created the tool Subfont which can automate the web font loading optimization for you. It’s available on <a href="https://www.npmjs.com/package/subfont">NPM</a>.</p><h3>It Was the Best of Times, It Was the Worst of Times — Raymond Camden</h3><p>Raymond gave a talk on his journey through the web and web development. It was a more humorous talk where he would talk about which things were better in the past and the things which are definitely better today. Raymond even quit as a web developer for a while because web development became too hard for some browsers. The takeaway at the end was that <em>web browsers are better than before but also more complex than before</em>. Browsers should document better what the changes are for the developers and what is available and what is not. It is good that browsers are being improved but it is hard to keep track of all the changes nowadays.</p><h3>The Universe in a Single Arrow — Anjana Vakil</h3><p>Anjana gave an enthusiastic and inspiring talk about functional programming in JavaScript with the Lambda calculus. The lambda functions are <strong>anonymous</strong> (not saved in a variable), <strong>pure</strong> (no side effects), with <strong>single input</strong> where the whole body is its return value. After that, Anjana did her magic with arrow functions in order to create church numerals. She showed us that you can do simple math with arrow functions, but also Boolean logic, and control flows. It was amazing to see but also mind boggling 🤯</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nXpVolbiQWu8J-ocFqNYyA.jpeg" /></figure><h3>The Web Design Cheat Code: Using SVG to Bridge CSS’ Gaps — Lea Verou</h3><p>The queen of CSS is back. Leas talks are always fast paced small tutorials where a lot of live code is shown. She showed how SVGs used in CSS can be very powerful. By doing so, you can change the styling of block quotes, meters, and list bullets. After that, Lea showed how to create sketchy borders with stroke-dasharray combined with animation, calcin geometry attributes, and SVG filters such as feTurbulance and feDisplacementmap. In order to create squigglevision as border lines, we can use animate in SVG with SMIL on the attribute name seed, because you cannot use CSS animations on SVG filter parameters. The downside is that this can be CPU intensive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/934/1*rLgKjBiMHKM6CU5msPTyAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVTuLHW7hb6kvJiKzpYQZQ.jpeg" /></figure><h3>The Future of Web Typography With Variable Fonts — Mandy Michael</h3><p>Mandy mesmerized us with variable fonts. A variable font is a font file that acts like multiple fonts. A variable font can contain one or more axes and you can animate them. Mandy showed us some nice demos with the variable font decovar. Using variable fonts is similar to using normal fonts in CSS but you can specify a range of font-weightinstead of a single value. Other properties you can use are font-stretch, font-style, and font-optical-sizing. With the font-variation-settings, you can define weight, width, italic, slant, and optical size in one line. Variable fonts are well supported by browsers. You can define a fallback by using @supports in CSS. By using variable fonts, you are reducing the number of font requests and when using WOFF2 files, the file size does not always have to be larger compared to single weight fonts. Mandy encourages us to try out variable fonts, it’s easy to use and much is possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LcDQCjhfZLAN_LyBk_-w7w.jpeg" /></figure><h3>The Mobile Web: MIA — Alex Russell</h3><p>The last talk was a bit of a depressing one. Alex tells us that the mobile web is not doing well, because no one is using the web on mobile devices. Using services such as Google maps and Gmail were amazing and mind blowing when they were introduced on desktop. That brought a lot of users from the traditional applications on the computer to the browser. Now, everyone has a mobile phone. However, according to research done by Google, the web is not essential to the future of computing on mobile devices. Alex states that for the web community this would mean that the web will be extinct on mobile devices. We should work together to make the web great again. Alex states that the ecosystem we are working on today is not healthy, we are leaning too much on the legacy of the web for desktop. The mobile web does not compete with mobile apps, and Apple is actually making sure that the web stays down, while most of the people who have other mobile devices have bad hardware. With bad CPUs, websites cannot perform well on phones, and unfortunately, networks cannot make up for it. We have to give up on responsive design, solely working on that is not the solution. A good experience is about performance, otherwise the web is not accessible. We have to start mobile device first, after that scale to desktop. It’s not too late, we have to use the tools nowadays available to us to set performance budgets, such as <a href="https://www.webpagetest.org/easy">webpagetest</a> and Lightwallet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3KLR2EX8hIj2PQCJ3jAhA.jpeg" /></figure><h3>Final thoughts</h3><p>Overall, it was a great conference with a lineup of very cool talks. Recurring themes were constraints and trade-offs, be it in web development or in daily life. If you want to watch the talks yourself, they are recorded separately and published on <a href="https://vimeo.com/fronteers">Vimeo</a>. More information on the speakers can be found on the <a href="https://fronteers.nl/congres/2019/speakers">Fronteers website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8DlJgE0ijqVb8-xl6FGzw.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc578a896f1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/fronteers-conference-2019-dc578a896f1e">Fronteers conference 2019</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AmsterdamJS Nation 2019]]></title>
            <link>https://medium.com/frontmen/amsterdamjs-nation-2019-a84bbc2b8f9a?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/a84bbc2b8f9a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[conference]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[amsterdam]]></category>
            <dc:creator><![CDATA[Little mousey]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 11:22:30 GMT</pubDate>
            <atom:updated>2019-06-14T20:33:56.579Z</atom:updated>
            <content:encoded><![CDATA[<h3>AmsterdamJS Nation conference</h3><p>On Friday the 7th of June I visited the AmsterdamJS Nation conference for the first time. The main event was held in a Church in Amsterdam, the Zuiderkerk next to the metro station Nieuwmarkt. In another venue, a synagogue called Uilenburgersjoel, the NodeJS talks were given. In this article, you can find my summary and takeaways from the talks I listened to at the conference in the main hall. It was a beautiful sunny day (they even handed out ice cream!) and the first keynote talk was given by Kyle Simpson.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nqnZOZsdm24GD6TET4_1Kg.jpeg" /></figure><p>That talk gave an inspirational start of the day. Kyle talked about the importance of the open web and how he started out as a little boy deconstructing a website by using the ‘view page source’ button. He made the comparison of the journey of creating the web with launching rockets into space. We still have a long way to go and it is our responsibility to make sure the web stays open in the future. We need to have a vision, even though we have to make the journey in small incremental steps. JavaScript should also be for the people, not created by machines. Code should be readable and understandable for people, that makes the web open. He states that the open, incremental, collaborative technologies such as JavaScript, HTML, and CSS will always win from closed-off technologies like apps and Flash.</p><p>Kyle stated that we should always bet on JavaScript, it has continuously been performing above expectations, even old code from 25 years back can still be used which makes it very robust for developers.</p><p>In ES4 they tried to implement a lot of changes to the language, which failed. With ES6/ES2015 a lot of changes have been made to the language, which made it hard for a lot of developers to keep up. Incremental changes to the language have been landed better for the public.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TBYRyxjBC4JAQ3UkiSbyA.jpeg" /><figcaption>Kyle Simpson</figcaption></figure><p>Finally, he showed us some new JavaScript features which will land soon:</p><ul><li>Private fields and private methods</li><li>Optional chaining</li><li>BigInt</li></ul><h4>Securing the DOM from the Bottom Up</h4><p>The next talk was about the vulnerability of the DOM by a web security engineer at Google. A lot of websites are vulnerable to XSS (cross-site scripting) attacks. This can be prevented by using trusted types in the DOM. This is an API which you can define in the HTML header:</p><pre><em>Content-Security-Policy: trusted-types template</em></pre><p>You can define your policy with JavaScript. The main idea behind it is that you should use objects instead of strings.</p><p>More information about this project you can find <a href="https://developers.google.com/web/updates/2019/02/trusted-types">here</a></p><h4>Testing Tools and Their Friends</h4><p>Another talk was about testing tools by the head engineer of Cypress. He states that from the user’s perspective, E2E tests are the most important ones to run. We can use Cypress for this, which provides methods for clear and understandable code. With Cypress, you can test the user flows. If you use the Istanbul code coverage tool combined with Cypress, you will know how much of the code you covered in the tests. And when you use Cypress combined with Percy, styling changes will also be covered during tests. It would be preferred to use Cypress in your CI/CD pipeline, when you do a branch merge for example.</p><h4>Webpack 5 — Why Breaking Changes? What is next?</h4><p>Webpack creator Tobias Koppers’s talk was about breaking changes for Webpack 5. The most important change is that Webpack won’t provide automatic polyfills for Node.js core modules anymore. This way, Webpack decreases the bundle size. As a developer, you should choose for yourself which polyfills are needed. Webpack 5 will include improved persistent and long term caching. There is a new algorithm for useful filenames. For example, instead of 1.bundle.js the name src_bundle_lazy_load.js will be used. Also important, the minimum node version will be 8. For more information on the changes in Webpack 5, you can find the slides <a href="https://github.com/sokra/slides">here</a></p><h4>Functional lenses for contemporary frameworks</h4><p>The next talk was by Andre Staltz about functional lenses for contemporary frameworks. He is a guru on functional programming and stated that lenses can be useful for state management. He compared lenses to getters and setters but composable and they won’t mutate the original variable. First, he explained what functors and profunctors are. A <strong>functor</strong> is a conversion from A to B, a mapper. A <strong>profunctor</strong> is a conversion of A to B and back. A lens is a conversion from one data structure (or state object) to another and back. We can make use of lenses for state management because for components it will seem like they work on local state, but they work with a global state in reality. This state is serializable, immutable and hierarchical. There are fewer concepts to learn: the reducers, actions, store, and dispatch are not needed anymore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Sirjz6ujt_-zqNpsCrzwQ.jpeg" /><figcaption>André Staltz</figcaption></figure><h4>Open Source: Another problem of complexity</h4><p>Full-time contributor/maintainer Henry Zhu at Babel explained the hardships of being an open source developer. It is hard to get by with open source, even with projects such as Patreon. When you are living on donations, people are harsh when a bug is not yet fixed and they paid money for it. He finds his relationships with his sponsors a bit awkward because he feels like he always has to earn his work, because other people pay him. You feel like other people are watching you or micromanaging you so you have to keep on working. You also feel weird about spending money. There is always too much work to do, so it would be great if sponsor companies can also work on user stories for open source projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5odNl_JDMTVc2VVAqRWseg.jpeg" /><figcaption>Henry Zhu</figcaption></figure><h4>Lightning talks</h4><p>From the lightning talks, the one about the search for app-iness in progressive web apps was very inspiring. Jamie Maria Schouren from DEITY showed us websites are still too slow nowadays but native apps have disadvantages. The <strong>AMP</strong> project (Accelerated Mobile Pages) was launched which provided fast landing pages but the <strong>PWA</strong> (Progressive Web Apps) made the difference. They are fast and reliable and can also make use of native features. By 2020, 50% of online purchasing would be considered using web apps as predicted by Gartner.</p><p>Another important talk was about accessibility by Elsevier. <strong>The most important takeaway was to avoid using the DIV tag when there are appropriate semantic HTML tags to use.</strong></p><p>The speaker advised the listener to use the keyboard to navigate through a website and a screen reader. Using accessibility tools such as WAVE and Tota11y can help making a website more accessible. Removing or disabling the CSS can tell you a lot about the structure of a website which is seen by the screen readers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZiI3UsdNb67SSYPOB_mgpQ.jpeg" /><figcaption>Nicholas Pringle</figcaption></figure><h4>Building Fast Angular Applications from End-to-End</h4><p>Minko Gechev from the Core Angular team showed us the performance improvements of Angular 8. The network performance has improved by using differential loading which is very interesting. Older browsers need polyfills for newer JavaScript features but newer browsers don’t so depending on the user agent certain packages will or won’t be downloaded. He also explained lazy loading with code splitting on component level with ngx-loadable and hero-loader. On route level, you can use module loading for when routing a page. Problems arise when there is a slow internet connection. Then, prefetching can be used. Minko explained a prefetching strategy with the use of Google analytics, using a model to predict which page will be loaded, mapping the page to a router and loading the JavaScript routes into chunks. When a user is browsing, the chunks which are likely needed for the user will be prefetched. He mentioned the library Guess js which helps with the prediction of the user behavior.</p><p>When it comes to performance budget, you can specify ‘budgets’ in the Angular json now to set warnings and errors when the app becomes too big.</p><h4>Immer, Immutability and the Wonderful World of Proxies</h4><p>Michel Weststrate showed his open source library Immer. This library provides a function to use as reducer for creating immutable new state. Earlier that day he won the open source award with the Immer library. He explained that we should not use proxies for daily work, only when you want to create a framework. Proxies can be powerful but undetectable (there is no proxy type) and dangerous, they are a low-level framework tool and can be very confusing to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yToMLSxqYA-srMOyc0F2Q.jpeg" /><figcaption>NodeJS hall</figcaption></figure><h4>Turbo charging 2D on the web</h4><p>Mat Groves from Goodboy Digital showed us a comparison of 2D rendering techniques. We can use plain HTML/CSS, canvas, or WebGL. WebGL has the best performance from this list, it is super fast. However, the usage of WebGL is complicated, it has a steep learning curve. Moreover, it can drain a device’s battery and unfortunately there is a maximum usage of 4 WebGL elements per page. For usage of 2D WebGL rendering engines we can use the PixiJS and CreateJS libraries. Mat also mentioned the future for 2D rendering, WebGL2 was the next step in performance improvement but did not bring anything new. WebGPU will be next gen, will be a new API faster than WebGL where we will have more power. WebGPU has more control over the GPU. Finally, Mat mentioned that Webassembly will soon be the place to make rendering engines. It performs very fast and opens the door for other tools like unity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ei9RKR2NbjDFM9TZ29B5g.jpeg" /></figure><h4>Automated Performance Testing With WebDriver</h4><p>Christian Bromann talked about automating performance testing with WebDriver. Christian discusses three metric types, milestone based, score based and resource based metrics.</p><p>He shows a few metrics to measure the performance (milestone based). One way is to calculate the time to first byte. Another rendering metric is the loading of a webpage in time: the first render to the screen, the first contentful paint, the first meaningful paint and the time to interactive. Speedindex is another metric to calculate how quickly the content of the page is rendered.</p><p>Christian shows that there is also a way to perform user-centric performance metrics, as used by Google. The steps they check are the following:</p><ul><li>Is it happening?</li><li>Is it useful?</li><li>Is it usable?</li><li>Is it delightful?</li></ul><p>At Christian’s company, they use Webdriver combined with Speedo, that executes regression performance tests.</p><p>His takeaways were that functional testing and performance testing should be done separately. Keep the performance tests simple and give them a separate job name.</p><p>There are generic performance testing tools such as Lighthouse, but you have to keep in mind what you want to test, maybe you need more specific metrics for your app. But when you want to use generalized metrics, score based metrics work best.</p><h4>Using WebGL and PWA to build an adaptive game for touch, mouse and VR devices</h4><p>David Rousset from Microsoft gave the last talk of the day about building 3D games for VR devices. Mostly David showed demos of his games. He used the Babylon js library for the creation of his games in WebGL (1 and 2). It is an open source 3D engine. After that, he used WebVR in Babylon JS. Then he concluded the talk by adding PWA to the game for offline experience with the help of the PWAbuilder.</p><p>If this article made you curious, you can view the talks on Youtube, the whole day at the venues has been recorded:</p><ul><li><a href="https://youtu.be/Fj4Vm9m95Io">Talks given in the main hall</a></li><li><a href="https://youtu.be/-rs-5ZL-f9w">Talks given in the Node JS hall</a></li></ul><p>I haven’t written about the talks at the Node.JS hall but I’ve heard they had some awesome talks with flying drones…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urVR8MENsodIuyTkutV9og.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a84bbc2b8f9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/amsterdamjs-nation-2019-a84bbc2b8f9a">AmsterdamJS Nation 2019</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing React components, both smart and dumb, using Jest and Enzyme]]></title>
            <link>https://medium.com/frontmen/testing-react-components-both-smart-and-dumb-using-jest-and-enzyme-1d80abce8940?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/1d80abce8940</guid>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[snapshot-testing]]></category>
            <dc:creator><![CDATA[Justus Romijn]]></dc:creator>
            <pubDate>Wed, 12 Jun 2019 10:02:23 GMT</pubDate>
            <atom:updated>2019-06-12T10:02:23.459Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wrBiLX_WgMkvf2-XqeM-JA.png" /><figcaption>Command Line Interface output of (snapshot) unit tests with Jest of React components. Viewed with VS Code.</figcaption></figure><p>In the past couple of years I’ve been working with mainly React. I embrace unit tests for all my components, but based on the type of component and how complex the rendering is, there are different ways of asserting output. So I’ve split up my unit test approach for these well-known categories:</p><ul><li>Presentational Components: Also known as “dumb” components. They are not concerned with business logic and rarely have their own state.</li><li>Container Components: Also known as “smart” components. They contain business logic, might maintain state of their own, and orchestrate presentation components.</li></ul><p>Let’s start with the building blocks of most React applications, the so-called Presentational Components:</p><blockquote>Use enzyme <strong>mount</strong> and validate output with jest snapshots.<br>Perform contract assertions for your props.</blockquote><p>The dumb components main concern is the render output, so mounting and then making snapshots of the outputted html makes a lot of sense to me. The snapshot alone is not enough. We also want to make sure that we handle the input from the outside world correctly. In the example below, we check if the defaults work as expected. If properties and callbacks are provided, we test if they have the expected effects on the output or, in the case of callbacks, are called properly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd07b02b0c17d811d76601029b3c0021/href">https://medium.com/media/dd07b02b0c17d811d76601029b3c0021/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c05b84b8f252fb4c2c1f3fc745de4245/href">https://medium.com/media/c05b84b8f252fb4c2c1f3fc745de4245/href</a></iframe><p>Making a snapshot for the scenario where the defaults of the component are used, as well as a snapshot for when props are provided really make it easy to cover all the branches of the code in a nice way.</p><p>Lets take a look at container components:</p><blockquote>Use enzyme shallow rendering for your container components if you can.<br>Access the child components props directly to test the wiring of your parent-child relations.</blockquote><p>Smart components are a whole different game. If you start snapshot testing your container components, and someone makes an innocent change to the output of a small presentational component (without changing the props interface), all containers using that component will have regression failures because the snapshots are invalidated. That makes your tests brittle and might lure you in a false sense of security, because it is easy to just ignore invalid snapshots by updating them with the new version (jest -u).</p><p>Instead of using snapshots, you can just access the properties of the child components directly and manipulate those, so the unit tests are only scoped to the actual logic of the container component itself. In the example below I use shallow testing, but if you have more complex nesting (often the case when using providers, graphQL queries, etc.) you can just exchange shallow for mount and it still works. Just as long as you keep away from snapshots or diving into the actual output of your presentational components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a1faeb6dc6a78d385383ee79447d717/href">https://medium.com/media/5a1faeb6dc6a78d385383ee79447d717/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4781de26d18bf836c44e58edf508a215/href">https://medium.com/media/4781de26d18bf836c44e58edf508a215/href</a></iframe><p>I hope this gives an overview of how to keep your unit tests scoped, and your mind sane. I aim for that 100% coverage with confidence.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d80abce8940" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/testing-react-components-both-smart-and-dumb-using-jest-and-enzyme-1d80abce8940">Testing React components, both smart and dumb, using Jest and Enzyme</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Pokédex with Vue CLI (part 4)]]></title>
            <link>https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-part-4-ed58bd448e1e?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed58bd448e1e</guid>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[localstorage]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Little mousey]]></dc:creator>
            <pubDate>Thu, 16 May 2019 10:08:11 GMT</pubDate>
            <atom:updated>2019-05-16T10:09:45.109Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the last part of the tutorial series to build a Pokédex in Vue with the Vue CLI. So far we built a working Pokédex existing of two pages: an overview page of all 151 pokémon, and the page with all the selected pokémon and their Pokédex entry. To achieve this, we implemented pages, routing, Vuex, and components. In this last part, we will discuss how to get the data to be persisted.</p><p>This is the overview of the whole tutorial:</p><ol><li><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-fc66920015b3">Initial setup</a></li><li><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-2-c3347ed4c7d4">Routing and State management</a></li><li><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-3-b140dd31fceb">Components</a></li><li><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-part-4-ed58bd448e1e">Optional: Persisted state &amp; Lessons learned</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6TrhS5mztta2P7RfpSfUA.png" /></figure><h3>But what if I reload the page?</h3><p>When reloading the page your application will be reset again. This means that your list of favorite pokémon will be gone and the user has to start over again choosing his or her favorite pokémon. An explanation for this is that the Vuex store is initially empty at the start of the application because, in the end, the store is plain javascript. We can imagine that this is not the desired behavior.</p><p>When you reload the page the Vuex state should be filled again with data of the pokémon list and favorite pokémon list at startup. But where to store this data? A solution could be the <strong>local storage</strong> of your browser. Even after closing the browser the data in the local storage will still be available. The data is linked to your URL however. So if your application is hosted on a different port or URL than before you won’t have the data available anymore.</p><p>I used the npm package <a href="https://github.com/robinvdvleuten/vuex-persistedstate"><strong>vuex-persistedstate</strong></a><strong> </strong>to solve this problem. You can also manipulate the local storage yourself by setting and reading the local storage with localStorage.setItem(keyName, keyValue); and const data = localStorage.getItem(keyName);</p><p>The reason why I used the npm package instead of setting it myself is that the <strong>vuex-persistedstate </strong>npm package maps the local storage to the items in the state object seamlessly. I don’t need any code for getting or setting the local storage items which made my mutations cleaner and more readable.</p><p>Example of a mutation before and after implementation of the <strong>vuex-persistedstate </strong>npm package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4509bed05a8abf429d895c4eeee5874/href">https://medium.com/media/c4509bed05a8abf429d895c4eeee5874/href</a></iframe><h3>Lessons learned</h3><p>If you know what you want to present on the page and your hands are scratching just to build something then you just start programming. That is what happened to me and after the first day, I felt good about what I achieved. However, on the second day, I had to do refactoring for the whole day because I hadn’t thought about the generic setup of the components. For me, it would be a lesson to think things through before I start programming (even though it can also be a good challenge to do the refactoring, it just takes a lot of time).</p><p>Other things people pointed out to me in a code review (which is always important and sometimes painful but helpful to become a better programmer) were the following:</p><ul><li>Think about where data is needed. It has no use to retrieve data already from the API when you are not already logged in.</li><li>Let pages be ‘smart’ and their components ‘dumb’. Components should not have access to the Vuex store, but retrieve data through props from the pages. This way the logic is put in one place, the page and there is less computational overhead for the developer.</li><li>Make everything modular where possible. Use imports and exports to keep the main.js file well-organized.</li><li>Naming is important. This part is tricky because it is also a bit personal. Previously I named the pages ‘selectPokemon’ and ‘overviewFavoritePokemon’ but after logging in you would be redirected to the select pokemon page so it might as well be the home page. The naming is important for other developers to understand your code better and for you when you will view the code again after a long time.</li><li>Think about usability too, let others test your application. At multiple times I thought my application was finished. Then someone told me that the login page should submit the input on pressing the enter key.</li><li>An application is actually never finished, there is always a way to improve your application</li></ul><p>If you guys like the application or the tutorial series let me know :) And suggestions for improvement are also welcome. By writing this article I’m learning a lot about Front-end too so if you see any errors or you want any additions to the text, please let me know.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed58bd448e1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-part-4-ed58bd448e1e">Build a Pokédex with Vue CLI (part 4)</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Pokedex with Vue CLI (part 3)]]></title>
            <link>https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-3-b140dd31fceb?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/b140dd31fceb</guid>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Little mousey]]></dc:creator>
            <pubDate>Thu, 16 May 2019 08:53:23 GMT</pubDate>
            <atom:updated>2019-05-16T10:10:55.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Pokédex with Vue CLI (part 3)</h3><p>In the previous two parts of this tutorial we discussed the initial Vue CLI setup, how to set up routing and state management and we created two pages of the application. In this part, we will create the components.</p><p>This is the overview of the tutorial:</p><ol><li><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-fc66920015b3">Initial setup</a></li><li><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-2-c3347ed4c7d4">Routing and State management</a></li><li><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-3-b140dd31fceb">Components</a></li><li><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-part-4-ed58bd448e1e">Optional: Persisted state &amp; Lessons learned</a></li></ol><p>At the end of this tutorial, we will have a cool pokédex application which shows the first 151 pokémon and you can look up the pokédex entries of your favorite pokémon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*anjO84ayLO61ziiLv-klBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJKvuhyMf_Xj1DA7nHhN5w.png" /></figure><h3>Components</h3><p>We need the following components:</p><ul><li>List which shows the available pokémon</li><li>List of the favorite pokémon</li><li>Card which shows an individual pokémon</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OXjcNx-6tOuPnFe69QSzwg.png" /><figcaption>Card for single pokémon</figcaption></figure><p>Let’s check what we will get from the PokéAPI. When querying for the first 151 pokémon with the following query</p><pre><a href="https://pokeapi.co/api/v2/pokemon?limit=151">https://pokeapi.co/api/v2/pokemon?limit=151</a></pre><p>We will receive a long list of pokémon names with their URL for more information about the pokémon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*R4N1nUgorsS5h62FkpfQOQ.png" /></figure><p>In your components folder, remove the HelloWorld.vue and create the following files PokemonList.vue, SummaryFavorites.vue and PokemonCard.vue.</p><p>I can imagine these code snippets can look a bit overwhelming. Between the template tags, there is HTML but with strange looking attributes such as v-if and v-for. These are called directives in Vue. A directive is a special token in the markup that tells Vue to do something to a DOM element.</p><p>The v-if makes parts of the template render conditionally (that is why there is also a v-else). The v-for makes it possible to loop over elements to render them so there is no need for writing out everything in HTML by hand.</p><p>The @click triggers a function after a click event is fired on that specific element. You might wonder why some attributes have a : in front of them. That is a shortcut for v-bind which allows you to use javascript expressions for passing data to the attribute.</p><p>And the most important thing here is, of course, the text interpolation with brackets{{ }}</p><p>You can use the brackets in every HTML element where you can define the text. Everything between the brackets will be read as a javascript expression. This way you can render the data from the Vue instance inside the template.</p><p>In the script template, the data contains the properties belonging to the Vue instance. The props are properties the Vue instance receives from other components that are calling it. Here we can define what kind of type we are expecting as property and whether it is required from the component which calls us.</p><p>The methods contains only functions known and available within that Vue instance and any function registered as a computed property is a special function that can be used as a variable. The value of the property will be automatically updated when its dependencies change.</p><p>As mentioned before, there are Vue lifecycle hooks such as created for executing methods at the desired time during the ‘lifetime’ of a Vue instance. For example, other lifecycle hooks are beforeUpdate and beforeDestroy. This makes it possible to call a method whenever a Vue instance is being updated (can come in handy when debugging).</p><h3>Update the pages</h3><p>Now we can update the pages by importing the components and pass data to them.</p><p>Update home.vue and favorites.vue as follows</p><p>We are importing the components in the pages and register them as components of the page. Then we use the components as named at import as HTML elements in the template. This is the place in the DOM where they will be rendered (in case of <strong>home.vue</strong> as child of div with class <em>select-pokemon-page</em>). We give the components the promised prop data as we defined in the components and we will map the emitted events to the methods known by the page. As mentioned before, by using mapState the page knows specific data from the Vuex state object. By using mapActions we can trigger specific actions from the Vuex store. All the mapped actions will be available as methods on this. That is why we can use the methods directly in the template.</p><p>Now your application should look like the screenshots. Open your application in the browser and choose some pokémon. Your application should look like the following after choosing 10 pokémon.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bb3VZohJWC2aLnrevVLOPQ.png" /></figure><p>If you want to you can add a login page like in my <a href="https://github.com/littlemousey/pokedex-vue">repository</a>, but it is not necessary for the pokédex. In my repository, I had to implement a password validation as part of an assignment 😉</p><p>In the last part of the tutorial, I will discuss persisted state for the application (that your data will still be available after reloading the page) and the lessons learned from creating this project. 💡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b140dd31fceb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-3-b140dd31fceb">Build a Pokedex with Vue CLI (part 3)</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Pokedex with Vue CLI (part 2)]]></title>
            <link>https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-2-c3347ed4c7d4?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/c3347ed4c7d4</guid>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[vuex]]></category>
            <dc:creator><![CDATA[Little mousey]]></dc:creator>
            <pubDate>Thu, 16 May 2019 08:10:49 GMT</pubDate>
            <atom:updated>2019-05-16T10:48:41.982Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build a Pokédex with Vue CLI (part 2)</h3><p>To give a small recap, in this tutorial I want to show you how to create a cool Pokédex application with Vue. In the <a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-fc66920015b3">previous part of this tutorial</a>, I wrote about the initial Vue CLI setup for the Pokédex application.</p><p>In this part, we will create pages, fix the routing and set up the state management for the application. I would suggest copying the images of the assets folder from the <a href="https://github.com/littlemousey/pokedex-vue">repository</a> to the assets folder in your own project to recreate the same view.</p><p>The <strong>src </strong>folder is where all the Vue magic happens. Let’s create the pages now. 👷</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gdwMrDBrog4vGm8q" /><figcaption>Photo by <a href="https://unsplash.com/@filmape?utm_source=medium&amp;utm_medium=referral">Jay</a> on <a href="https://unsplash.com?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Pages &amp; Routing</h3><p>There are two pages we want to create:</p><ul><li>A page where a pokémon can be selected from the list</li><li>A page where you can find details on your favorite pokémon</li></ul><p>At first, we want to make sure that the routing works fine. In <strong>App.vue</strong>, the root element of the Vue application (it will be rendered before your custom Vue elements) we have to check whether it contains &lt;router-view/&gt; All the pages and their components will be rendered in that tag.</p><p>In fact, replace the content with the following:</p><pre>&lt;template&gt;</pre><pre>&lt;div&gt;</pre><pre>&lt;router-view /&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/template&gt;</pre><p>Next, check if the <strong>main.js</strong> is the same as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc629f8b61e0f0106aba3fc58cc28591/href">https://medium.com/media/dc629f8b61e0f0106aba3fc58cc28591/href</a></iframe><p>Create a folder named pages within src folder and add a file named home.vue. Place the following code in it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ceb44ba6d8d8cb9ef4057e7e80726cc/href">https://medium.com/media/5ceb44ba6d8d8cb9ef4057e7e80726cc/href</a></iframe><p>After that, create a new file called favorites.vue with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4965234f796125a6a05c115be6b4ac9c/href">https://medium.com/media/4965234f796125a6a05c115be6b4ac9c/href</a></iframe><p>As you can see, a Vue file exists of three parts:</p><ul><li>template</li><li>script</li><li>style</li></ul><p>The <strong>template</strong> is similar to HTML but has extra Vue features which will be rendered to HTML in the DOM by Vue. In the <strong>script,</strong> the logic for the specific Vue instance is specified. The <strong>style</strong> is where you can define the CSS or a CSS pre-processor if it is configured in your project.</p><p>It is good to know that you don’t have to use the template, script, and style. You can omit the style if you don’t want any custom styling for the Vue instance. You can even omit the template part, but then nothing will be shown for that instance. The script part can also be omitted if the component does not need any data or logic.</p><p>What we have to do now is set up the routing in router.js. Add the pages as imports and add them to the routes as components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35d5b91318234dba51c075da3dee2468/href">https://medium.com/media/35d5b91318234dba51c075da3dee2468/href</a></iframe><p>In case you haven’t already, go to your terminal and execute the command</p><pre>npm run serve</pre><p>If you go to your localhost:8080 now you can see ‘Home page’ in pixel font style together with a Pokémon logo. You can even go to localhost:8080/favorites and you will view a page which shows the title ‘Your favorite Pokémon’ and a back button which you can use to go back to the home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uD3KIr6LLsNW6-bKC3e5WA.png" /><figcaption>Initial page when opening localhost:8080</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dmf5wLCVZXdY_mA2ihViQw.png" /><figcaption>When you navigate to localhost:8080/favorites</figcaption></figure><p>Great job! 🎉</p><p>You can leave the view folder as is or you can delete it. We won’t use it for our Pokédex.</p><h3>State manager</h3><p>As you could see in home.vue we called the pokéAPI in the created hook with the fetch inside getPokemonData(). created is one of the Vue lifecycle hooks. However, we are not saving the pokémon data anywhere. We should save it in a data store. The one we use will be <strong>Vuex</strong>.</p><p>To keep it simple for this tutorial I will only discuss Vuex briefly.</p><p>For our application, we want that more than one component can have access to the same data. We store this data in a store, one object which is called the state. The state can be filled and changed by mutations. These mutations are the only ones to have direct access to the state. You cannot trigger mutations directly, that needs to be done with actions.The main reasoning behind this is code maintainability in bigger applications. The actions can contain business logic and can be asynchronous, but when they call mutations (they can call multiple mutations) the mutation has only one task which is to change the state.</p><p>Change the content of state.js to the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66968b4ec7a5197484f0cc9914c47f02/href">https://medium.com/media/66968b4ec7a5197484f0cc9914c47f02/href</a></iframe><p>So we have two properties in the State object: statePokemonDataList and stateFavoritePokemonList. These can be directly manipulated by the mutations which are called by the actions.</p><p>Now we have to update our Pages by mapping the properties from the state to make the data accessible within the page. Then we will also map the actions to usable methods on the page so we can trigger an action when the data in the store needs to be changed. In order to do so, we need mapState and mapActions from the vuex library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/140d8e584701652cbd2230d711dc95c4/href">https://medium.com/media/140d8e584701652cbd2230d711dc95c4/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/febf3790fbd80836df26e4e7eb0ccf7d/href">https://medium.com/media/febf3790fbd80836df26e4e7eb0ccf7d/href</a></iframe><p>Now, I would recommend that you use the Vue.js devtools plugin for either Firefox or Chrome so you can see that the pokémon data retrieved from the pokéAPI is stored in the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZS1NclEIu1fjQlhZ7PWuGQ.png" /></figure><p>So far so good! 😁 Now we need to create the components for the pages. This will be explained in <a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-3-b140dd31fceb">part 3 of this tutorial</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3347ed4c7d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-2-c3347ed4c7d4">Build a Pokedex with Vue CLI (part 2)</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Pokédex with Vue CLI]]></title>
            <link>https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-fc66920015b3?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/fc66920015b3</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Little mousey]]></dc:creator>
            <pubDate>Wed, 15 May 2019 14:18:04 GMT</pubDate>
            <atom:updated>2019-05-16T10:49:29.920Z</atom:updated>
            <content:encoded><![CDATA[<p>I wanted to practice with Vue CLI and I wanted to build something fun. I’m a pokémon fan (from the 90’s) and I was thrilled when I found the <a href="https://pokeapi.co/">pokéAPI</a>. Then I also found <a href="https://nostalgic-css.github.io/NES.css/">NES.css</a> and that obviously was a match made in heaven for a cool application. I only included the first 151 pokémon because I’m more a fan of the first generation pokémon 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W6TrhS5mztta2P7RfpSfUA.png" /><figcaption>Pokédex in Vue</figcaption></figure><p>To give a small introduction on myself, I’m a little Front-end developer 🐭 still learning a lot about Front-end. If you are a beginner too, you can hop on and read this article. And if you are an experienced developer or just a curious person who just wants to know more about Vue you can read along too of course 😉</p><p>Vue is one of the popular frameworks nowadays (along with Angular and React). You can create applications faster with a framework compared to just HTML, CSS and plain Javascript. Frameworks already have a lot of functions and plugins they offer and recommended libraries that are compatible with the framework so that you don’t have to figure out everything on your own. So why do we need a Vue CLI? This is a way to start up your Vue project with plugins and libraries installed on beforehand and enable tree shaking (only install the specific modules you need from the third party libraries). This can be a huge performance improvement over the use of CDN (script and link stylesheet tags in HTML). Also, Vue CLI helps you with an initial folder structure of your application and initial setup code for the libraries 🎉</p><p>In this tutorial, we are going to rebuild the Pokédex with Vue CLI. This tutorial is split up in four parts:</p><ol><li><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-fc66920015b3">Initial setup</a></li><li><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-2-c3347ed4c7d4">Routing and State management</a></li><li><a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-3-b140dd31fceb">Components</a></li><li><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-part-4-ed58bd448e1e">Optional: Persisted state &amp; Lessons learned</a></li></ol><p>If you want to see the <a href="https://stoic-kilby-75508b.netlify.com/">Pokédex demo</a> on beforehand, you can view it <a href="https://stoic-kilby-75508b.netlify.com/">here</a></p><p>The password for logging in is <strong>pokemonmaster</strong></p><p>My Github repo is <a href="https://github.com/littlemousey/pokedex-vue">here</a>, you can clone or fork it whenever you like</p><p>It is possible that the code in the repo is different than the code mentioned at the time of writing. Small changes might have been added for code optimizations. Also, please let me know if you see any errors or improvements for this article 😉</p><h3>Let’s get started</h3><p>So to first install Vue CLI globally on your computer. You need a Node.js version higher than 8.9 (you can check it by using the command <strong>node -v</strong>). If you don’t have Node.js and npm installed yet, you should <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">install</a> them if you want to build along.</p><p>Of course, you can also use <strong>yarn</strong> to build a new pokédex from scratch but I used <strong>npm</strong> for my project.</p><p>Let’s open the terminal. The command to install Vue CLI is as follows</p><pre>npm install -g @vue/cli</pre><p>To check whether you have the right version (higher than 3)</p><pre>vue --version</pre><p>So now let’s create a new project. Open a folder where you would like to create the project and open the terminal there.</p><pre>vue create pokedex</pre><p>You will be prompted to pick a preset. In our case choose the ‘Manually select features’. Pick the following options by pressing space (submit by pressing enter):</p><ul><li>Babel</li><li>Router (history mode ‘yes’)</li><li>Vuex</li><li>Optional: Linter / Formatter (linter with prettier &amp; lint on save)</li></ul><p>It is okay if you by accident omit one library/plugin. You can just add it yourself later by using the npm install command on the command line (you can find the specific command for each library on npm). So why do we need Babel, Router, and Vuex?</p><p><strong>Babel</strong> is a code transpiler that will turn new javascript code into old javascript code. New browsers such as Chrome and Firefox will be able to understand new javascript code (also known as ES2015 or ES6) but older browsers like Internet Explorer cannot understand new javascript code. This way, the application can be run on different browsers.</p><p>We use <strong>Vue Router</strong> to navigate between pages. In the old days, you would have an HTML file for every page and navigate between the pages. With vue, you can build a Single Page Application where the rendering happens on one page. Navigating between the pages is simulated with javascript. We use the history mode to override the default behavior, which is that a # is added to the URL for preventing a page reload when navigating to a different page. With the history mode we can also prevent the page reload but without the strange # in our URL.</p><p><strong>Vuex</strong> is needed as state management. It saves the internal data/memory of your application. While your application runs the data will be stored in a central place. With this library, you can set and change the data in the store in a sophisticated way.</p><p>If you want to you can add the linter / formatter option. It is not needed to code along, but for readability it’s nice to have neatly indented code.</p><p>Next will be to open the project directory with the following command</p><pre>cd pokedex</pre><p>And run the application with</p><pre>npm run serve</pre><p>You will see the following when you follow the localhost url stated in the terminal (http://localhost:8080 by default if no other app is already running on that port)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aY4NkjSgDRU97wD3-XY86w.png" /><figcaption>Vue app out of the box running</figcaption></figure><p>If you open the project folder and go to <strong>package.json</strong> you can find the installed libraries in it and also the npm run commands you can run. That is where the <strong>npm run serve </strong>command came from. For now, you only need that command. However, it is good to know that you can add new commands and dependencies manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*aVFKqs4TpMjN1uxbw8ds6w.png" /><figcaption>Example of the package.json</figcaption></figure><p>Okay, first things first. We want to add the NES.css to give our application the 8-bit look and feel. Go to <strong>index.html</strong> and add the following between the <strong>&lt;head&gt; </strong>tags.</p><pre>&lt;link href=&quot;https://fonts.googleapis.com/css?family=Press+Start+2P&quot; rel=&quot;stylesheet&quot;/&gt;</pre><pre>&lt;link href=&quot;https://unpkg.com/nes.css@latest/css/nes.min.css&quot; rel=&quot;stylesheet&quot; /&gt;</pre><pre>&lt;style&gt;<br>      html, body, pre, code, kbd, samp {<br>          font-family: &#39;Press Start 2P&#39;, cursive;</pre><pre>}<br>&lt;/style&gt;</pre><p>You might be asking what the difference is between public and the src folder. Everything placed in the <strong>public</strong> folder will not be rendered by Webpack (module bundler) which will normally do optimizations. All of the static files such as favicon will be copied and pasted in the built version of the application. The index.html is the root of the application and that is why we define the core style here. Normally I’m more of a fan of defining global styling in external CSS files instead of inline CSS but here we are only defining the font-family.</p><p>The <strong>src </strong>folder is where all the Vue magic happens. Let’s create the pages, routing and state management in the <a href="https://medium.com/frontmen/build-a-pokedex-with-vue-cli-part-2-c3347ed4c7d4">next part of this tutorial</a> 👋 🐭</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc66920015b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/build-a-pok%C3%A9dex-with-vue-cli-fc66920015b3">Build a Pokédex with Vue CLI</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React hooks — Why and How]]></title>
            <link>https://medium.com/frontmen/react-hooks-why-and-how-e4d2a5f0347?source=rss----db21d8172a0---4</link>
            <guid isPermaLink="false">https://medium.com/p/e4d2a5f0347</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sebastiaan van Arkens]]></dc:creator>
            <pubDate>Fri, 25 Jan 2019 13:33:14 GMT</pubDate>
            <atom:updated>2019-01-25T13:48:12.253Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*vZtzdetbLQ7xEPxRBFJZGg.png" /></figure><h3>React Hooks — Why and How</h3><p>Recently the React team decided to bring <a href="https://reactjs.org/docs/hooks-intro.html"><strong>Hooks</strong></a> into our lives. I am pretty sure that you have heard of Hooks, though there are still a lot of people that haven’t taken the time or gotten the chance to experiment with them.<br>In this post, I will be showing you reasons <strong>why</strong> you should be using the new Hooks in your future work. Furthermore, I will be explaining <strong>how</strong> you can use them best and hopefully motivate you to build awesome things with Hooks.</p><p><em>In the code examples below you will see that I am using </em><em>&lt;&gt;&lt;/&gt; a couple of times. These are </em><a href="https://reactjs.org/docs/fragments.html"><em>Fragments</em></a><em>. In case you are not familiar with these, go check them out! They are awesome.</em></p><h3>Why Hooks</h3><p><em>TL;DR: Hooks give us the possibility to extract stateful logic which before could only be used in Class components and allow us to test this logic separately and reuse this logic.</em></p><h4>Mixins are no more</h4><p>Back in the days in order to reuse stateful logic, there were <strong>mixins</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f4d1718215f0c68ae5b7810b399b45/href">https://medium.com/media/42f4d1718215f0c68ae5b7810b399b45/href</a></iframe><p><strong><em>There were a couple of problems with mixins:</em></strong><br><em>Mixins introduce implicit dependencies</em> — In short, this means that both your component could rely on a method defined in your mixin (<em>or the other way around</em>) and there is no way to enforce this method to be present.</p><p><strong><em>Mixins cause name clashes</em></strong> — If you have two mixins that both define a handleKeydown method, you cannot use both and you cannot define a method with the same name on your component.</p><p>Eventually, mixins became considered harmful when we learned about <em>Higher-Order Components</em></p><h4>Higher-Order Components pattern</h4><p>The HOC pattern is pretty powerful yet so simple and elegant.<br>It’s just a function that returns your component wrapped with another component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bc01dc25ab10f1d526c49c2459f2181/href">https://medium.com/media/1bc01dc25ab10f1d526c49c2459f2181/href</a></iframe><p>Although it’s a great and powerful way there are some downsides too, for example using too many HOC’s could get you in <strong>wrapper hell</strong>.<br>There are entire libraries build around this pattern, like <a href="https://github.com/acdlite/recompose">Recompose</a>. Recompose made it easier to turn a dumb functional component stateful, simply by composing it with a couple of HOC’s — which in turn can get you to <strong>wrapper hell</strong>.</p><h4>The problem with classes and current lifecycle implementations</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/419f7dc73453da43ab6c7982bbdfeb1b/href">https://medium.com/media/419f7dc73453da43ab6c7982bbdfeb1b/href</a></iframe><p>As you can see in the example above we have defined our lifecycle methods: componentDidMount, componentDidUpdate and componentWillUnmount.<br>These lifecycle methods can of course only be defined once per component, which means that we have non-related effectful code within each one of these lifecycle methods, i.e., componentDidMount:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8b77c8d9d5531f4e632b4a531dd038f/href">https://medium.com/media/e8b77c8d9d5531f4e632b4a531dd038f/href</a></iframe><p>The fetchUser and the window.addEventListener have nothing to do with each other, yet they live the same code block. This can make class components messy and decreases code readability as complexity within your component grows.</p><h3>Hooks to the rescue</h3><p>With the introduction of Hooks, the use of functional components get’s promoted — This does not mean that classes are being removed from React.</p><blockquote><strong>Hooks are completely opt-in.</strong> You can try Hooks in a few components without rewriting any existing code.</blockquote><p><strong>What do Hooks solve?</strong> In class components it’s <em>hard to reuse stateful logic between components</em> and <em>complex class components become hard to understand</em> and <em>even harder to read</em>.</p><h4>useState</h4><p>Let’s say I want to have a controlled input within my component. I can create this controlled input by implementing theuseState Hook which will store the current value entered in the input and provides us with a method to update the state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b258f272a06a528a7405decb926f8bfa/href">https://medium.com/media/b258f272a06a528a7405decb926f8bfa/href</a></iframe><p>Amazing, right? we have just added a state to our functional component!<br>But what if we need multiple states? Don’t worry, you can!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01b921a491f12bb12be80fa05e3085b5/href">https://medium.com/media/01b921a491f12bb12be80fa05e3085b5/href</a></iframe><p>useState is amazingly simple to use and can be passed any datatype to store in the state, for example, objects. The difference between the original class component method setState and the method provided by useState to set the state is that it does not merge objects.</p><h4>useReducer</h4><p>In order to deal with a complex state like a nested object, we can use useReducer.<br>Everyone that has worked with <a href="https://redux.js.org/">Redux</a> before will notice similarities in syntax and usage:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88c834292022ab1d8946e89aff3bc0be/href">https://medium.com/media/88c834292022ab1d8946e89aff3bc0be/href</a></iframe><h4>useEffect</h4><p>useEffect is a lifecycle Hook for functional components that combines componentDidMount, componentDidUpdate and componentWillUnmount. useEffect is named useEffect because this is where you carry out your side effects, e.g., <em>ApiFetching</em>, <em>Subscriptions</em> or <em>Events</em>.</p><p>Even though it is a lifecycle method like the others, in a way it’s better than the rest. The reason for it being better is that you can make use of useEffect multiple times within a single component, which allows you to split up and keep related logic grouped together and maintaining readability of your code.</p><p>The most simple example of using useEffect, is to make our component listen to the keydown event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c00f710def4af9603d884bc0306f7f51/href">https://medium.com/media/c00f710def4af9603d884bc0306f7f51/href</a></iframe><p>As you can see we return a function inside of our effect which removes the eventListener, useEffect calls a returned function whenever it is time to clean up, like when a componentWillUnmount is called.</p><p>The second parameter in useEffect allows us to only run the effect when specific values have changed like in the following example, we only run the effect whenever the userId has changed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d16c85d86193e716432524a693605306/href">https://medium.com/media/d16c85d86193e716432524a693605306/href</a></iframe><p>Optionally the second parameter can also just be an empty array, in this case it will only execute on componentDidMount and componentWillUnmount and the effect won’t run on componentDidUpdate.</p><h4>Let’s put useState and useEffect to use</h4><p>Now that we’ve discussed useState, useReducer and useEffect I thought it would be nice to put some of these to use and refactor a class component to a functional component. Furthermore we will utilize the Hooks API and create a custom Hook that enables us to easily implement handling keyboard shortcuts on component level.</p><p>Let’s say we have a clock component which shows the current time and updates every second. Here we go!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fmo11mrz6l9%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fmo11mrz6l9%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fmo11mrz6l9%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/d95490476cd07ea7b430d78f2942b4fd/href">https://medium.com/media/d95490476cd07ea7b430d78f2942b4fd/href</a></iframe><p>We have a simple class component with a state containing the current time, a componentDidMount lifecycle method that creates an interval that updates the current time in the state every 1000 milliseconds and a componentWillUnmount which clears the interval when we unmount the component… Pretty straight forward.</p><p>Now the part that we actually want to refactor is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a63950dce2a4b0566d2e0152740aa443/href">https://medium.com/media/a63950dce2a4b0566d2e0152740aa443/href</a></iframe><p>We want to refactor the lifecycle methods above to use a single useEffect and the state to use useState so that we can refactor our class component into a functional component.</p><p><em>How would we do this using Hooks?</em><br>Let’s get started by importing both useState and useEffect. Let’s then turn our component into a functional component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db9a7c3e33d011a751fd77481202fee6/href">https://medium.com/media/db9a7c3e33d011a751fd77481202fee6/href</a></iframe><p>Now our variable time is undefined so let’s create a state called time, we will be using useState with a default value which is the current time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a30630deaad9e1d7e39a7437744396a/href">https://medium.com/media/2a30630deaad9e1d7e39a7437744396a/href</a></iframe><p>We now have a state within our functional component that stores our current time! As our next step we update this every second or so as we did in our class component, let’s implement the useEffect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6b6c4d8d3e9fe4d88e7b308fa5a2c3b/href">https://medium.com/media/f6b6c4d8d3e9fe4d88e7b308fa5a2c3b/href</a></iframe><p>Remember that useEffect acts as componentDidMount, componentDidUpdate and componentWillUnmount. In our situation, we do not want our effect to run again on componentDidUpdate so we pass an empty array as the second parameter to only run our code on componentDidMount and componentWillUnmount.<br>Adding to that you can see that we return a function from our effect and that we call clearInterval from within, this is us cleaning up, remember? That method gets called whenever React thinks it’s time to clean up like componentWillUnmount.</p><p>Here’s a working example of our refactored Clock component using Hooks</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fj26lzxnyy3%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fj26lzxnyy3%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fj26lzxnyy3%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/dafcb7f591bad8368205a5cfac5720e3/href">https://medium.com/media/dafcb7f591bad8368205a5cfac5720e3/href</a></iframe><p>The code looks different, shorter and much cleaner but does exactly the same, take a look at the <em>before</em> and <em>after</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5ugj2hLElc_HzngwVo3NQ.png" /><figcaption>Our code before and after the refactor</figcaption></figure><h4>Custom Hooks</h4><p>Now that we’ve gone over the basics, let’s go ahead and create our own custom Hook.<br>According to the React Hooks documentation</p><blockquote><strong>A custom Hook is a JavaScript function whose name starts with ”</strong><strong><em>use</em>” and that may call other Hooks</strong></blockquote><p>Of course you can name your Hook whatever you like. It is just best practice to start your hook with “use”. If you start your custom Hook’s name with “use”, React’s <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">eslint-plugin-react-hooks</a> is able to find bugs in the code using Hooks.</p><p>A custom Hook is a great way to create reusable logic, in this example we will create a custom Hook that allows us to easily add keyboard shortcuts on component level.</p><p>Imagine we have a list of some kind, in this example, we will use a list of people portrayed in the series “Silicon Valley”, I have set up a Codesandbox that you can use to get started. As you can see there is an active item highlighted, you can click any of the other items to highlight the item.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F8z1pj4vm12%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1%26module%3D%252Fsrc%252FListOfUsers.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F8z1pj4vm12%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1%26module%3D%252Fsrc%252FListOfUsers.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8z1pj4vm12%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4b9dcc64969e83cf3fba0a32fcb0708/href">https://medium.com/media/b4b9dcc64969e83cf3fba0a32fcb0708/href</a></iframe><p>Now let’s create and implement our custom Hook and Hook up the arrow keys so that we can navigate through this list using our keyboard.</p><p>We want to create a Hook that:</p><ul><li>Stores the active keys in the state;</li><li>Sets an active key in the state on keydown;</li><li>Removes an active key from the state on keyup;</li><li>Returns a method to check for active shortcuts in a human-readable way, for example, “shift+enter”;</li></ul><h4>Setting up the basics</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/259803225dd6a4d6ea4167ef7ab7f244/href">https://medium.com/media/259803225dd6a4d6ea4167ef7ab7f244/href</a></iframe><p>Next we will implement some logic to add an active key to our state, remove it from our state whenever it’s no longer active, create our isShortcut helper method and attach our event listeners, <em>let’s also not forget to clean up!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f708962b6c6b8243958efb9c94441244/href">https://medium.com/media/f708962b6c6b8243958efb9c94441244/href</a></iframe><p>We have just created a javascript function named useShortcut which adds two event listeners, one to handle our keydown and one to handle our keyup event.<br>On keydown, we are adding the newly pressed key to our activeKeys state, if it isn’t already active and on keyup, we remove the released key from the activeKeys state.<br>We’ve also created a helper method called isShortcut which accepts a string like “shift+enter” and splits these into separate keys after which it will check if <strong>all</strong> keys are currently present in our activeKeys state.<br>Our method returns an array containing our activeKeys array and our helper method isShortcut. And whenever React finds it’s time to clean up we remove our event listeners.</p><p>Great! We have just created our own custom Hook, let’s put it to use in our Codesandbox from earlier where we display a list of people.</p><p>We can use our new custom Hook by importing it and adding a useEffect to our component from which we call our helper method like previewed in the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db89ee07312fad3465e07c6d194fa784/href">https://medium.com/media/db89ee07312fad3465e07c6d194fa784/href</a></iframe><p>I have created a working version in Codesandbox so you can see the end result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fk09vnl342o%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1%26module%3D%252Fsrc%252FListOfUsers.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fk09vnl342o%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1%26module%3D%252Fsrc%252FListOfUsers.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fk09vnl342o%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cbd20483744e5e86c7d5d99ebb5192a/href">https://medium.com/media/2cbd20483744e5e86c7d5d99ebb5192a/href</a></iframe><p>Now I have got to be honest, our useEffect looks pretty messy… Remember that I told you that you can use useEffect as many times as you want inside a component? We could split this up into 3 different useEffects but instead, I think we should update our custom Hook and create a custom effect which we can just implement.</p><p>What does a custom effect look like?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41c8247da735bf4fe46e110a23dd5a71/href">https://medium.com/media/41c8247da735bf4fe46e110a23dd5a71/href</a></iframe><p>And behind the scenes, it’s not a lot more than a method that uses our custom Hook and useEffect and calls our callback method whenever a shortcut matches, here’s the source:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a62c0a0578c16ac3d64d41f96579960/href">https://medium.com/media/9a62c0a0578c16ac3d64d41f96579960/href</a></iframe><p>So to put it all together, I have created a Codesandbox that uses our new custom effect, take a look at the source!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkw864l6l07%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1%26module%3D%252Fsrc%252FListOfUsers.js&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fkw864l6l07%3Fcodemirror%3D1%26fontsize%3D12%26hidenavigation%3D1%26module%3D%252Fsrc%252FListOfUsers.js&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkw864l6l07%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed10ae215d45a4f1d01fdc0c402a2682/href">https://medium.com/media/ed10ae215d45a4f1d01fdc0c402a2682/href</a></iframe><p>Much cleaner eh..?</p><p>I hope you have enjoyed reading about the Hooks that we have discussed.<br>The Hook we have created in the above written examples is available on <a href="https://www.npmjs.com/package/use-shortcut">NPM</a>.<br>I will soon be posting a next part in which we will go over a bunch of other Hooks.</p><p>Thanks for reading :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4d2a5f0347" width="1" height="1" alt=""><hr><p><a href="https://medium.com/frontmen/react-hooks-why-and-how-e4d2a5f0347">React hooks — Why and How</a> was originally published in <a href="https://medium.com/frontmen">Frontmen</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>