<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lior Zisman on Medium]]></title>
        <description><![CDATA[Stories by Lior Zisman on Medium]]></description>
        <link>https://medium.com/@liorzisman?source=rss-b278d3880f09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*pzGYg-PzKu8ZeiR3igmdBA.jpeg</url>
            <title>Stories by Lior Zisman on Medium</title>
            <link>https://medium.com/@liorzisman?source=rss-b278d3880f09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:14:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liorzisman/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Video Games Are Bad For You]]></title>
            <link>https://medium.com/@liorzisman/why-video-games-are-bad-for-you-266b41c0f50a?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/266b41c0f50a</guid>
            <category><![CDATA[life-decisions]]></category>
            <category><![CDATA[lifestyle]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[mental-health]]></category>
            <category><![CDATA[gaming]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Wed, 29 Jul 2020 10:51:40 GMT</pubDate>
            <atom:updated>2020-07-29T10:53:20.078Z</atom:updated>
            <content:encoded><![CDATA[<p>Video games have recently became very popular, and even mainstream. <br>Once a domain of nerds mostly, people proudly introduce themselves as “gamers” nowadays.</p><p>Everyone seems to want to be a part of the industry — between major companies sponsor the best of gamers or competitions and influencers showing off their skills on stream, gaming is being celebrated.</p><p>Tournaments of various competitive games (“eSports”) offer some of the largest prize pools ever seen ($33 million for Dota 2’s <em>“The International 9” </em>or $30.4 million for Fortnite’s “<em>World Cup Finals</em>”).</p><p>One might wonder what exactly is the catalyst behind such a massive change in the narrative regarding the video games industry, as rarely shifts in public mindset occur naturally and effortlessly.</p><h3>The Hardcore Gamer</h3><p>I still remember the adrenaline and excitement. It was probably 2004 or 2005, we were racing for the “server first” kill of Ragnaros, the end boss of the first “World of Warcraft” raid. Simply put, our group of 40 dedicated gamers competed against other groups of 40 dedicated gamers for the prestige of being the first in the server to defeat that boss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JYEXvsm_r86nCXqRCMwvmA.jpeg" /><figcaption>Our “Kill Shot”. My character is circled, under the name “Zismen”. Typo on purpose.</figcaption></figure><p>The difficulty, besides defeating the encounter, is evident in many parameters — having 40 people available for a few nights a week, coordinating on voice chat and executing the strategy. And it felt exceptional, exciting and exhilarating every time I showed up to a raiding night.</p><p>There were frustrating moments, when someone screwed up or had to be offline that day. There were happy moments, when we made progress or had good times in the voice chat. There were sad moments, such as when we lost the “server first” to another guild. We did get our faction first though, and we were happy and proud.</p><p>This was my life, for quite a while. Switching everything off to go and conquer my goals in the “World of Warcraft”. I knew it all. People would turn to me for questions about how to do stuff or where to get that quest. I was “popular” and known. People would check what items my character would wear. <br>Needless to say, it aligned well with the positive feelings I was getting from every aspect of the game.</p><p>There is another side to this story, though. The side that is very easy to forget about, and honestly — sometimes, playing is done purposefully to forget.</p><p>It’s about a player’s kids not receiving enough attention or care the need and deserve that evening. It’s about schoolwork not being done, because you needed to prepare for the raid. It’s about skipping seeing your friends or partner that night because the guild needed you.</p><p>I was a teenager back then. Driven by the pure pleasure the game gave me, as it was basically designed by experts in psychology and human behavior to be alluring and borderline addictive, I would come home, toss my backpack somewhere, and dive into the virtual world.</p><p>Skipping schoolwork or other responsibilities became so easy. Who would choose actual work over a world of fun and excitement, that is just a few clicks away? Luckily, I still found the time to be with my friends, and even made some virtual ones too (I ended up meeting them in real life 15 years after we “met” online). Yet, the negative effect of what was my daily routine is clearly visible — and potentially life defining.</p><h3>Path of Least Resistance</h3><p>When it’s that easy to have fun with the illusion of achievements and social activity, it makes it very easy to gravitate towards that kind of activity.<br>And for some people, do it non stop.</p><p>What is the “hidden” cost of such behavior? Unsurprisingly, it interferes with processes that shape one naturally into a “regular” human being.<br>Especially from a social perspective.</p><p>Since it is a lot easier, especially for some individuals, to turn to the virtual worlds and “shield” themselves from the outside — they are likely to do it. <br>Like electrical current, humans also tend to choose the path of least resistance. People often avoid pain or work, even though things could be better once the work is done or the pain is dealt with — because not doing it is very appealing.</p><p>Instead of engaging with the world and people, you interact mostly with virtual entities, and sometimes humans. Those interactions do not train you for the real world. I know ex-gamers that their social skills were significantly deteriorated, and they now make up for lost time, if they can.</p><p>The escape from reality is sometimes a blissful option to have. But when it becomes the default one — you avoid handling stuff in your life, or use the games to avoid doing that. Perhaps its responsibilities around the house, or emotional weight you need to process — it will not get done.<br>And that deficit accumulates. You spend time and energy on fake objectives that will get you nowhere. By design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EP6n3RcQ0zu-8-SRxD6Tfw.jpeg" /><figcaption>A Dota 2 scoreboard. My highlighted row includes 20 kills, 0 deaths, highest level when the game ended. Dreamy stat line. Praised by team mates. How did it make me feel? Yet, did I really accomplish anything?</figcaption></figure><h3>Skinner’s Box</h3><p>B. F. Skinner was a psychologist, behaviorist, and a professor of psychology at Harvard University. He considered “free will” to be an illusion, and that human action is depending on the consequences of previous actions.</p><p>If the consequence of an action are bad, there is a high chance it will not be repeated, and vice versa — if the consequences are good, there is a high chance it will be repeated. He named this “reinforcement”.</p><p>This is demonstrated thoroughly in his “Skinner’s Box” series of experiments, used to study animal behavior. A hungry rat was placed into the box, which had a lever on the side. The rat’s random movement would accidentally knock the lever, which released a food pellet. The rat quickly learned to go straight to the lever after a few visits in the box. It learned that pressing the lever yields a rewarding outcome, so it would repeat it again and again.</p><p>Imagine killing 10 lizards (sorry lizards!) for some quest giver in a game.<br>In return, you get gold coins, a valuable currency. And, you even get an ‘achievement’ for doing the same quest for 5 days straight (true story.<br>They even call them “daily quests”).</p><p>Strangely similar, isn’t it?</p><p>This works the other way too. The removal of an unpleasant reinforcer can also encourage certain behavior. Skinner placed a rat in the box, and shocking it with unpleasant electric current, which caused some discomfort. As the rat randomly moved around the box, it would hit a lever, which immediately switched off the current. Once again, the rats quickly learned to go straight for the lever after a few visits in the box. The consequence of pressing the lever yielded a rewarding outcome, which in this case — is removal of a negative effect, so it would be repeated again and again.</p><p>Unsurprisingly, similar mechanisms can be found in many games. If you do not accomplish an objective in a timespan, you will lose something. In order to remove the negative effect, you needed to perform an action. For example, complete a dungeon, or defeat a boss monster.</p><p>When could potentially happen when psychological methods to encourage certain behavior (hint: ones that make the encouraging entity money) are implemented into innocently seeming “games” that affect kids and teenagers, mostly?</p><h3>What’s Next?</h3><p>All of this is not to say video games are the root of all evil, of course. Games are fun, they bring people together, create friendships and may even improve some skills. I attribute my level of english to my gaming years.</p><p>So why am I telling you all this? I hope to raise awareness and help people make choices that would benefit them in the long run. Keep this in mind — gaming companies are ultimately businesses, and they have their own best interest in mind. Can’t blame them for that.</p><p>You need to have your own best interest in mind, not only considering gaming, to ensure you build your life in a way which favors your goals, dreams and ambitions. But if you ask me, the path towards those never crosses with excessive gaming.</p><p>I say this from first hand experience.</p><p>I decided to talk more about this topic and life defining decisions in general.<br>You can <a href="https://twitter.com/LiorZisman"><strong>follow me on Twitter</strong></a> as I continue to document my journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=266b41c0f50a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Five Must-Know JavaScript Concepts for Interviews]]></title>
            <link>https://medium.com/@liorzisman/five-must-know-javascript-concepts-for-interviews-161c8144c977?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/161c8144c977</guid>
            <category><![CDATA[programming-interviews]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-fundamental]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Fri, 29 May 2020 13:16:54 GMT</pubDate>
            <atom:updated>2020-05-29T13:16:54.668Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1P7cmuEvd_C-c6euhFdIuw.jpeg" /><figcaption>Focus on what’s important. Photo by <a href="https://unsplash.com/@pawelskor?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Paul Skorupskas</a> on <a href="https://unsplash.com/s/photos/focus?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>JavaScript is well known for its seemingly ‘strange’ behaviour.<br><a href="https://www.destroyallsoftware.com/talks/wat">This</a> hilarious video always comes up to mind when I try to explain fellow developers who are not too familiar with JavaScript what is so quirky about it.</p><p>It doesn’t have to be like that, though. Especially if you are about to interview for a JavaScript related position, or trying to strengthen your understanding of the language’s fundamental concepts, this article is for you.</p><p>I will present the top 5 concepts I think one must absolutely MASTER in order to excel in every JavaScript interview. They will most likely enhance how you design and implement your JavaScript applications from performance and stability perspectives.</p><p>Let’s jump right in!</p><h3>Closure</h3><p>I decided to open with the closure (hah!), because its of critical importance, and therefore — almost always the interviewer will try to test your skills when it comes to closures.</p><p>So, what is a closure?</p><blockquote>“A <strong>closure</strong> is the combination of a function bundled together (enclosed) with references to its surrounding state (the <strong>lexical environment</strong>).”</blockquote><p>Essentially, when a closure is created, it ‘locks’ with it references to whatever was referenced, even if that something was present in a different scope, and even if that scope is no longer in place (for example, a function that completed execution).</p><p>Let’s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3a01ca9c27fdf5c9e4dfa4db72041d/href">https://medium.com/media/0d3a01ca9c27fdf5c9e4dfa4db72041d/href</a></iframe><p>In this example, outer function receives a food parameter, places it inside the suggestion variable, and returns a function (I named it for your convenience, it is not a must).<br>That returned function receives a parameter, name, and uses it in a string to be printed to the screen. You can also notice the suggestion variable being used. But by the time you try to invoke the returned function, outer has already returned. How is suggestion available?</p><p>The answer, of course, is in the closure — when the inner function is created to be returned, the suggestion variable used is being ‘locked’ into the closure that is created as well. That <strong>variable</strong> is there to be used whenever the returned function is invoked.</p><p>Why did I put the emphasis on the variable itself? Let’s look at the next example, which is commonly asked as a question in interviews in similar forms:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e092f493587d4b9b3f3c3a19ff6128a6/href">https://medium.com/media/e092f493587d4b9b3f3c3a19ff6128a6/href</a></iframe><p>You are given this for loop, and asked — what will be printed to the screen.</p><p>One might say — ‘Well, the setTimeout creates a function to run every time with the current value of i , therefore it prints 0, 1, 2, 3 and 4’.</p><p>… Which is obviously wrong. This code actually prints 5, 5, 5, 5 and 5.<br>Let me point the reason out:</p><p>‘Well, the setTimeout creates a function to run every time with the current <strong>value</strong> of i , therefore it prints 0, 1, 2, 3 and 4’</p><p>Since we learned the reference to the variable itself is ‘locked’ within the closure, and not the value — when the loop finishes running, the value of i is actually 5, and therefore each console.log will just print 5.</p><p>How can you fix this? Well, there are a few ways to do this, though I feel this one shows the most understanding of the concept. Look at it and see if you understand why it solves the problem, and how.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f48d5359a3bad9a94286831271be7ce/href">https://medium.com/media/1f48d5359a3bad9a94286831271be7ce/href</a></iframe><p>As you can see, I use an <a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">Immediately Invoked Function Expression</a> (IIFE) to pass i to the <strong>closure</strong> that will be created by the IIFE, and then that current value of i is ‘locked’ for use inside the setTimeout internal function (as x), resulting in 0, 1, 2, 3 and 4.</p><p>Closure related mistakes happen every day, when functions are invoked in a different-than-expected lexical environment. Learn this topic well.</p><h3>Execution Context</h3><p>In this context we have to mention this. The keyword is well used in programming languages, but operates slightly different in JavaScript.</p><p>You would use this when you need to refer to a property of the current object. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ddb8d7038c3c164e1fb4909f57ae9aa/href">https://medium.com/media/4ddb8d7038c3c164e1fb4909f57ae9aa/href</a></iframe><p>In the getPrice function, we want to use the price property of the object, so we refer to it using this. As expected, running this code would yield ‘The price is 17’.</p><p>However, what does this really refer to? What would happen after this change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/efaee0ff5770b5c46c4521c5f6c077f1/href">https://medium.com/media/efaee0ff5770b5c46c4521c5f6c077f1/href</a></iframe><p>Seemingly, by getting the reference to getPrice from pancake, we should the same thing printed, right? So… this would print ‘The price is undefined’.<br>Do you know why?</p><p>The answer relies in the <strong>execution context </strong>for getPrice.<br>In the first example, it is invoked ‘on’ pancake — therefore, pancake becomes the execution context for that function, and this refers to it.</p><p>In the second example, the function is taken away from its expected context. <br>So when we run it, what is the value of this? What is the <strong>global</strong> execution context the function seems to be running in (since its within the global scope)?</p><p>That depends where you run it. If you open the developer tools in a browser and enter console.log(this), you will get the window object — which is the global execution context for JavaScript running in the browser, and it does not naturally come with a property named price. So we end up with an undefined price.</p><p>Understanding this concept of execution context in your scopes is vital, both for interview questions and to spare you of unnecessary debugging in your applications.</p><h3>Prototypes</h3><p>What does [1, 2, 3] and [4, 5] have in common? They are both arrays. <br>In other programming languages, you might say they are both of the same class, but in JavaScript we have a different object system — and it’s based on prototypes. To create a new array, behind the scenes, you don’t actually refer to a ‘blueprint’ of some sort that defines the object structure. Instead, you refer to an actual object instance. Objects inherit their properties directly from other objects.</p><p>What does that mean? , with a ‘hidden’ property called __proto__. <br>For example, for arrays, the __proto__ points to Array.prototype — which is an object that contains all array methods you know and love, such as indexOf , map or concat.</p><p>When a new array needs to be created, a constructor function is invoked to create that instance. So in face, Array.prototype.constructor is actually Array itself. The prototype itself is then assigned to the instance’s __proto__ property, and this is how the methods are invoked on that instance.</p><p>Why is this interesting? Let’s say you need to add a method to <strong>all</strong> arrays. During runtime (!). That resets all elements of the array to 0.<br>You could do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f553c6d84786f97c8eb18ef898e4be4e/href">https://medium.com/media/f553c6d84786f97c8eb18ef898e4be4e/href</a></iframe><p>The output would show that arr is now [0, 0, 0].</p><p>How did that happen? We added a new property of the <strong>Array prototype</strong>, that all arrays point to, and defined that to be a function that does what we needed. Since that point, all arrays now have access to that method.<br>Magic huh?</p><p>Another important thing to mention, is that this knowledge lets us utilise a prototype’s functions where they fit on objects from another prototype, even though they are not present in that prototype.</p><p>Let’s look at this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edf2d5e3190e2a0ce0548fa01b70a540/href">https://medium.com/media/edf2d5e3190e2a0ce0548fa01b70a540/href</a></iframe><p>When querying DOM elements, you often end up with a NodeList or a HTMLCollection. Those indeed look like arrays, but we now understand that they are from a different prototype — and that means, the access to the Array prototype methods is not guaranteed. But we’d really like to use map or forEach on them sometimes. How can we achieve that?</p><p>Notice how in the first example, we referred to the array as this to reset its elements to 0? Well, we learned that in order to set this to what we need, we must control the <strong>execution context</strong> and provide the correct <strong>lexical environment</strong>. We can do this using call or apply.</p><p>Let’s see how it is done:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e6b0a6f26a0dbbe3f8f5a25ceb18b7c/href">https://medium.com/media/2e6b0a6f26a0dbbe3f8f5a25ceb18b7c/href</a></iframe><p>Advanced thing to notice — where is call coming from?</p><p>The answer is… from the prototype of map, which is a of the Function prototype!</p><p>call receives the this value and arguments provided individually.<br>apply gets the this value and arguments passed in an array.</p><p>Let’s have some fun with that and prototypes. <br>Here’s a <strong>complex</strong> example — adding the built in Math.max to the array prototype. The catch? Math.max receives the numbers as parameters (as opposed of using the this).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed016dbeca58fa3e30f256fd3a60ddce/href">https://medium.com/media/ed016dbeca58fa3e30f256fd3a60ddce/href</a></iframe><p>This was a perfect opportunity to use apply — because the thing we want to get the maximum of is an array, and apply expects an array of arguments for that second parameter. null was provided as context, because Math.max does not refer to this in its use.</p><p>Knowledge of prototypes is key when it comes to high-end JavaScript understanding, and is tested often in interviews. Study it well!</p><h3>Asynchronous Programming</h3><p>JavaScript is single threaded. Meaning, it has one call stack, and one memory heap. It must execute a piece of code, before moving to the next.</p><p>Considering this, can you explain how functions like setTimeout or setInterval work? Furthermore, explain what would be printed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa22574bb2df4209ee4c78e7794b119/href">https://medium.com/media/3aa22574bb2df4209ee4c78e7794b119/href</a></iframe><p>The answer is 3, then 1, and finally 2. Do you know why?</p><p>Even though the setTimeout operations are timed to be executed in 0ms, it does not get executed immediately. It is being placed in a callback queue to be run when the main (and only) thread has ‘time’ to do it. Until that time, they will sit in the queue, waiting.</p><p>And the console.log(3)? It just gets placed directly in the stack, ready to be executed.</p><p>This whole operation is in managed by something called the <strong>Event Loop</strong>. <br>It feeds the stack with callbacks from the queue, in order, when the stack is empty. Here is a snapshot after the code in the example has been executed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nhcTxJGM338ykxnpFIMb-A.png" /></figure><p>We can see the setTimeout operations placed in the queue, and the console.log(3) placed in the stack. Then, the task in the stack gets executed, and only after that — the stack is fed with tasks from the queue, by the Event Loop.</p><p>This mechanism allows for asynchronous programming where we only have one thread. It all happens synchronously.</p><p>I highly recommend <a href="https://www.youtube.com/watch?v=8aGhZQkoFbQ">this</a> video if you want to understand the Event Loop better.</p><h3><strong>Promises</strong></h3><p>Speaking of asynchronous programming, we have to mention promises.</p><p>It is an object that will yield a value upon success or failure of an operation (for example, a network request), and has three possible states: pending, fulfilled and rejected.</p><p>In other words, the asynchronous method returns a <strong>promise</strong> to provide a value sometime in the future. At that state, the promise is in <strong>pending</strong> state, neither fulfilled or rejected. When it finally resolves, it will have one of those latter states.</p><p>Let’s say I want to write a function that simulates a network request — for mock or testing purposes. Can you write such a function?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a25e7e41d04116ffacb0ec3bb915a8b5/href">https://medium.com/media/a25e7e41d04116ffacb0ec3bb915a8b5/href</a></iframe><p>The mockRequest function does not care about its arguments, it just creates a new promise, that will always resolve — within three seconds, thanks to the setTimeout. I then chained a then to print the resolved value of the promise.</p><p>Promises are fundamental to client side development with JavaScript, and you should be comfortable creating and using them through 3rd party providers.</p><p>I hope I helped you learn a few things, and improve your JavaScript knowledge and understanding, so you can write better code and be more successful in interviews!</p><p>For more articles, information and interesting offers, visit my <a href="https://www.liorzisman.com/?utm_source=medium&amp;utm_medium=article_link&amp;utm_campaign=must_know_js">webpage</a>, and become a better developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=161c8144c977" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git — an advanced introduction]]></title>
            <link>https://medium.com/@liorzisman/git-an-advanced-introduction-f72aedf56665?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/f72aedf56665</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Mon, 03 Sep 2018 12:39:22 GMT</pubDate>
            <atom:updated>2018-09-03T12:39:22.309Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git — an advanced introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TsCUbWC2AzCeeFwaZd7oSw.jpeg" /><figcaption>A wonderful sight at the end of the branch. Photo by <a href="https://unsplash.com/photos/ulreZ0ubl8A?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">dorota dylka</a> on <a href="https://unsplash.com/search/photos/branches?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>Source Control systems play a key role in software development processes, but not only — from content writers to designers, people use it to manage versions of their projects.</p><p><a href="https://medium.com/@liorzisman/git-a-short-introduction-b41c651bf26">Part 1</a> covered reasoning behind Source Control systems, and went over the foundations of working with Git, a commonly used Source Control system.</p><p>In this part I will cover more advanced, yet crucial, functionality of Git — working with remote repositories, branches, and problems that might occur when simultaneous work is done — and how to solve them.</p><h3>Remotes</h3><p>In order to enable collaboration, the project must be available somewhere for your team to access. It also effectively acts as a backup, as the project is fully available in the remote location, providing you keep it up-to-date.</p><p>To allow that, repositories are normally hosted somewhere on the internet (on a ‘remote’ server). It is worth noting though, a remote repo could also be on your local machine. The term ‘remote’ only specifies that it’s elsewhere.</p><p>For that to happen, your Git project needs to have a destination address for that remote location, and a name for that address. <br>You can have more than one such destination for a project, so traditionally the main one is named <strong>origin</strong>.</p><p>To add an origin for your repo, enter git remote add origin &lt;address&gt; .<br>You can view the remote addresses of your Git project with git remote -v .</p><p>Sometimes, you will need to get a fresh copy of a project from a remote repo. You can use git clone &lt;address&gt; for that. It will also add that address as the origin for the project.</p><h3>Slightly Branching</h3><p>Let’s branch for a moment from remotes and talk about… well, <strong>branches</strong>.</p><p>In a nutshell, a branch in Git is simply a lightweight movable pointer to a commit. The default branch name in Git is <strong>master</strong>, and is created automatically when you init a repo. As you make your commits, the master branch ‘pointer’ points at the last commit you made, and moves forward automatically.</p><p>You can always create more of these pointers, which will initially point to the same commit as the pointer you branched from, and select which one is the currently working branch — meaning the commits will be ‘pointed’ by that branch pointer. Notice — those commits will not affect any other branch.</p><p>This enables <strong>working in parallel</strong> on the same project — each collaborator can work on a branch of his own, and <strong>merge</strong> the work back to the main branch when he’s done. We’ll talk about merging later on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQiDHFljbP3wC-MtFSxZlg.png" /><figcaption>Typical branching workflow. Each person branches off the main one, and merges his work to it when he’s done.</figcaption></figure><p>This also adds a major benefit — since the commits ‘belong’ to a separate branch, incase you want to discard your work or go back to the previous state (the most up to date master), you can just delete the branch or start a new one, which is way easier and efficient than manually deleting, or reverting to an early commit on the master branch. This is why I use branches even when I work alone on a project — maintenance is a breeze and I don’t ‘mess’ the codebase when I experiment with a new feature or new technology.</p><p>In order to get the list of branches of the current repo from your remote, enter git fetch. It will <strong>fetch</strong> the list from the server, so you can select any of them as your currently working branch, and proceed to commit to that branch.</p><h3>Push and Pull</h3><p>So far we saw how to configure a project for collaborative work. Now lets learn how to put that to use.</p><p>In order to put the changes you committed to a branch on a remote, simply run git push. It will modify the branch on the remote to match your local version.</p><p>But how does Git know how to ‘merge’ the commits into one version of the branch? This operation can be done because the snapshots taken of a branch are ordered as discussed in <a href="https://medium.com/@liorzisman/git-a-short-introduction-b41c651bf26">part 1</a>.<br>One might wonder what could happen if two (or more) parallel changes are committed to the same part of a file, and how Git resolves this ‘conflict’.</p><p>Before we approach that though, I should mention the reverse operation — syncing changes committed to a remote branch to your local working copy. This is a common thing to do when working collaboratively on a branch.<br>This is done by doing git pull. And as before, this could also result in a ‘conflict’.</p><h3>Merges — Putting it all together</h3><p>The ultimate goal of all of this collaborative work on branches is to be able to combine the work of everyone into one branch. Putting the changes committed to a branch on another branch is called <strong>merging</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*1GQ4FLPm4xI1piqxft-5MQ.png" /><figcaption>The complete picture.</figcaption></figure><p>Because Git knows which changes are more recent, it can put together the commits in the correct order in the destination branch of the merge, assuming it the sequence ‘makes sense’ — putting the combined work together.</p><p>But, if the same part of a file has been changed in two different ways we get a <strong>merge conflict</strong>. In this situation Git does not know how to order the changes (which one is more relevant than the other?) and presents it to the user to resolve manually. You can choose to keep the changes from either branch or keep all changes.</p><h3>Final words</h3><p>I hope you enjoyed the two part Git introduction. Source Control, and especially the commonly used Git, has become such an integral part of how we manage versions of our products — working with it is almost a must-have skill. And the more you understand it, the better you will be able to use it to your benefit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f72aedf56665" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Git - a short introduction]]></title>
            <link>https://medium.com/@liorzisman/git-a-short-introduction-b41c651bf26?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/b41c651bf26</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Sat, 04 Aug 2018 17:25:26 GMT</pubDate>
            <atom:updated>2018-08-05T06:30:35.066Z</atom:updated>
            <content:encoded><![CDATA[<h3>Git — a short introduction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SoRt06-YX3GNLgQSGr0TYw.jpeg" /><figcaption>“Any fool can know. The point is to understand.” — Albert Einstein. Photo by <a href="https://unsplash.com/photos/wk833OrQLJE?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">_HealthyMond .</a> on <a href="https://unsplash.com/search/photos/understand?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>.</figcaption></figure><p>Two colleagues of mine, data scientists, asked me to come over for a moment. They were focused and had desperation in their eyes. I asked what I could do for them, and I was told ‘we get this weird error when we try to<br>git pull --rebase’.</p><p>After helping them with their issue, we discussed a few things about Git.<br>At some point I commented ‘but that’s probably boring for you data scientists’, to which one of them replied ‘I would still like to know what I’m doing’.</p><p>And then it hit me. I took it for granted that everyone around me at work — designers, data scientists and product managers — understand source control and can use Git (what we use at work) with ease, at least the basic features.</p><p>So here’s my introduction to Git. I will start with covering the concept of Source Control and why is it useful, before diving to the basic functionality.</p><h3>Source Control</h3><p>Imagine working on a painting. A surreal tropical beach. Halfway through drawing the palm trees, you have an idea — what if you made one tree orange? You proceed to paint one tree orange. Immediately you realise it does not fit. How do you fix it? You could paint over the orange, to return to the previous colour. It also might be such a mess that you must discard the whole painting and start from scratch. Probably I can come up with a few more complicated and undesirable solutions — but you get the picture.</p><p>This is where Source Control (also known as Version Control) comes in handy. It’s a system that lets you record changes done over time so you can recall specific versions of your project at will. This ensures that if you screw things up or lose parts of your work, you can easily recover. You can also compare changes between versions of your project.</p><p>There are a few commonly used systems for Source Control. I will focus on a the commonly used Git.</p><h3>Git basics</h3><p>The way Git records the changes you do to your project is by recording <strong>snapshots</strong> — every time you save the state of your project, Git takes a ‘picture’ of what your files looked like at that moment, and stores a reference to that snapshot. If files have not been changed — Git does not record those files in the snapshot taken.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*x6leKOxsxUkzNamTFWyqxA.png" /><figcaption>Storing data over time — recording changed files, linking to previous (identical) files otherwise.</figcaption></figure><p>In order to do so, Git thinks of the data as a miniature filesystem. In order to initialise that filesystem for a project, called a <strong>repository</strong> (or a repo, for short), you need to navigate to your project’s folder in the terminal (in any OS) and type:</p><p>git init</p><p>This will create a subdirectory named .git that will contain the repo skeleton. Hence, if you’re already working on a project with a Git repo, this step is not required, as the repo has already been initialised.</p><h3>Files and Commits</h3><p>Files that Git ‘knows’ about are Tracked. Everything else — Untracked. Those are files that were not in the last snapshot and not added to the next snapshot.</p><p>In order to track a file, it has to be added with git add &lt;filename&gt; . <br>You can also add your entire folder using git add * . Be warned — it might add files you did not think about.</p><p>Correspondingly, to un-track a file, git rm --cached &lt;filename&gt; . This will return the file to untracked state. Without the --cached flag, the file will be deleted. It has a safety mechanism that requires you to add the -f flag in order to complete.</p><p>A Tracked file in your Git project can be in one of three states:</p><ul><li>Unmodified — A file that has not been changed since the last snapshot.</li><li>Modified — A file that has been changed since the last snapshot, but not yet ‘marked’ to be added to the next.</li><li>Staged — A modified file that has been ‘marked’ to be added to the next snapshot. An added file turns directly to be in staged state.</li></ul><p>Please note, git add is also used to stage changes in a modified file. <br>For example, if you added a file, and then modified its contents, then in order to commit the latest changes, you must stage those by using git add on that same file. This pattern allows you to commit the initial version of the modified file without including the later changes just yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*bYmQlQkM05jJCHWtDh0FvQ.png" /><figcaption>The lifecycle of tracked files in Git.</figcaption></figure><p>In order to view the status of your files, enter git status . This will display the status of your files.</p><p>The action of saving a snapshot of the changes since the last one is called to <strong>commit</strong>. When you perform a commit, staged files are recorded in the snapshot, and since they are not different compared to the last (the one you just took) snapshot, they turn to unmodified files.</p><p>In order to perform a commit, you must also provide a message, so the reason and contents of this commit will be clear when someone views it in the future. Type git commit -m &quot;&lt;commit message&gt;&quot; in order to execute the commit. <br>You can also just run git commit , and this will start the default editor for your terminal for you to enter the commit message.</p><h3>Summary</h3><p>I think its critical to cover the reasoning behind Git before proceeding to features. Understanding the mechanism will help you make better decisions when it comes to keeping a project maintainable and being able to handle complications when they occur.</p><p>In the next part I will cover slightly more advanced, yet crucial, functionality of Git — remotes, branches and merges.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b41c651bf26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A short review of when you should be using the React Context API]]></title>
            <link>https://medium.com/@liorzisman/a-short-review-of-when-you-should-be-using-the-react-context-api-cafcd49404ca?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/cafcd49404ca</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[context]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Mon, 02 Apr 2018 21:49:18 GMT</pubDate>
            <atom:updated>2018-04-03T10:57:41.731Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUTnD5RV8o7WPffXJttDWA.jpeg" /><figcaption>Giving a flower is a nice way to add romantic context to a situation. Photo by <a href="https://unsplash.com/photos/3reWf5Rp4jo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Evan Kirby</a> on <a href="https://unsplash.com/search/photos/giving?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As you probably already know, React’s Context API just finally became official in version 16.3. Up until now It has been an experimental API and was generally considered an ‘advanced’ feature, as “<a href="https://react-cn.github.io/react/docs/context.html">Most applications will never need to use context</a>”.</p><p>Now with the new API finally out and all the hype around it, I felt it encourages use that might be forced and not necessary.</p><p>I remembered the tweet about Context by <a href="https://medium.com/@dan_abramov/">Dan Abramov</a> and I feel it should be used as the base for this discussion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*clACBuPVmr9iZJM_8AdwWA.png" /></figure><p>So what has changed since July 2016? Let’s examine all three if statements:</p><ul><li>The first clause states that if you are a library author and need to pass something down deeply, you should be fine with API changes and buggy updates. However, now with the new API being official — there is most likely no need to worry about buggy updates or frequent, breaking API changes.</li><li>The second clause asks you to use a ‘Higher Order Component’ (HOC) instead of using the API directly. I feel this still stands strong — it fits well with patterns normally used with the Context API. It also mentions typical use-cases for context.</li><li>The third and final clause urges you to file an issue if a library asks you to use context and ask them to provide a HOC, to further promote the idea of using HOCs to pass context.</li></ul><p>So overall, we can conclude that since the Context API is now more reliable and safer to use, we can worry less about using it — but developers should still consider when to use it with care.</p><p>Let’s take a look at two typical use cases for the Context API:</p><h3>#1: Dependency Injection</h3><p>As I explained in my article about <a href="https://medium.com/@liorzisman/5-very-useful-react-tips-you-might-have-never-heard-of-92a4c25ddd44">some very useful React tips</a>, you can use React’s Context API to pass data to a deeply-nested component without polluting the interfaces all along the way.</p><p>Let’s see how it is done with the new Context API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/078b1e7cfa020acf51738257a3e4367b/href">https://medium.com/media/078b1e7cfa020acf51738257a3e4367b/href</a></iframe><p>In this example, App renders the Post component inside the Provider , the HOC provided by the createContext function. This enables you to acquire the context, no matter how deeply nested the usage might be, by rendering the Consumer HOC, also provided by the same mechanism.</p><p>Post renders a Title and a Message , which consume the relevant values from the passed context object inside the Consumer .</p><p>This simple example demonstrates the simplicity and clarity of the new API, as it is very readable and easy to use.</p><h3>#2: Theming</h3><p>Building on the <a href="https://reactjs.org/docs/context.html#dynamic-context">documentation</a> example, let’s see how we can theme components using context:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cd92bb2ba40b88c220a5b6d3cb7364c/href">https://medium.com/media/8cd92bb2ba40b88c220a5b6d3cb7364c/href</a></iframe><p>Here we have two theme-able components — the ThemedButton and ThemedLabel . The button renders a label, which renders text.<br>By toggling between the themes on the state (using the extra button), the components cycle between two themes — bright text on a dark button, and dark text on a bright button. This is done with ease as the theme context provider is a ‘single source of truth’ for the theming options, and yet allows the theme to be easily consumed by all the theme-able components.</p><h3>Final words</h3><p>I’m glad the Context API became official. It’s a powerful tool that brings simplicity and elegance to otherwise cumbersome patterns to implement. <br>Just keep in mind to use it only when it is fitting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cafcd49404ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 very useful React tips you might have never heard of]]></title>
            <link>https://medium.com/@liorzisman/5-very-useful-react-tips-you-might-have-never-heard-of-92a4c25ddd44?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/92a4c25ddd44</guid>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 22:51:24 GMT</pubDate>
            <atom:updated>2018-03-20T17:13:34.194Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfqQzq2ote3mLK19FcdCKQ.jpeg" /><figcaption>Always stay open for new ideas. Photo by <a href="https://unsplash.com/photos/7e2pe9wjL9M?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Riccardo Annandale</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>After I noticed the comments to a recent <a href="https://twitter.com/_ericelliott/status/974866657322479616">tweet</a> by <a href="https://medium.com/u/c359511de780">Eric Elliott</a> about a pretty clever way to use a debugger inside your JSX, I realised this was not common knowledge. Such simple tricks should be more widely known, so I decided to come up with this list of 5 useful React tips that could improve your code development experience.</p><h3>#1: Using debugger in JSX</h3><p>I believe everybody who developed in React for a while found himself trying to make sure his component receives the correct props to render with. <br>Sure, you can always log the props, but this has a few disadvantages:</p><ul><li>The console is sometimes messy and chaotic, and not easy to follow.<br>Possibly need to distinguish between props printed from different components (which might be of the same class).</li><li>Having a ‘Snapshot’ of the situation can help you follow the rendering process closely and resolve problems beyond the scope of the props.</li></ul><p>When I encountered this situation, I naturally tried to use a debugger statement inside the JSX. The problem? JSX expects expressions, not statements. How do you turn a statement into an expression?</p><p>My solution was { eval(&#39;debugger&#39;) } . Since eval does evaluation (duh) of the expression inside it, I could ‘sneak’ a debugger inside JSX successfully.</p><p>Another method I learned, following the <a href="https://twitter.com/_ericelliott/status/974866657322479616">tweet</a> I mentioned earlier, is to use an Immediately Invoked Function Expression (IIFE) to use the debugger, and it also lets you add the props right after it to view them:<br>{ (() =&gt; { debugger; this.props; })() } . Thanks <a href="https://medium.com/@_ericelliott">Eric</a>!</p><h3>#2: Passing a function to setState</h3><p>As you probably know, setState is not synchronous — React may delay it for better perceived performance, and in fact it is actually not guaranteed that the state changes will be applied immediately.</p><p>This behaviour can yield unexpected results. A classic example would be:</p><pre>this.setState({ count: this.state.count + 1});<br>this.setState({ count: this.state.count + 1});<br>this.setState({ count: this.state.count + 1});</pre><p>Assuming this.state.count started as 0, what would be the value of it after these 3 lines? The answer might be surprising — 1. The reason is that the state does not actually update between each call of setState, so in reality, they are all just setting the value of count to 1.</p><p>How to solve this? I was pretty amazed it took me that long to find out that setState can receive a function as a parameter! The function must be with the signature (prevState, props) =&gt; stateChange . <br>So our example now looks like this:</p><pre>const incrementStateCount =<br>  (prevState, props) =&gt; ({count: prevState.count + 1});</pre><pre>this.setState(incrementStateCount);<br>this.setState(incrementStateCount);<br>this.setState(incrementStateCount);</pre><p>How is this any different? prevState is a reference to the <strong>previous state</strong>. Meaning, in a way, we create sequential behaviour by using the function argument to increment the value, since both prevState and props are guaranteed to be up to date. So the final value of this.state.count will be 3.</p><h3>#3: Dependency Injection using Context</h3><p>Sometimes you might find yourself in a situation with deeply nested components, forcing your interfaces to allow passing of props through middle-tier ones just so they will be available in the deepest components.<br>This hurts the readability and maintainability of your code.</p><p>Those familiar with <a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a> probably can solve this problem by implementing a higher-order component. However, the effort this requires and the effect it has on the code is huge, and it might not solve the problem completely.</p><p>This can be solved by using React’s Context API. <br>Some additional things have to be defined — let’s take a look at this example:</p><pre>class Title extends React.Component {<br>  render() {<br>    return &lt;span&gt;{this.context.title}&lt;/span&gt;;<br>  }<br>}</pre><pre>Title.contextTypes = {<br>  title: string<br>}</pre><pre>class Header extends React.Component {<br>  render() {<br>    return &lt;Title /&gt;;<br>  }<br>}</pre><pre>class App extends React.Component {<br>  getChildContext() {<br>    return {title: &#39;Pancakes are the best!&#39;};<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;Header /&gt;<br>    );<br>  }<br>}</pre><pre>App.childContextTypes = {<br>  title: string<br>}</pre><p>In this example, the App component will render the title , even though it was never explicitly passed down to the deeply-nested Title component.</p><p>What did this require? The main, parent component, needs to specify its childContextTypes , and implement the getChildContext method to provide values. Those will be passed down to any child component that specifies the data it needs in his own contextTypes .</p><p>Furthermore, if contextTypes is defined in a component, a few <a href="https://reactjs.org/docs/context.html#referencing-context-in-lifecycle-methods">lifecycle methods</a> will receive an additional context / nextContext parameter, providing you with more control.</p><h3>#4: Error Boundaries</h3><p>A Javascript error in a part of the UI should not break the entire application.<br>It’s something you should always consider — gracefully handling errors inside your components. It also benefits the development process greatly.</p><p>React 16 introduced the concept of ‘Error Boundaries’. They are components that are meant to catch errors in their child component tree, and handle it gracefully. According to the <a href="https://reactjs.org/docs/error-boundaries.html">documentation</a>, <em>“Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them”.</em></p><p>To create an error boundary component, simply make a component that implements the componentDidCatch method. It receives the error and information as arguments, and it is the place to display fallback UI, log the error to a service, and make sure the application can continue operating.</p><p>A good example of such a component is described in the documentation:</p><pre>class ErrorBoundary extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { hasError: false };<br>  }</pre><pre>componentDidCatch(error, info) {<br>    // Display fallback UI<br>    this.setState({ hasError: true });<br>    // You can also log the error to an error reporting service<br>    logErrorToMyService(error, info);<br>  }</pre><pre>render() {<br>    if (this.state.hasError) {<br>      // You can render any custom fallback UI<br>      return &lt;h1&gt;Something went wrong.&lt;/h1&gt;;<br>    }<br>    return this.props.children;<br>  }<br>}</pre><p>And then use it like this:</p><pre>&lt;ErrorBoundary&gt;<br>  &lt;MyWidget /&gt;<br>&lt;/ErrorBoundary&gt;</pre><h3>#5: Return arrays to avoid redundant elements</h3><p>Every React developer is probably a bit annoyed when he wraps a list of elements in a render with a span or a div, just because he must return one element from it. This is indeed annoying for a few reasons:</p><ul><li>This causes rendering of pointless elements to the DOM.</li><li>Invalid HTML might be created by mistake (where you need correct nesting, for example li inside of ul or td inside of tr).</li></ul><p>Turns out, you don’t have to suffer from these effects. Simply return an array of items! Don’t forget to provide a key.</p><pre>// map returns an array of list items.<br>// no need to wrap the returned list in an extra element!<br>const ListItems = ({items}) =&gt;<br>  items.map(item =&gt; &lt;li key={item}&gt;{item}&lt;/li&gt;);</pre><pre>// can render the list inside a ul and have valid HTML<br>...<br>&lt;ul&gt;<br>  &lt;ListItems items={items} /&gt;<br>&lt;/ul&gt;<br>...</pre><p>React also introduced <a href="https://reactjs.org/docs/fragments.html">Fragments</a>, which is a different way to achieve the same result — cleaner DOM, more accurate HTML.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92a4c25ddd44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Controlled Components —And why you should be using them]]></title>
            <link>https://medium.com/@liorzisman/controlled-components-and-why-you-should-be-using-them-61cb8357bf27?source=rss-b278d3880f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/61cb8357bf27</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lior Zisman]]></dc:creator>
            <pubDate>Sat, 20 Jan 2018 21:38:25 GMT</pubDate>
            <atom:updated>2018-01-21T12:54:19.513Z</atom:updated>
            <content:encoded><![CDATA[<h3>Controlled Components — And why you should be using them</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa7Y-eqdfisb5RbNa_bafA.jpeg" /><figcaption>Composition of simple objects can be sometimes a work of art. Photo by <a href="https://unsplash.com/photos/hhlF006622M?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Gabriele</a> on <a href="https://unsplash.com/search/photos/composition?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Components are the building blocks of modern front-end development. They let you split the UI into independent, reusable pieces, and think about each piece in isolation, and there are various approaches and concerns when it comes to their implementation.</p><p>A component can be described as a function that takes information provided externally (also known as ‘props’), along with their own self-maintained information (also known as ‘state’), and generates a UI element (such as buttons, images or date pickers).</p><p>Composition is a process where you create a more complex component using other, more basic components. The approach you choose when implementing your components will often dictate how the parts of the application will communicate and operate together when composed. This has a great impact on how maintainable your application will become, and how good the development experience will be.</p><p>Which brings me to the topic of this article, the concept of Controlled Components. But before we explain what they are, let’s examine a typical composition case and discuss what problems can emerge.</p><h3>Motivation</h3><p>I will use React in the code examples as I believe it is widely known and abstracts technicalities, so we can focus on the concepts. Even if you are unfamiliar with React, I am sure the examples will be very clear to you.</p><p>Let’s assume we need to implement a section of a form, that lets the user enter his first and last name, and we are provided with a TextInput component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e7d319e86dbb093ada2861215b1e1ff/href">https://medium.com/media/8e7d319e86dbb093ada2861215b1e1ff/href</a></iframe><p>This is a classic component — it takes a prop (placeholder text for the input) and maintains its value (as a state), and returns the UI element generated.</p><p>Naturally, we will want to use two of these — one for the first name, and one for the last name. Then we might want to display that full name in a label.<br>Our sub section of the form would probably look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f2dd48df47494549b7cee23a3d1b892/href">https://medium.com/media/8f2dd48df47494549b7cee23a3d1b892/href</a></iframe><p>At this point, I want you to think — how would you get the full name for display in the &lt;p&gt; tag? And to refine — what is the problem in the design of TextInput that creates a difficulty?</p><h3>The Problem</h3><p>The information the TextInput stores in its internal state is not easily accessible from the outside — we would have to apply another method to acquire this information (for example, put an attribute on the input and use a DOM query to get its value). These methods may be expensive and inefficient. Also, if you wanted to change the information through external means, you would have to take similar actions.</p><p>These observations hint us there might be a problem with the way the data flows in the composite component we created. The interface to modify and control the internal components is missing the most important part — the text which it contains!</p><p>What if — We let the parent component manage everything which is not necessary to store internally, so our internal component becomes closer to operate as a function that translates properties into UI elements (with minimal internal state interference)?</p><h3>Controlled Components</h3><p>Lets change TextInput and FullName components so they conform to this concept. First, TextInput:</p><p>As discussed above, the component needs to receive its value as a property. The component now looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32dc36c70e57114c64bef346054af96f/href">https://medium.com/media/32dc36c70e57114c64bef346054af96f/href</a></iframe><p>As the name of the file suggests, something is missing.<br>If you render this component and try to enter text into it —<br>nothing will happen.</p><p>The reason is — the component has, currently, no mechanism to notify whoever provided him with the value, that this value has changed (in our case — new text has been entered). Without this mechanism, the TextInput is not usable.</p><p>The most logical way of achieving this would be using the onChange event listener — and let the user, parent component, pass as a prop a callback to handle whatever needs to be happening when text is entered. <br>As a small added bonus, this gives control to the user of this component — for example, he can now modify the input as it is being entered, allowing all kinds of filtering options.</p><p>We will implement such an onChange when we modify the parent component, FullName.</p><p>The final TextInput looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d335efc0d970b48466218a82df7d5d30/href">https://medium.com/media/d335efc0d970b48466218a82df7d5d30/href</a></iframe><p>As for the FullName component, it now has additional responsibility — it has to manage not only the value of both TextInput components, but also provide them with callbacks, so they can tell it when to update the corresponding value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6149cda827c74adb49952b87212e1cb0/href">https://medium.com/media/6149cda827c74adb49952b87212e1cb0/href</a></iframe><p>Now the value for each TextInput is maintained by the FullName component, which enables us to easily access the state and render the full name to the screen. When these values are updated — The displayed full name will be updated as well.</p><h3>Conclusions</h3><p>Lets recap some of the advantages of this methodology:</p><ul><li>Composition — now our TextInput component can be easily composed and controlled, which keeps a simple and clear interface, while allowing ‘natural’ data flow in the component hierarchy.</li><li>Greater Flexibility — TextInput can be adjusted to perform additional tasks in its onChange callback, something which was not possible (or atleast, not as simple and fluent) when it managed its own value in the state (and therefore, managed the onChange by itself, internally).</li></ul><p>But of course, it is not perfect. One noticeable downside is the overhead — the TextInput component now is not functional, until it is provided with a callback and wrapped in a parent component. This means there is more work to be done until it is usable.</p><p>Overall, balance is required — planning what data to keep internally and what to receive from the higher order component is key to making good, easily-usable controlled components. Finding this balance is a valuable skill to have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61cb8357bf27" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>