<?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 Çağlayan Yanıkoğlu on Medium]]></title>
        <description><![CDATA[Stories by Çağlayan Yanıkoğlu on Medium]]></description>
        <link>https://medium.com/@caglayanyanikoglu?source=rss-8c3027d5f52a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NITbXARCpH67fI24dmQSGg.jpeg</url>
            <title>Stories by Çağlayan Yanıkoğlu on Medium</title>
            <link>https://medium.com/@caglayanyanikoglu?source=rss-8c3027d5f52a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 14 Nov 2026 12:46:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@caglayanyanikoglu/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[Write Secure Code in JavaScript: Prototype Pollution Part 2]]></title>
            <link>https://blog.stackademic.com/write-secure-code-in-javascript-prototype-pollution-part-2-41071d8683c6?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/41071d8683c6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[secure-coding]]></category>
            <category><![CDATA[defensive-security]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 18:04:33 GMT</pubDate>
            <atom:updated>2024-01-12T02:59:14.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, this will be my first article of the 2024 year :) Today I will continue with Defensive Coding in JavaScript. That’s a goosebump topic. When you understand that, you will understand how OOP works in JavaScript. I hope I can broaden your horizons in this article. If you haven’t read the first article about <a href="https://caglayanyanikoglu.medium.com/write-secure-code-in-javascript-prototype-pollution-part-1-754d38edbe65">Write Secure Code in Javascript</a>, please read it first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mlQUwvVqrU8qcnZU" /><figcaption>The attacker and the coder who try to defend the hacker</figcaption></figure><p>First I want to remind you what was Prototype Pollution. In JavaScript, we use Prototype for OOP. Yes, we use “Class” syntax but under the hood, it transpile to “Prototype”.</p><p>Let me show you a little example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*LASKcv7eGGarPlGrj1tQ7Q.png" /><figcaption>Chrome console tool</figcaption></figure><p>I’ve defined an empty object whose name is obj1. After that, I changed the original toString method of it. But it will not change toString method only for obj1 . It will affect all objects toString method.</p><p>Let’s create another object and check for toString method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H61CKlSNfFCP7Y3skmyP0w.png" /><figcaption>Chrome console tool</figcaption></figure><p>As you can see, even if the obj2 object is newly created, it has our mutated method.</p><p>We’ve talked about how attackers use these tactics to hack our code in a <a href="https://blog.stackademic.com/write-secure-code-in-javascript-prototype-pollution-part-1-754d38edbe65">previous article</a>. So let’s try to write real real-life example.</p><p>I already created a repo and if you want to try these examples, you can reach it from the link below:</p><p><a href="https://github.com/CaglayanYanikoglu/defensive-coding">GitHub - CaglayanYanikoglu/defensive-coding</a></p><p>So in this repo, we have <em>authz.js</em> and <em>attacks</em> folder. I want to give brief information about what authz.js does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38e85d5b306795f49724ec389019af9f/href">https://medium.com/media/38e85d5b306795f49724ec389019af9f/href</a></iframe><p>Let’s dive into the code above. We have one parent function makeAuthzManager . In that function, we have internals object with <em>secrets</em>. But the important function is authorizedFetch . This function takes <strong>requests</strong> as params and adds tokens to headers. It’s a basic function. In the attacks folder, we will try to attack and get to tokens without permission. We have 4 example attacks and I will try to explain attacks and how to defend them.</p><h4>Attack 1:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/970d871274dd172f4e4834f134bcad06/href">https://medium.com/media/970d871274dd172f4e4834f134bcad06/href</a></iframe><p>In the first attack, attacker override reduce function. Now whenever the reduce function is called, attacker’s reduce function will work. In authz.js, just check the line 41:</p><pre>const authorizedRequests = requests.reduce((acc, request, index) =&gt; {</pre><p>As you can see, we use the reduce function for requests, but the attacker has changed it. Our code is vulnerable to these attacks.</p><p><strong>So how we prevent this attack?</strong></p><p>When we call requests.reduce, we are using attacker “reduce” function. Because he/she changed from object proto function. We have to use the clean reduce function.</p><p>To do that, we have to call Array.prototype.reduce function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af8abc3d8542b026bc93a700ff589053/href">https://medium.com/media/af8abc3d8542b026bc93a700ff589053/href</a></iframe><p>Now we removed requests.reduce and we called the reduce function from the original array prototype. So we prevented the first attack. Yayyy!!</p><h4>Attack 2:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/833b72915f4e8d38c9a2d882058ac6e8/href">https://medium.com/media/833b72915f4e8d38c9a2d882058ac6e8/href</a></iframe><p>In the second attack, the attacker change set method for Authorization in the headers object. Now our headers object has been mutated.</p><pre>const { url, headers, method } = request;<br>headers.Authorization = &quot;Bearer &quot; + internals.secrets[index];</pre><p>When we set our secret token in the code above, the attacker reaches our secret token. Because when we set headers.Authorization, it will call attacker’s mutated set function.</p><p><strong>So how we prevent this attack, again?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*m5ZB0NbFeSjQQ2ZkWIeWig.png" /><figcaption>defend code</figcaption></figure><p>Actually, the answer is easy. When we use headers, we will create our own object and set the “Authorization” attribute. The second attack is dismissed too 🎉🎉.</p><h3>Attack 3:</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77bd1c9b0eaba2833a9933680cd7617a/href">https://medium.com/media/77bd1c9b0eaba2833a9933680cd7617a/href</a></iframe><p>This attack is a more sneaky one. The attacker, define to Object.prototype new secrets set method. In our code when we create a new object and try to set secrets, the attacker will receive our props. The attacker created a new stolen variable and put a new variable in the set method.</p><pre>const internals = {};<br><br>internals.guessLimit = 2;<br>internals.secrets = [];<br><br>setSecrets: (secrets) =&gt; {<br>  internals.secrets = secrets;<br>}</pre><p>So if you check our authz.js code above, when we create internals object, it has already mutated the set method for secrets. So when we set secrets, the attacker gets our secrets.</p><h4>What is the defense solution here?</h4><p>When an attacker changes the object prototype, whenever we create a new object, it will be mutated. So we have to create an object without a prototype.</p><pre>  const internals = Object.create(null);</pre><p>If we use Object.create(null) a method with a null parameter, it says: Create a new object without prototype. Because Object.create() method takes the parameter as a new prototype object. If we give null, it won’t be any harmful or mutated prototype. Because there will be no prototype at all. Btw, it’s not a good idea to do that but I will explain in Part 3 :)</p><h3>Attack 4:</h3><p>Let’s assume the attacker is a clever and experienced one. And he/she could think that we will prevent the attack 3 with Object.create() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50026bd56956389f55cf5c92528ab759/href">https://medium.com/media/50026bd56956389f55cf5c92528ab759/href</a></iframe><p>What a wonderful attack, right? The attacker will mutate Object.create() method. In attack 3, we created a new object with Object.create and give null as a parameter right. In this way, we secured the clear prototype. But now, an attacker overrides Object.create method and if the parameter does not exist, it gives an empty object.</p><pre>return create(proto || {}, props);</pre><p>Look at this code above. Take the proto and if not exist, using || to give an empty object. With that move, now attack 3 is enabled again.</p><h4>So how do we defend this crazy talented hacker, right?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*kGaLZIbyq6r-25-3hGiV9Q.png" /><figcaption>authz.js</figcaption></figure><p>We will use create method from directly the original Object. Now if use this Create method, we will ensure, it is not mutated.</p><p>I guess that’s all from this article. I know it’s a very complicated topic. I tried to explain all the details. I would like to talk about this topic very much. I’m also learning :)</p><h3>So, how can we secure our code?</h3><p>I know, you all asking, how can we write all this code on our own? Because there are a lot of vulnerable codes, and we can not prevent all of them.</p><p>I will talk about good solutions in Part 3. I hope you enjoyed while reading this.</p><p>So, I guess that’s all from me for this week. For more advanced JavaScript and React articles, feel free to follow me. You are welcome to write your responses, I always read and answer them. :)</p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq">X</a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41071d8683c6" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/write-secure-code-in-javascript-prototype-pollution-part-2-41071d8683c6">Write Secure Code in JavaScript: Prototype Pollution Part 2</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Write Secure Code in JavaScript: Prototype Pollution Part 1]]></title>
            <link>https://blog.stackademic.com/write-secure-code-in-javascript-prototype-pollution-part-1-754d38edbe65?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/754d38edbe65</guid>
            <category><![CDATA[prototype]]></category>
            <category><![CDATA[defensive-coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[secure-coding]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Sun, 17 Dec 2023 09:57:04 GMT</pubDate>
            <atom:updated>2023-12-18T01:53:36.353Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, this week I want to talk about a really interesting topic. Last month I attended <a href="https://www.nodeconf.eu/">NodeConfEu</a> in Ireland. There were a lot of very good developers and talks. I was impressed and I wanted to write this topic because of one workshop. That was an amazing experience. So these writes will be about Defensive Coding with JavaScript.</p><p>In these articles, I will talk about:</p><ul><li>What is Prototype in JavaScript? (Summary)</li><li>What is Prototype Pollution?</li><li>How do NPM packages turn malicious?</li><li>Examples of attacks &amp; and how to defend them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tqCG0UwUwHRS0M2e.jpeg" /><figcaption>The Hacker</figcaption></figure><h3>What is Prototype in JavaScript?</h3><ul><li>The prototype is a fundamental concept in JavaScript that enables object-oriented programming.</li><li>In JavaScript, every object has a prototype, which serves as a blueprint or template for the object.</li></ul><p>So we are using <strong>Classes</strong> in Javascript for object-oriented programming, right? Actually no. We are using Class syntax but under the hood, JavaScript uses “Prototype” for object-oriented. Classes are not the same as other OOP languages. Yea, it’s a kinda confusing thing but, in JavaScript, everything is coming from an object.</p><p>While JavaScript has introduced the class syntax to make it more familiar and convenient for developers coming from languages with classical inheritance, JavaScript itself uses prototypal inheritance.</p><p>When you try to access a property or method on an object, JavaScript first looks for it in the object itself. If it’s not found, it continues searching in the prototype chain.</p><p>Prototype chain: If a property or method is not found in the object, JavaScript looks up the chain until it finds the corresponding property or method or reaches the end of the chain (null).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*BGu-ybOBusBea2Xr" /><figcaption>JavaScript Prototype Example</figcaption></figure><ul><li>Constructors are used to create objects and define their initial properties.</li><li>Objects created by a constructor have a prototype property that points to the constructor’s prototype object.</li><li>Each function in JavaScript has a special property called prototype.</li><li>The prototype object is used as the prototype for objects created by the constructor.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/0*bCIMfy_-32pAGSth" /><figcaption>Chrome Console: person1 output</figcaption></figure><p>As you can see in the screenshot above, “<strong>person1&quot;</strong> has a name<em> </em>property<em>. </em>But also it has [[Prototype]] object and this object has sayHello function.</p><p>Briefly, in JavaScript, everything is, indeed, centered around objects. I hope what I have explained has shed some light for you. Because this topic is one of the most difficult ones to understand.</p><h3>What is Prototype Pollution?</h3><p>So we talked about Prototype, but what is Prototype Pollution? How can be harmful right?</p><p>JavaScript Prototype Pollution is a security vulnerability that occurs when an attacker manipulates the prototype of an object to introduce malicious properties or methods. I will talk about how they attack it and how to defend against them in Part 2.</p><ul><li>JavaScript allows the modification of an object’s prototype dynamically during runtime.</li><li>Attackers can extend or modify the prototype chain of objects to introduce malicious properties or methods.</li><li>By polluting the prototype, an attacker can affect all instances of objects derived from that prototype.</li><li>This pollution can impact the behavior of functions and methods that rely on the prototype chain for property and method lookup.</li><li>Often, the targets of prototype pollution attacks are libraries and frameworks that dynamically process user input or third-party data. For example: <strong>NPM</strong> packages.</li><li>Attackers exploit vulnerabilities in the parsing and handling of data, leading to pollution of prototype objects.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/0*G4Up5HVb-SsJrEB0" /><figcaption>Example of JavaScript Prototype Pollution</figcaption></figure><p>In the screenshot above, we changed the toString method. After we call toString method, our (attacker) method will override original toString method.</p><p>Prototype pollution can lead to unexpected behavior, data leakage, or unauthorized access. It is a serious security concern, as it can be exploited to compromise the integrity and confidentiality of an application.</p><p>Understanding and mitigating prototype pollution is essential for building secure JavaScript applications, especially when dealing with user input or third-party data. Regular code reviews and adherence to security best practices are crucial in preventing such vulnerabilities.</p><p>In this part, I tried to explain Prototype and Prototype Pollution as much as I could. In the second part, I will talk about how NPM packages turn malicious, examples of attacks, and defend them. Wait for the second part :)</p><p>So, I guess that’s all from me for this week. For more advanced JavaScript and React articles, feel free to follow me. You are welcome to write your responses, I always read and answer them. :)</p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=754d38edbe65" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/write-secure-code-in-javascript-prototype-pollution-part-1-754d38edbe65">Write Secure Code in JavaScript: Prototype Pollution Part 1</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Folder/File Structure Patterns and Tips: Part 2]]></title>
            <link>https://blog.stackademic.com/react-folder-file-structure-patterns-and-tips-part-2-43e0b1f657b4?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/43e0b1f657b4</guid>
            <category><![CDATA[react-best-practices]]></category>
            <category><![CDATA[folders]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-folder-structure]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Mon, 27 Nov 2023 08:27:19 GMT</pubDate>
            <atom:updated>2023-11-29T01:15:50.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone. Welcome to <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a><strong>. </strong>I know, I haven’t written an article for a while and I’m truly sorry for this.<strong> </strong><a href="https://medium.com/@caglayanyanikoglu/react-folder-file-structure-patterns-and-tips-part-1-b8e55bda446f">In the previous article</a>, I talked about React folder structure types. In this second part, I will continue with some folder tips and best practices. In my projects, I always use these methods and I want to share them with you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*0NNtB0VVptdo9DVGtmKQRQ@2x.jpeg" /><figcaption>React Folders</figcaption></figure><p>Usually, I use the “Grouping by file type” pattern in my projects. Because I like to commonize my functions a lot. But as I mentioned in my previous writing, if the project is big, a “Feature-based” pattern would be better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*undPW0KMGLkitctgQs3mIA.png" /></figure><p>In the screenshot above, you can see, I separated files by their type. I will not talk about folder details because I’ve already written in a previous article.</p><h3>What are the tips for folder and file structures in React?</h3><h4>1- ) “shared” folder for common things</h4><p>We have a components folder right, every project has this. In this folder, we hold page components in their name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*Im0CWMJgorrWMVfayYsRiw.png" /></figure><p>For example, you have 3 main pages in your application and you created their pages and their related components. For sure, on every page, there will be specific components for only that page. After you implement these components, you will need “Button”, “Modal”, etc components. These components will be used for multiple pages.</p><p>I always create a “<strong><em>shared</em></strong>” folder to put common components into that folder. You can see common components in the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*XWGPXhVfefyBUCCmXZdmwg.png" /></figure><h4>2-) “index.js” for every component, page, etc…</h4><p>In this pattern, we create “index.js” for every component and page. I love this pattern but what are the benefits?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*S_tj9LKnZR8szP8Xtm75EA.png" /></figure><p>In the application, if we want to import a Button component, we should call it like this:</p><pre>import Button from &quot;./components/shared/Button/Button.js&quot;;</pre><p>It’s very bad looking though. “<strong><em>Button/Button.js”. </em></strong>Let’s create index.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*QHCbHmXquX_vqGx7q7LARQ.png" /><figcaption>index.js</figcaption></figure><p>Basically, we import the Button component and export it from index.js. We don’t have to write “Button/index.js”. Because it already looks for index.js.</p><pre>import Button from &quot;./components/shared/Button&quot;;</pre><p>Now it seems more clear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*qv1AGgq_PC9tC6oSnlCRQw.png" /><figcaption>index.js</figcaption></figure><p>There’s also, an easy and more fancy way to import and export components as seen in the screenshot above :).</p><h4>3-) Import files to one file and export from it</h4><p>For example: In “shared” components, I’ve also created index.js. I import all components from “shared/index.js” like the below screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZSfkCiIjT9f3vU95w2U2Q.png" /><figcaption>shared/index.js</figcaption></figure><blockquote>But why?</blockquote><p>For example, in some components, I need the “Modal”, “Button” and “Dropdown” components. My code will be like this:</p><pre>import Button from &quot;./shared/Button&quot;;<br>import Modal from &quot;./shared/Modal&quot;;<br>import Dropdown from &quot;./shared/Dropdown&quot;;</pre><p>It will cause a lot of lines and complexity will go crazy. When I export all these components from shared/index.js, this code transforms into this:</p><pre>import { Button, Dropdown, Modal } from &quot;./shared&quot;;</pre><p>It’s great, right? Usually in one component, there are a lot of internal and external imports. And if we do not use this method, we can not follow which file comes from where.</p><h4>4-) Get rid of relative path hell</h4><pre>import Modal from &#39;../../../../../../components/Shared/Modal&#39;;</pre><p>Most likely, you called some file with a similar relative path like above. When we want to import a file from somewhere on another main path, we have to go main path then we have to call it. It’s very confusing and bad-looking, right? And if we change the file place, we have to fix all routes.</p><p>Create jsconfig.json in your main folder. Then add this below code.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;baseUrl&quot;: &quot;src&quot;<br>  },<br>  &quot;include&quot;: [<br>    &quot;src&quot;<br>  ],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;,<br>    &quot;build&quot;<br>  ]<br>}</pre><p>After that, you can call files with <strong>absolute path</strong>. For example:</p><pre>import Modal from &#39;components/Shared/Modal&#39;;</pre><h4>5-) Keep components length short</h4><p>Last but not least, I always try to keep my component in maximum line height. This is for me “200” lines for advanced components. I always separate big components into small parts.</p><p>So, I guess that’s all from me for this week. For more advanced JavaScript and React articles, feel free to follow me. You are welcome to write your responses, I always read and answer them. :)</p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43e0b1f657b4" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/react-folder-file-structure-patterns-and-tips-part-2-43e0b1f657b4">React Folder/File Structure Patterns and Tips: Part 2</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Folder/File Structure Patterns and Tips: Part 1]]></title>
            <link>https://blog.stackademic.com/react-folder-file-structure-patterns-and-tips-part-1-b8e55bda446f?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8e55bda446f</guid>
            <category><![CDATA[folder-structure]]></category>
            <category><![CDATA[file-structure]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[react-folder-structure]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 15:34:32 GMT</pubDate>
            <atom:updated>2024-09-24T13:07:05.244Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone, welcome to <strong>#SundayTechMusings </strong>:) First of all, I’m very glad because my articles getting likes and comments. If you have any suggestions for topics, please don’t hesitate to contact me, I would be very happy.</p><p>Today I will talk about my favorite folder structures and tips. When I wrote my first React application, I remember all the time I was looking for how the structure should be. So I know a lot of new programmers are confused about that. I will try to tell the best practices that I learned. I will divide this topic into two parts. The first one will be about folder structures and the second will be about best practices.</p><p><a href="https://differ.blog/differ-ai">Introducing DifferAI</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dd4Mf9g0UPkQE4_I.jpg" /><figcaption>React Folder</figcaption></figure><h4>Before my recommendations, Is there a recommended way to structure React projects?</h4><p><a href="https://legacy.reactjs.org/docs/faq-structure.html">React Documentation</a> answers this question:</p><blockquote>React doesn’t have opinions on how you put files into folders. That said there are a few common approaches popular in the ecosystem you may want to consider.</blockquote><p>Yes, maybe you have already seen that. So what are these popular approaches?</p><ul><li>Grouping by features or routes</li><li>Grouping by file type</li><li>Atomic Design</li></ul><p>We can extend this list but I will explain only three of these.</p><h4>1- Grouping by features or routes (Feature-Based Pattern)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Y_GFFGxt5fpnxwBx7pQJ9w.png" /><figcaption>file structure (Feature-Based Pattern)</figcaption></figure><p>The Feature-Based Pattern is like organizing your code in a React app by grouping similar things together. Each group has all the stuff needed for a specific job in the app, like building blocks, tools, and other necessary things.</p><p>Imagine these groups as separate boxes that you can add, remove, or change without messing up the rest of the app. This way, you can also use the same stuff in different parts of the app to save time and effort.</p><p>I will create a simple folder structure with feature-based.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZ3QUrq8cEt1PSmSZ6COaw.png" /><figcaption>file structure</figcaption></figure><p>In the above screenshot, I’ve created four main folders.</p><ul><li><strong>src/app</strong>: It’s a main application folder.</li><li><strong>src/features</strong>: We hold all features in that folder. Each feature has its own components, services, tests, .etc in this folder.</li><li><strong>src/shared</strong>: In the application, we will have a lot of common components, services, etc. We will keep these common files in the shared folder.</li><li><strong>public</strong>:<strong> </strong>This is for static files like images, icons, etc.</li></ul><p>If you have a big application, or if you think the application will grow too much, you can consider using a feature-based folder structure. In this pattern, we can separate our features and it will be a very clear folder structure.</p><h4>Advantages</h4><p>The best thing about this setup is that it’s really easy to add or change the code. Because the code is divided into different parts (features), you can easily add new parts or improve the ones already there. This split also makes the codebase simpler, as some files can be considered private, which helps you understand the code better.</p><p>Another good thing is that the code outside the features section is usually straightforward to grasp. Most of the important stuff is neatly packed inside the features section. This makes it simpler to understand and work with the code.</p><h4>Disadvantages</h4><p>The main downside of this setup is that it can get a bit complicated. If you’re working on a big application, this added complexity isn’t a big problem, because it actually makes the whole project less complicated. However, if your app is small and only has a few parts/pages, this system might end up being too much. Many of the folders might not even be used, or they might only have a few files. Because of this, I suggest using this folder structure mainly for bigger and more advanced projects that really need this extra separation.</p><h4>2- Grouping by file type</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*erTu-rpY4bKhxor999aOwA.png" /><figcaption>react folder structure</figcaption></figure><p>This is my favorite folder structure for small-medium-size projects. We create folders for each type in the src folder. Every folder could have a <strong>common folder</strong> that contains shared utilities.</p><p>In this pattern, we avoid too many nestings, unlike feature-based patterns. But if we have a lot of features in the project it can be a complex structure.</p><h4>Advantages</h4><ul><li><strong>Easy to Find:</strong> You can quickly locate files because they’re organized by their purpose.</li><li><strong>Less Messy:</strong> When your app gets bigger, this keeps things tidy and helps prevent confusion.</li><li><strong>Readability:</strong> Others can understand your code better when it’s organized logically.</li><li><strong>Reusable Code:</strong> You can easily reuse common pieces of code in different parts of your app. Which is my reason for using this pattern.</li></ul><h4>Disadvantages</h4><ul><li><strong>Lots of Folders:</strong> It can get overwhelming with many folders, making it harder to find things.</li><li><strong>Learning Curve:</strong> New team members might take time to learn where everything is.</li><li><strong>More Updates:</strong> Changing file locations or names can cause problems with how files are connected.</li><li><strong>Some Complexity:</strong> Sometimes, files might belong to more than one category, which can be tricky.</li></ul><h4>3- Atomic Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*EJHBAbJLu8W5wt0VQ0f-QQ.png" /><figcaption>Atomic design folder structure</figcaption></figure><p>I believe you heard about Atomic Design in your life at some point. Atomic Design is a methodology for creating design systems and organizing code in a way that promotes reusability, scalability, and maintainability. It’s a hierarchical approach that breaks down user interfaces into smaller, reusable components.</p><p>In Atomic Design, components are organized into five distinct levels based on their complexity and reusability. These levels are:</p><ol><li><strong>Atoms:</strong> Atoms are the smallest building blocks of your UI. They represent individual HTML elements like buttons, input fields, labels, and more. Atoms are highly reusable and have minimal dependencies.</li><li><strong>Molecules:</strong> Molecules are combinations of atoms. They represent simple UI components that have a specific functionality. For example, a search bar might be a molecule composed of an input atom and a button atom.</li><li><strong>Organisms:</strong> Organisms are more complex UI components that combine multiple molecules and/or atoms to form a functional unit. An example could be a header component that includes a logo (atom), navigation (molecule), and a search bar (molecule).</li><li><strong>Templates: </strong>Templates are higher-level structures that provide a layout for arranging organisms and molecules on a page. They define the overall structure of a page without containing the actual content.</li><li><strong>Pages:</strong> Pages are instances where you populate templates with actual content and data. They represent the final product that users interact with.</li></ol><h3>Conclusion</h3><p>My advice is to choose your familiar file structure. Just try to avoid too many nestings. If you have deep directory nesting, the project can be bad DX(Developer Experience).</p><p>React says don’t overthink it. <em>Don’t spend more than five minutes</em> to choose file structure. This is React documentation’s advice. As the project grows larger, you can mix these patterns and that would be not a problem.</p><p><strong>For second part of this article:</strong></p><p><a href="https://blog.stackademic.com/react-folder-file-structure-patterns-and-tips-part-2-43e0b1f657b4">React Folder/File Structure Patterns and Tips: Part 2</a></p><p>So, I guess that’s all from me for this week. For more advanced JavaScript and React articles, feel free to follow me. :)</p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><blockquote><em>👉 </em><strong>Also learn about these 11 useful React tips and tricks to boost your app’s performance:</strong></blockquote><p><a href="https://differ.blog/inplainenglish/11-useful-react-js-hack-every-developer-should-know-8debac">11 Useful React.js Hack Every Developer Should Know</a></p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a> | <a href="https://cofeed.app/"><strong>CoFeed</strong></a> | <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8e55bda446f" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/react-folder-file-structure-patterns-and-tips-part-1-b8e55bda446f">React Folder/File Structure Patterns and Tips: Part 1</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most Senior React Devs Don’t Know How To Fix This / Keys in React]]></title>
            <link>https://medium.com/jotform-tech/most-senior-react-devs-dont-know-how-to-fix-this-keys-in-react-848b2408a183?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/848b2408a183</guid>
            <category><![CDATA[react-key]]></category>
            <category><![CDATA[advanced-react]]></category>
            <category><![CDATA[seniors]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mounting]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 16:03:28 GMT</pubDate>
            <atom:updated>2023-09-04T06:53:13.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Most Senior React Devs Don’t Know How To Fix This</h3><p>Hello everyone. Welcome to <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a><strong>. </strong>Today, I will write about a really important aspect of React that will broaden your understanding of React Mount and the <strong>key</strong> property. Last week, while working on a project, I encountered a significant issue in React. The problem was small, but I couldn’t figure out how to fix it, and it was quite frustrating. However, after investigating the issue and trying different approaches, I discovered an incredible solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*933bq1q0vBaAeyXP" /><figcaption>keys</figcaption></figure><h4>What was the issue?</h4><p>Here is some simple code to illustrate the problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67246a3fbd5477f22fa7ae676b9c35fb/href">https://medium.com/media/67246a3fbd5477f22fa7ae676b9c35fb/href</a></iframe><p>Imagine we have an app with an Input component that holds a state value for the input type. When we click a button, the input type will toggle between “name” and “email.”</p><p>Here’s the code for the Input component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b3616a9df44dd5031a5c653062b0938/href">https://medium.com/media/3b3616a9df44dd5031a5c653062b0938/href</a></iframe><p>Take a look at the above code and try to identify what’s wrong. As you can see, there are no mistakes in these simple components.</p><p>Let’s demonstrate the problem with a GIF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*iGY-sJLZrTdPgYyKOhqg3Q.gif" /><figcaption>basic app</figcaption></figure><p>As you can see, when we click the button to change the type, although the Input component changes, the input value remains the same. This is not the behavior we desire.</p><h4>So, why does React act like that?</h4><p>The reason is that in the code, we have the same Input component in the same place. When we change the type, React still considers it as the same component, which is true to some extent.</p><p>React renders the component, but it doesn’t remount it. React does this to avoid unnecessary remounting. We need to inform React that it’s a different component.</p><h4>What are the solutions?</h4><p>As mentioned above, we need to remount this component and notify React that it’s an entirely different component.</p><p>The first solution is to change the order and placement of the components.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef5b291a5f92b1b2f0ffb8d258a09508/href">https://medium.com/media/ef5b291a5f92b1b2f0ffb8d258a09508/href</a></iframe><p>Now, if you review the updated code above, you’ll notice that we have div and main wrappers. Therefore, React will recognize them as different components and remount them. The problem is resolved.</p><p>Cool, right? However, we had to introduce additional HTML elements, which is not an ideal solution. It could potentially break styles, and it adds unnecessary complexity to the code.</p><p>The second solution is amazing: adding a <strong>key</strong> prop to the Input component. I can already hear some of you saying, “What the heck?” 😄</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4cc4fc8150eaefeb184f3a8b0dbb038/href">https://medium.com/media/e4cc4fc8150eaefeb184f3a8b0dbb038/href</a></iframe><p>By simply adding a key prop to the Input component, we tell React that it’s a new and distinct component. We are all familiar with adding keys to list elements, right? In a similar way, by assigning keys to these components, React can efficiently identify and manage their state.</p><p>In some cases, components may be conditionally rendered or created dynamically. By providing a key to these components, you can help React differentiate between different instances of the same component and optimize re-rendering. This can be particularly useful when you want to preserve the state of specific components across re-renders.</p><p>That’s all from me for this week. For more advanced JavaScript and React articles, feel free to follow me. :)</p><p>If you find this content helpful and would like to show your support, you can buy me a beer🍺😊<br><a href="https://www.buymeacoffee.com/caglayanDev">Buy Beer🍺</a></p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=848b2408a183" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/most-senior-react-devs-dont-know-how-to-fix-this-keys-in-react-848b2408a183">Most Senior React Devs Don’t Know How To Fix This / Keys in React</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Journey to the Center of JavaScript, Episode 5: Async Js & Event Loop]]></title>
            <link>https://medium.com/jotform-tech/a-journey-to-the-center-of-javascript-episode-5-async-js-event-loop-92b7023143f1?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/92b7023143f1</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[sundaytechmusings]]></category>
            <category><![CDATA[event-loop-in-js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Tue, 16 May 2023 18:03:31 GMT</pubDate>
            <atom:updated>2023-08-14T13:51:05.931Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Journey to the Center of JavaScript, Part 5: Async JS and Event Loop</h3><p>Hello everyone. In this week&#39;s <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a>,<strong> </strong>I will talk about my favorite JavaScript topic: async operations. I’m very excited about it actually :). This article will be the fifth installment of the “A Journey to the Center of JavaScript” series 🚀.</p><p>You can catch up on the previous four articles here:</p><ul><li><a href="https://tech.jotform.com/a-journey-to-the-center-of-javascript-168936c8c20c">A Journey to the Center of JavaScript</a></li><li><a href="https://tech.jotform.com/a-journey-to-the-center-of-javascript-episode-2-hoisting-aba8f3f6c182">A Journey to the Center of JavaScript — Episode 2: Hoisting</a></li><li><a href="https://tech.jotform.com/a-journey-to-the-center-of-javascript-episode-3-closure-e96054182ee2">A Journey to the Center of JavaScript — Episode 3: Closure</a></li><li><a href="https://caglayanyanikoglu.medium.com/a-journey-to-the-center-of-javascript-part-4-iife-e39ffa60a74c">A Journey to the Center of JavaScript, Part 4: IIFE</a></li></ul><p>I want to start with a little advice. When most junior developers try to learn web programming they make the same mistakes. They focus on learning React, Vue, or some other popular libraries even if they don’t know the basic cores concepts of JavaScript. I always advise my students to learn the logic of the code. Otherwise, they can just take some code parts from websites like <strong>Stackoverflow</strong> and if the code works they don’t search anymore.</p><p>Today I will talk about the <strong>logic of JavaScript</strong> and how JavaScript handles <strong>async operations</strong> with a <strong>single thread</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MNmSXEtKvm06DtP_.gif" /></figure><h4>What is async?</h4><p>I want to give a real-life example to explain async operations. Let’s say, you go to Starbucks to get a coffee. After you order, the next person doesn’t have to wait for your coffee to be ready to order theirs. While one barista is getting your coffee ready, another is still taking the orders. This is the basic description of async operations: Doing multiple jobs at the same time.</p><p>I’ve mentioned before that JavaScript is a single-threaded language, meaning it can do one job at one time. So how does JavaScript handle multiple tasks in one thread? Because it often needs to perform tasks that take time, such as making network requests, reading from a file, or waiting for user input.</p><p>Before answering that, I would like to give async examples in JavaScript.</p><h4>What are the async processes in JavaScript?</h4><ul><li>API calls</li><li>Promises</li><li>SetTimeout function</li><li>DOM manipulation</li><li>Reading from file</li></ul><p>In the above operations, JavaScript does not wait for an answer. You have to tell JavaScript that it’s an async process. You can do that with the promises or async await keywords.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbe01bdbb80fb14b52581fc46d04e158/href">https://medium.com/media/cbe01bdbb80fb14b52581fc46d04e158/href</a></iframe><p>If you execute the code below you will see console output in this order:</p><ul><li>first</li><li>third</li><li>second</li></ul><p>That’s because setTimeout function will execute this code after a <strong>minimum of two </strong>seconds. I said minimum because it will wait for the other functions to execute. That was easy. What about if we put a 0 second delay?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d5301a78bc0e4c6be5a4e3f7bc7bfb5/href">https://medium.com/media/3d5301a78bc0e4c6be5a4e3f7bc7bfb5/href</a></iframe><p>What will be the output?</p><p>You may think a 0 second delay won’t change anything and the console output would be “first, second, third.” Or some of you may think it depends on execution time and it changes randomly each time.</p><p>The right answer is actually always the same as above.</p><ul><li>first</li><li>third</li><li>second</li></ul><p>At this point, we must understand how the JavaScript engine works.</p><h3>Event loop</h3><p>Some people confuse the event loop with events in HTML. But actually, an event loop is a different fundamental concept. Basically, an <strong>event loop</strong> helps JavaScript handle these tasks efficiently.</p><p>The event loop works by constantly checking two main sources: the call stack and the event queue. The call stack keeps track of the functions being executed at any given moment, while the event queue holds tasks or events that are waiting to be processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vpBHtgFAjBqNitrZ.png" /><figcaption>The call stack in JavaScript</figcaption></figure><p>When the function is called, it is stored in the call stack. After the function is executed, it is removed from the call stack. Here’s a simplified step-by-step overview of how the event loop works:</p><ol><li>The JavaScript engine starts executing code from top to bottom, adding function calls to the call stack as it encounters them.</li><li>If a function encounters an asynchronous task (e.g., a network request or a timer), it delegates the task to the browser’s Web APIs or other runtime environments, which handle the task in the background.</li><li>While the task is being processed, the JavaScript engine continues executing the remaining code without waiting for the task to complete. This is the non-blocking nature of JavaScript.</li><li>Once the task is completed, it’s placed in the event queue as an event.</li><li>The event loop continuously checks if the call stack is empty <strong>and if the event queue has any pending events.</strong> If the call stack is empty and <strong>there are events in the queue</strong>, the event loop takes the first event and pushes its associated callback function onto the call stack.</li><li>The callback function is then executed, and if it contains any further asynchronous tasks, the process is repeated from step 2.</li><li>This cycle continues indefinitely, with the event loop constantly checking the call stack and event queue and moving tasks from the event queue to the call stack as they become available.</li></ol><p>You can check this image and this GIF to understand how event loop works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*98D4XwLPH750Hh_V.gif" /><figcaption>Event loop image</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*GD6T8X-bVe8mODy5.gif" /><figcaption>Event loop GIF</figcaption></figure><p>In the above GIF, you can see how JavaScript handles all tasks with a single thread.</p><p>By using this mechanism, the event loop allows JavaScript to handle asynchronous operations efficiently while ensuring that the user interface remains responsive. It prevents blocking or freezing of the user interface by ensuring that long-running tasks are executed in the background and their results are processed when the call stack is empty.</p><p>It’s important to note that JavaScript itself doesn’t directly control the event loop. The event loop implementation varies depending on the runtime environment in which JavaScript is running, such as web browsers or Node.js.</p><h4>To sum up</h4><p>JavaScript handles all these async tasks with an event loop. As I mentioned above if you know the logic behind the code, you can build much better, more optimized structures.</p><p>That’s it for this week&#39;s <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a><strong>.</strong> If you want to get more content on advanced JavaScript and React, you can follow me and subscribe to get emails.</p><p>If you find this content helpful and would like to show your support, you can buy me a beer🍺😊<br><a href="https://www.buymeacoffee.com/caglayanDev">Buy Beer🍺</a></p><p><a href="https://github.com/CaglayanYanikoglu/">CaglayanYanikoglu - Overview</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92b7023143f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/a-journey-to-the-center-of-javascript-episode-5-async-js-event-loop-92b7023143f1">A Journey to the Center of JavaScript, Episode 5: Async Js &amp; Event Loop</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Journey to the Center of JavaScript, Part 4: IIFE]]></title>
            <link>https://medium.com/jotform-tech/a-journey-to-the-center-of-javascript-part-4-iife-e39ffa60a74c?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e39ffa60a74c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[immediately-invoked]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[iife]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 14:47:14 GMT</pubDate>
            <atom:updated>2023-07-07T18:14:29.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, everyone. In the fourth installment of the “Journey to the Center of JavaScript” series on advanced JS, we continue with the topic of immediately invoked function expression (IIFE). I will try to keep it short :).</p><p>Check out the previous three articles in this series below.</p><ul><li><a href="https://tech.jotform.com/a-journey-to-the-center-of-javascript-168936c8c20c">A Journey to the Center of JavaScript</a></li><li><a href="https://tech.jotform.com/a-journey-to-the-center-of-javascript-episode-2-hoisting-aba8f3f6c182">A Journey to the Center of JavaScript — Episode 2: Hoisting</a></li><li><a href="https://caglayanyanikoglu.medium.com/a-journey-to-the-center-of-javascript-episode-3-closure-e96054182ee2">A Journey to the Center of JavaScript — Episode 3: Closure</a></li></ul><h4><strong>IIFE (immediately invoked function expression)</strong></h4><p>IIFE is a function that is defined and executed immediately in the same line of code. The main purpose of an IIFE is to create new scope in your code, which can help to avoid naming conflicts and keep your code more organized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2VwSpEvSXR6RL400.png" /><figcaption>IIFE example</figcaption></figure><p>In the example above, we define an anonymous function and immediately invoke it with parentheses at the end. The function will execute right away without calling from anywhere.</p><h4><strong>Why should we use IIFE, and what are the benefits</strong>?</h4><p>One of the benefits of using an IIFE is that it can help to prevent global namespace pollution. In other words, we cannot reach function variables or functions outside IIFE. This can be crucial in some scenarios, like working with large codebases with many developers.</p><p>Also, it reduces the risk of naming conflicts and can make it easier to reason about your code.</p><h4>A real-world example</h4><p>Let’s say you’re developing a web application with your team. That application has a filter feature in which users can filter a large dataset by various names, dates, categories, etc.</p><p>To avoid polluting the global namespace with the filter-related variables and functions, you can wrap the entire filter logic in an IIFE. IIFE creates a new scope for the filter-related code, which keeps it separate from other parts of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-IebnRXIMlTR0Bao.jpg" /><figcaption>Linus Torvalds’ famous words</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b713b215b556a677098c08352bb87e7/href">https://medium.com/media/3b713b215b556a677098c08352bb87e7/href</a></iframe><p>In this above example, the data variable and three filter functions are defined inside the IIFE. As I mentioned, these variables and functions in IIFE are not accessible from outside the IIFE, which helps to prevent naming conflicts with other parts of the application.</p><h4>To sum up</h4><p>Using an IIFE helps to keep the filter-related code organized and separate from other parts of the application, which can make it easier to maintain and debug.</p><p>Watch for more articles about advanced JavaScript and React in <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a>. And for more content like this, you can follow me on <a href="https://github.com/CaglayanYanikoglu">GitHub</a>, <a href="https://twitter.com/caglayanDev">Twitter</a>, or <a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">LinkedIn</a> to catch more on these topics.</p><p>See you for the next <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a><strong>.</strong></p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p>If you find this content helpful and would like to show your support, you can buy me a beer🍺😊<br><a href="https://www.buymeacoffee.com/caglayanDev">Buy Beer🍺</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e39ffa60a74c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/a-journey-to-the-center-of-javascript-part-4-iife-e39ffa60a74c">A Journey to the Center of JavaScript, Part 4: IIFE</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Journey to the Center of JavaScript — Episode 3: Closure]]></title>
            <link>https://medium.com/jotform-tech/a-journey-to-the-center-of-javascript-episode-3-closure-e96054182ee2?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e96054182ee2</guid>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[closure]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[closures-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 17:23:02 GMT</pubDate>
            <atom:updated>2023-07-07T18:14:46.358Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Journey to the Center of JavaScript, Part 3: Closures</h3><p>Hello, everyone. In the third installment of <strong>A Journey to the Center of JavaScript</strong>,<strong> </strong>we continue with closures. We started with <strong>primitive and reference value types</strong> in <a href="https://medium.com/@caglayanyanikoglu/a-journey-to-the-center-of-javascript-168936c8c20c">the first article</a>. My second article was about<strong> </strong><a href="https://medium.com/@caglayanyanikoglu/a-journey-to-the-center-of-javascript-episode-2-hoisting-aba8f3f6c182"><strong>hoisting</strong></a>. You can start with these articles if you haven’t read them. I hope you enjoy this week’s <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a><strong> </strong>:).</p><p>The third post in this series is about <strong>closures. </strong>Today I will give an example from one of my daily routines at <a href="https://medium.com/u/d01266a9fdd5?source=post_page-----e96054182ee2--------------------------------">Jotform</a> because it’s very instructive.</p><p>But before we talk about closures, I want to give brief information about <strong>lexical scoping</strong>.</p><h4>Lexical Scoping</h4><p>Lexical scoping is a fundamental concept in JavaScript that helps determine how variables and functions are accessed in different parts of your code. In simple terms, lexical scoping refers to the way JavaScript code defines the scope of a variable or function based on its location within the code’s block structure.</p><p>To understand lexical scoping, it’s important to first understand what a scope is. In JavaScript, a scope is a set of variables, functions, and objects that are accessible in a particular part of the code. A scope can be either global or local. Global scope refers to variables or functions that are accessible throughout your entire codebase, while local scope refers to variables or functions that are accessible only within a particular block of code. This is an important part to understand the difference between <em>var and </em><em>const, let.</em></p><p>Now, let’s look at how lexical scoping works. In JavaScript, when a function is defined, it captures the scope in which it is defined. This means that the function can access any variables or functions that were defined in the same scope, as well as any variables or functions defined in any outer scopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hW5dE0NW0ra8nWAGpia4vg.png" /><figcaption>Scope example</figcaption></figure><p>In the above example, the console output will be “Caglayan.” As I mentioned, you can reach outer variables from inner functions.</p><h4>Scoping with let and const</h4><p>Mdn Says:</p><blockquote>Traditionally (before ES6), JavaScript only had two kinds of scopes: <em>function scope</em> and <em>global scope</em>. Variables declared with var are either function-scoped or global-scoped, depending on whether they are declared within a function or outside a function. This can be tricky, because blocks with curly braces do not create scopes.</blockquote><p>My sincere advice is not to use <em>var </em>as I mentioned in my post on <a href="https://caglayanyanikoglu.medium.com/a-journey-to-the-center-of-javascript-episode-2-hoisting-aba8f3f6c182#:~:text=reduces%20the%20risk-,of,-error.">hoisting</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53e73e9775f1079ee0b0349f0242939c/href">https://medium.com/media/53e73e9775f1079ee0b0349f0242939c/href</a></iframe><p>In the above code, you may think that it will throw an error. But it won’t. It will give a <em>name</em> value depending on the if condition. Because unlike <em>const and </em><em>let ,</em><em>var</em>statements create global variables.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cf59334f32c2af71244d05be5838d8b/href">https://medium.com/media/5cf59334f32c2af71244d05be5838d8b/href</a></iframe><p>This time, it will throw an error because the let variable is declared in function scopes. We cannot reach that from outer scopes.</p><h3>What is a closure?</h3><p>A closure is a feature in JavaScript that allows a function to access variables and parameters from its outer (enclosing) function, even after the outer function has <strong>returned</strong>. In other words, a closure is a function that has access to variables and parameters from its parent function, even after the parent function has completed execution. If you are familiar with <strong>event loop</strong> in JavaScript, after function execution, the function is removed from the call stack. (If you’re not familiar with this topic, it’s OK. I will cover it in a future article.)</p><p>To create a closure in JavaScript, you need to define a function inside another function. The inner function has access to variables in the outer function’s scope, even after the outer function has returned.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c031d5a89bee7fc86fefaa6545e95f9/href">https://medium.com/media/6c031d5a89bee7fc86fefaa6545e95f9/href</a></iframe><p>In this example, outerFunction takes a parameter x and returns innerFunction. innerFunction takes a parameter y and returns the sum of x and y.</p><p>When we call outerFunction(5), it returns innerFunction, which we store in the addFive variable. When we then call addFive(3), it adds 3 to the x value passed to outerFunction, which is 5, and returns the sum 8.</p><p>The key point to understand here is that innerFunction has access to the x parameter of outerFunction, even though outerFunction has completed execution and x is no longer in scope.</p><p>Closures are useful in many scenarios, such as in creating private variables and methods in object-oriented programming, or in managing state in functional programming. However, they can also cause memory leaks if not used carefully, as the outer function’s variables and parameters are not garbage-collected even after the function has completed execution.</p><h4>A real-life example of a closure</h4><p>Now that we’ve defined closure, I want to share the example of one that I mentioned in the beginning.</p><p>If you worked with backend search in your application, you know the <strong>debounce</strong> function. If you don’t, take a look at my <a href="https://tech.jotform.com/react-performance-improvements-356f81b1904f#:~:text=7.%20Throttling%20and%20Debouncing%20Events">debounce</a> article.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd5cf1be0e8037f51f626db16d0fffa8/href">https://medium.com/media/fd5cf1be0e8037f51f626db16d0fffa8/href</a></iframe><p>In debounce function we should keep the timeout variable. We should keep the timeout variable in the outer function because every time we call this function, it must stay the same. So this is why we use <strong>closures</strong>. If we do not use closures, every time we create a new setTimeout function, it won’t work correctly.</p><h4>To sum up</h4><p>The <strong>closure</strong> is very useful. It’s also covered in many interviews for front-end positions, so you should understand the logic of it.</p><p>This was the third article of my “Journey to the Center of JavaScript” series. Follow me for more posts on advanced JavaScript and React. See you in the next <a href="https://www.linkedin.com/feed/hashtag/?keywords=sundaytechmusings&amp;highlightedUpdateUrns=urn%3Ali%3Aactivity%3A7033126066730774529"><strong>#SundayTechMusings</strong></a><strong>.</strong></p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p>If you find this content helpful and would like to show your support, you can buy me a beer🍺😊<br><a href="https://www.buymeacoffee.com/caglayanDev">Buy Beer🍺</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e96054182ee2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/a-journey-to-the-center-of-javascript-episode-3-closure-e96054182ee2">A Journey to the Center of JavaScript — Episode 3: Closure</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding “return null” vs “return false” in React]]></title>
            <link>https://medium.com/jotform-tech/return-null-vs-return-false-in-react-826d8abcc429?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/826d8abcc429</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[advanced-react]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-performance]]></category>
            <category><![CDATA[web-performance]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 20:27:08 GMT</pubDate>
            <atom:updated>2023-08-24T07:47:24.076Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone. This week in <strong>#SundayTechMusings, </strong>I will try to explain the difference between “return null” and “return false” in React.</p><p>This topic is actually related to performance. For some background on techniques for optimizing performance, check out my <a href="https://tech.jotform.com/react-performance-improvements-356f81b1904f">Performance Optimization Techniques</a> on this topic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yaIvvEwXKIvFQ_8g" /><figcaption>React</figcaption></figure><p>A lot of people think “return null” and “return false” are the same. While they’re very similar, there are some differences related to how React works.</p><p>When developing with React, it’s common to use conditional rendering to display different components based on certain conditions. In some cases, you may want to explicitly indicate that a component should not render. This is where null and false come in. While both of these values prevent the rendering of a component, there are important differences between them.</p><h4>Returning null</h4><p>When a component returns null, it tells React not to render anything in the DOM for that component. This can be useful when you want to conditionally render a component based on a certain state, but don&#39;t want anything to be displayed when that state is not met. For example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e981169b9d964c12feb08d0033bdeef/href">https://medium.com/media/9e981169b9d964c12feb08d0033bdeef/href</a></iframe><p>In the above example, if the name prop is not provided, the component returns null, which prevents the &lt;h1&gt; element from being rendered. If the name prop is provided, the component renders the &lt;h1&gt; element with the greeting. This is the classic way of doing this.</p><h4>Returning false</h4><p>When a component returns false, it tells React not to render anything in the DOM for that component, just like null. However, there is an important difference: returning false also prevents the component from updating in the future. This is because React interprets false as a signal to “unmount” the component, which means removing it from the DOM entirely.</p><p>Here’s an example of a component that returns false:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c06b8ee85f74df7a139bf3a2ff56fa6/href">https://medium.com/media/7c06b8ee85f74df7a139bf3a2ff56fa6/href</a></iframe><p>In this example, if the onClick prop is not provided, the component returns false, which prevents the &lt;button&gt; element from being rendered. If the onClick prop is provided, the component renders the &lt;button&gt; element with the specified click handler.</p><p>It’s important to note that returning false can have unintended consequences, such as preventing the component from updating when it should. For this reason, it’s generally safer to use null when you want to prevent rendering without affecting future updates.</p><p><strong>Returning false</strong> from a component’s render method is only useful when the component doesn’t have any side effects, such as updating state or triggering API requests. If a component has side effects and returns false, those side effects will still happen, which can lead to unexpected behavior.</p><p><a href="https://github.com/facebook/react/blob/main/packages/react/src/ReactElementValidator.js#L347-L385">react/ReactElementValidator.js at main · facebook/react</a></p><p>If you check the above code in the React library, you will see a “null” check. For a better understanding of how React works, check out this code.</p><h4>To sum up</h4><p>In summary, returning null and returning false both prevent a component from rendering anything in the DOM, but there are important differences between them. null is a simple way to conditionally render a component without affecting future updates, while false signals to React to unmount the component and can cause unintended consequences. It’s important to choose the right option for your specific use case.</p><p>For more on advanced React and JavaScript, check out my other posts and subscribe to email updates.</p><p>If you find this content helpful and would like to show your support, you can buy me a beer🍺😊<br><a href="https://www.buymeacoffee.com/caglayanDev">Buy Beer🍺</a></p><p>See you next week at <strong>#SundayTechMusings</strong></p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p><a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">Linkedin</a></p><p><a href="https://twitter.com/caglayanDev">Twitter</a> (TR)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=826d8abcc429" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/return-null-vs-return-false-in-react-826d8abcc429">Understanding “return null” vs “return false” in React</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use the setState callback in React wisely]]></title>
            <link>https://medium.com/jotform-tech/use-setstate-callback-wisely-96a9f4a2d0ed?source=rss-8c3027d5f52a------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a9f4a2d0ed</guid>
            <category><![CDATA[state]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[setstate]]></category>
            <category><![CDATA[async]]></category>
            <dc:creator><![CDATA[Çağlayan Yanıkoğlu]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 11:00:55 GMT</pubDate>
            <atom:updated>2023-08-04T08:19:50.767Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, everyone. This week in <strong>#SundayTechMusings, </strong>I will try to explain how to use <strong>setState</strong> wisely in React.</p><p>In React, we usually hold our data in states. When data changes, React will render the new data on the screen for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/0*L2kjsVOalOtZFcJp.jpeg" /><figcaption>React and State</figcaption></figure><p>So the state is like a kind of storage. setState or useState are functions to change state values. Let’s look at the useState hook using the function component.</p><p>useState is one of the most-used hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kaiCKRl8cmtrvjdlMuVQMg.png" /></figure><p>In the above code, I wrote one basic component. We have count value that we store in the state. The useState function’s parameter is the default state value. In our code count value will be <strong>0</strong> at the beginning.</p><p>Every time we click the button, we increase the count value by 1. So setCount function arg is the new state value for the count. This code works without any problem. So let’s change setCount a little bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdVZLwufB8qWYdjFX2-CWw.png" /></figure><p>The above code works the same as before. So what’s the difference between setCount functions? This time, we’ve used the callback function in setCount.</p><h4>Why do we need a callback in setState?</h4><p>In the case of the function argument, it can be useful to use a callback function with setState to ensure that the state update is performed correctly. This is because setState may update the state <strong>asynchronously</strong>, and if you need to perform some action that depends on the state being updated immediately after calling setState, you cannot rely on the state to have been updated yet.</p><p>Here’s a simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/702e9c30055dd6bfc8696098c4f2564e/href">https://medium.com/media/702e9c30055dd6bfc8696098c4f2564e/href</a></iframe><p>In the above code, we update the <strong>count state</strong> asynchronously in increaseCountAsync. If we don’t use a callback in setState (in our case setCount), it will give unreliable results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*lAKSPVqDUKJDzSHz5Y4Pfg.gif" /></figure><p>As you can see in the above GIF, when the increaseCountAsync function was called, the count value was 2. After clicking several times on the “Increase Count” button, the count value is 11. But when increaseCountAsync executed the setCount function, the count value was still 2 which is wrong. The new value should be 12 but it is 3.</p><p>In <strong>asynchronous</strong> situations like this, we should use a callback in our setState function to ensure the <strong>state</strong> value is updated.</p><p>So let’s fix the problem.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b41af43ba1ee940a506db2972116182/href">https://medium.com/media/1b41af43ba1ee940a506db2972116182/href</a></iframe><p>Bu adding the callback function in lines 7 and 12, we ensure the state value is updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*f8DHu3fHWJPFnX7b2yHWeA.gif" /></figure><p>As you can see we fixed the problem. So it’s crucial to use a callback when you update the state <strong>asynchronously.</strong></p><p>That’s it for this week’s <strong>#SundayTechMusings</strong> is over :) See you next week.</p><p>Happy <strong>hacking</strong>! :)</p><p>If you find this content helpful and would like to show your support, you can buy me a beer🍺😊<br><a href="https://www.buymeacoffee.com/caglayanDev">Buy Beer🍺</a></p><p><a href="https://github.com/CaglayanYanikoglu">CaglayanYanikoglu - Overview</a></p><p>My Twitter: <a href="https://twitter.com/caglayanDev">https://twitter.com/caglayanDev</a><br>My Linkedin: <a href="https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/">https://www.linkedin.com/in/%C3%A7a%C4%9Flayan-yan%C4%B1ko%C4%9Flu-a6b42b13b/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a9f4a2d0ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jotform-tech/use-setstate-callback-wisely-96a9f4a2d0ed">Use the setState callback in React wisely</a> was originally published in <a href="https://medium.com/jotform-tech">Jotform Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>