<?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 Faiz Noeris on Medium]]></title>
        <description><![CDATA[Stories by Faiz Noeris on Medium]]></description>
        <link>https://medium.com/@m.faiznoeris?source=rss-f3df4fcd5346------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*BKvbx-AK2He2DlwMMTYbDA@2x.jpeg</url>
            <title>Stories by Faiz Noeris on Medium</title>
            <link>https://medium.com/@m.faiznoeris?source=rss-f3df4fcd5346------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 07:34:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m.faiznoeris/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[Enhancing Performance in Next.js Applications]]></title>
            <link>https://javascript.plainenglish.io/enhancing-performance-in-next-js-applications-f4dc82f1fa87?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4dc82f1fa87</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[enhancement]]></category>
            <category><![CDATA[performance-management]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 07:10:37 GMT</pubDate>
            <atom:updated>2025-01-13T08:03:01.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fruQMa4n8xMg0B3Z" /><figcaption>Photo by <a href="https://unsplash.com/@marcsm?utm_source=medium&amp;utm_medium=referral">Marc Sendra Martorell</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Next.js is a powerful framework for building fast and scalable web applications. To maximize its potential, developers must focus on performance optimization. This guide expands on various strategies to enhance the performance of Next.js applications.</p><h3>1. Utilize Static Site Generation (SSG)</h3><p>Static Site Generation (SSG) allows developers to pre-render pages at build time, which significantly improves load times for content that does not require real-time data. This method is ideal for blogs, documentation, and landing pages.</p><h4>Example</h4><pre>export async function getStaticProps() {<br>    const data = await fetchData();<br>    return {<br>        props: { data },<br>    };<br>}</pre><h3>2. Implement Incremental Static Regeneration (ISR)</h3><p>ISR enables developers to update static content without a full rebuild, making it perfect for frequently changing content such as news articles or product listings.</p><h4>Example</h4><pre>export async function getStaticProps() {<br>    const data = await fetchData();<br>    return {<br>        props: { data },<br>        revalidate: 10, // Re-generate the page every 10 seconds<br>    };<br>}</pre><h3>3. Optimize Images</h3><p>Next.js includes an Image component that optimizes images automatically by serving them in modern formats and sizes tailored to the user&#39;s device. This reduces load times and improves user experience.</p><h4>Example</h4><pre>import Image from &#39;next/image&#39;;<br><br>const MyComponent = () =&gt; (<br>    &lt;Image src=&quot;/path/to/image.jpg&quot; alt=&quot;Description&quot; width={500} height={300} /&gt;<br>);</pre><h3>4. Code Splitting and Dynamic Imports</h3><p>Next.js automatically splits code into smaller bundles, but you can further optimize performance by using dynamic imports for components that aren’t immediately necessary. This helps in reducing the initial load time.</p><h4>Example</h4><pre>import dynamic from &#39;next/dynamic&#39;;<br><br>const DynamicComponent = dynamic(() =&gt; import(&#39;./DynamicComponent&#39;));<br><br>const MyPage = () =&gt; &lt;DynamicComponent /&gt;;</pre><h3>5. Prefetching and Preloading</h3><p>Next.js prefetches linked pages in the background, improving perceived performance. Using the next/link component ensures that linked pages are prefetched automatically.</p><h4>Example</h4><pre>import Link from &#39;next/link&#39;;<br><br>const MyLink = () =&gt; (<br>    &lt;Link href=&quot;/about&quot;&gt;<br>        &lt;a&gt;About Us&lt;/a&gt;<br>    &lt;/Link&gt;<br>);</pre><h3>6. Reduce JavaScript Bundle Size</h3><p>Analyzing and optimizing your bundle size is crucial. Tools like Webpack Bundle Analyzer can help identify large libraries or unnecessary imports that can be removed or optimized.</p><h4>Example</h4><pre>// Instead of importing the whole library<br>import { specificFunction } from &#39;large-library&#39;;</pre><h3>7. Leverage Caching</h3><p>Implement caching strategies using HTTP caching headers or service workers to store static assets and API responses, which reduces load times for returning users.</p><h4>Example</h4><pre>export default function handler(req, res) {<br>    res.setHeader(&#39;Cache-Control&#39;, &#39;public, max-age=31536000, immutable&#39;);<br>    res.json(data);<br>}</pre><h3>8. Optimize Third-Party Scripts</h3><p>Use the next/script component to manage third-party scripts effectively by controlling their loading priority, which can prevent them from blocking rendering.</p><h4>Example</h4><pre>import Script from &#39;next/script&#39;;<br><br>export default function OptimizedScript() {<br>    return (<br>        &lt;&gt;<br>            &lt;Script src=&quot;https://example.com/script.js&quot; strategy=&quot;lazyOnload&quot; /&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><h3>Conclusion</h3><p>Optimizing performance in Next.js is essential for delivering a fast user experience. By implementing strategies such as <em>SSG</em>, <em>ISR</em>, image optimization, dynamic imports, caching, and effective script management, developers can significantly enhance their applications’ performance.</p><p>Regularly analyzing performance metrics will help adapt strategies to ensure ongoing efficiency and scalability in Next.js applications.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <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=f4dc82f1fa87" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/enhancing-performance-in-next-js-applications-f4dc82f1fa87">Enhancing Performance in Next.js Applications</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operators in JavaScript You Might Not Know]]></title>
            <link>https://javascript.plainenglish.io/operators-in-javascript-you-might-not-know-23194d7ca843?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/23194d7ca843</guid>
            <category><![CDATA[logical-assignment]]></category>
            <category><![CDATA[bitwise-operator]]></category>
            <category><![CDATA[javascript-operators]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[operators]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 02:02:49 GMT</pubDate>
            <atom:updated>2025-01-11T09:36:23.558Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TKtfZ5wT1BqcKS3F" /><figcaption>Photo by <a href="https://unsplash.com/@afgprogrammer?utm_source=medium&amp;utm_medium=referral">Mohammad Rahmani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>JavaScript is a rich and versatile programming language, offering a wide array of operators that can streamline your code and enhance its readability. While many developers are familiar with basic operators like arithmetic and comparison, there are several lesser-known operators that can significantly improve your coding efficiency. In this article, we will delve deeper into some of these operators, providing examples and use cases to illustrate their utility.</p><h3>1. Nullish Coalescing Operator (??)</h3><p>The nullish coalescing operator (<strong>??</strong>) is a relatively new addition to JavaScript (introduced in <em>ES2020</em>) that allows for more precise handling of default values. Unlike the logical OR operator (||), which returns the right-hand operand for any falsy value (including 0, &#39;&#39;, and false), the nullish coalescing operator only considers null and undefined as triggers for the right-hand operand.</p><h4>Example:</h4><pre>const userInput = null;<br>const defaultValue = &#39;Default Value&#39;;<br><br>// Using nullish coalescing<br>const result = userInput ?? defaultValue; // &#39;Default Value&#39;<br><br>// Using logical OR<br>const result2 = userInput || defaultValue; // &#39;Default Value&#39;</pre><p>In this example, both operators yield the same result, but if userInput were 0, the logical OR would return &#39;Default Value&#39;, while the nullish coalescing operator would return 0.</p><h3>2. Optional Chaining Operator (?.)</h3><p>The optional chaining operator (<strong>?.</strong>) allows you to access deeply nested properties of an object without having to check each level for existence. This operator returns undefined if any part of the chain is null or undefined, preventing runtime errors.</p><h4>Example:</h4><pre>const user = {<br>    name: &#39;Alice&#39;,<br>    address: {<br>        city: &#39;Wonderland&#39;,<br>        zip: null<br>    }<br>};<br><br>// Safely accessing nested properties<br>const city = user.address?.city; // &#39;Wonderland&#39;<br>const zipCode = user.address?.zip; // null<br>const country = user.address?.country; // undefined</pre><p>This operator simplifies code that interacts with complex data structures, making it cleaner and less error-prone.</p><h3>3. Exponentiation Operator (**)</h3><p>The exponentiation operator (**) is a relatively new addition to JavaScript (introduced in ES2016) that allows you to raise a number to the power of another number. This operator provides a more concise syntax compared to using the Math.pow() function.</p><h4>Example:</h4><pre>const base = 2;<br>const exponent = 3;<br><br>const result = base ** exponent; // 8 (2^3)<br>console.log(result); // Outputs: 8</pre><p>Using the exponentiation operator makes your code more readable and expressive when dealing with powers.</p><h3>4. Unary Plus (+)</h3><p>The unary plus operator (<strong>+</strong>) can be used to convert strings into numbers quickly. This is especially useful when dealing with user input or data from external sources where type coercion might be necessary.</p><h4>Example:</h4><pre>const stringNumber = &#39;123&#39;;<br>const invalidNumber = &#39;abc&#39;;<br><br>const numberValue = +stringNumber; // 123<br>const nanValue = +invalidNumber; // NaN<br><br>console.log(numberValue); // Outputs: 123<br>console.log(nanValue); // Outputs: NaN</pre><p>Using this operator provides a fast and efficient way to coerce types without verbose syntax.</p><h3>5. Bitwise NOT (~)</h3><p>The bitwise NOT operator (~) inverts the bits of its operand. This operator can be useful for certain mathematical operations, such as quickly calculating the negative of a number minus one.</p><h4>Example:</h4><pre>const num = 5; // Binary: 00000000 00000000 00000000 00000101<br>const inverted = ~num; // Binary: 11111111 11111111 11111111 11111010<br><br>console.log(inverted); // Outputs: -6 (in decimal)</pre><p>This operator can be particularly useful in scenarios where you need to manipulate binary data or perform bitwise calculations.</p><h3>6. Other Bitwise Operators</h3><p>Bitwise operators perform operations on binary representations of numbers. They can be particularly useful for low-level programming tasks, such as optimizing performance or manipulating individual bits.</p><h4>Common Bitwise Operators:</h4><ul><li>AND (<strong>&amp;)</strong>: Returns a binary number where each bit is set to 1 if both corresponding bits are 1.</li><li>OR (<strong>|</strong>): Returns a binary number where each bit is set to 1 if at least one of the corresponding bits is 1.</li><li>XOR (<strong>^</strong>): Returns a binary number where each bit is set to 1 if only one of the corresponding bits is 1.</li><li>Left Shift (<strong>&lt;&lt;</strong>): Shifts bits to the left, effectively multiplying by powers of two.</li><li>Right Shift (<strong>&gt;&gt;</strong>): Shifts bits to the right, effectively dividing by powers of two.</li></ul><h4>Example:</h4><pre>// Checking if a number is even or odd using AND operator<br>const isEven = (num) =&gt; (num &amp; 1) === 0;<br><br>console.log(isEven(4)); // true (even)<br>console.log(isEven(5)); // false (odd)<br><br>// Left shift example<br>const leftShiftResult = 3 &lt;&lt; 2; // 12 (3 * 2^2)<br>console.log(leftShiftResult); // Outputs: 12<br><br>// Right shift example<br>const rightShiftResult = 8 &gt;&gt; 2; // 2 (8 / 2^2)<br>console.log(rightShiftResult); // Outputs: 2</pre><p>Bitwise operations can enhance performance in certain scenarios, especially when working with large datasets or in performance-critical applications.</p><h3>7. Logical Assignment Operators</h3><p>Introduced in <em>ES2021</em>, logical assignment operators combine logical operations with assignment, allowing you to write more concise code.</p><h4>Types of Logical Assignment Operators:</h4><ul><li>Logical AND Assignment (<strong>&amp;&amp;=</strong>): Assigns the right-hand operand if the left-hand operand is truthy.</li><li>Logical OR Assignment (<strong>||=</strong>): Assigns the right-hand operand if the left-hand operand is falsy.</li><li>Nullish Coalescing Assignment (<strong>??=</strong>): Assigns the right-hand operand if the left-hand operand is nullish (null or undefined).</li></ul><h4>Example:</h4><pre>let x = false;<br>let y = true;<br>let z;<br><br>x &amp;&amp;= true; // x remains false<br>y ||= false; // y remains true<br>z ??= &#39;default&#39;; // z becomes &#39;default&#39;<br><br>console.log(x); // Outputs: false<br>console.log(y); // Outputs: true<br>console.log(z); // Outputs: &#39;default&#39;</pre><h3>Conclusion</h3><p>Understanding these lesser-known JavaScript operators can significantly enhance your coding capabilities. By incorporating them into your projects, you can write more concise and efficient code, ultimately improving your development workflow.</p><p>Whether you’re managing optional values, performing quick calculations, or simplifying complex expressions, these operators provide valuable tools at your disposal. As you continue your journey in JavaScript development, consider exploring these operators further to unlock their full potential.</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <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=23194d7ca843" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/operators-in-javascript-you-might-not-know-23194d7ca843">Operators in JavaScript You Might Not Know</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Asynchronous JavaScript: Promises, Async/Await, and Beyond]]></title>
            <link>https://javascript.plainenglish.io/mastering-asynchronous-javascript-promises-async-await-and-beyond-89af6db8b42f?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/89af6db8b42f</guid>
            <category><![CDATA[asynchronous-programming]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[asyncawait]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Sat, 21 Dec 2024 04:46:07 GMT</pubDate>
            <atom:updated>2025-01-06T05:20:03.114Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8fdtlbp1Kd24DHrd" /><figcaption>Photo by <a href="https://unsplash.com/@kommumikation?utm_source=medium&amp;utm_medium=referral">Mika Baumeister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Asynchronous programming is a cornerstone of modern JavaScript development, enabling developers to write responsive applications that can handle multiple tasks simultaneously. This article explores the evolution of asynchronous JavaScript, focusing on Promises, Async/Await, and advanced patterns that enhance efficiency and readability.</p><h3>The Evolution of Asynchronous Programming</h3><p>Historically, JavaScript relied heavily on callbacks to manage asynchronous operations. While effective, callbacks often led to “callback hell,” making code difficult to read and maintain. The introduction of Promises in ES6 (<em>ECMAScript2015</em>) marked a significant improvement by providing a cleaner way to handle asynchronous operations.Promises represent a value that may be available now, or in the future, or never.</p><p>They have three states: <em>pending</em>, <em>fulfilled</em>, and <em>rejected</em>. Here’s a simple example:</p><pre>let myPromise = new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        resolve(&quot;Operation successful!&quot;);<br>    }, 1000);<br>});<br><br>myPromise.then(result =&gt; console.log(result)).catch(error =&gt; console.error(error));</pre><h3>Async/Await: A Syntactic Sugar Over Promises</h3><p>Introduced in ES2017 (ES8), Async/Await allows developers to write asynchronous code that looks synchronous, greatly improving readability. An async function returns a promise, and the await keyword pauses execution until the promise resolves.</p><h4>Basic Usage</h4><p>Here’s an example of using async/await:</p><pre>async function fetchData() {<br>    try {<br>        let result = await myPromise;<br>        console.log(result);<br>    } catch (error) {<br>        console.error(&quot;Error occurred:&quot;, error);<br>    }<br>}<br><br>fetchData();</pre><p>This approach allows for centralized error handling in one location rather than scattering .catch() methods throughout your code.</p><h3>Advanced Examples of Promises</h3><p>While Promises and async/await cover most use cases, advanced patterns can further enhance performance and manageability:</p><h4>1. Chaining Promises</h4><p>Chaining is one of the most common uses of promises, allowing for sequential execution of asynchronous tasks. Each then returns a new promise, which can be used to chain further operations.</p><pre>function fetchData() {<br>    return new Promise((resolve) =&gt; {<br>        setTimeout(() =&gt; resolve(&quot;Data fetched!&quot;), 1000);<br>    });<br>}<br><br>function processData(data) {<br>    return new Promise((resolve) =&gt; {<br>        setTimeout(() =&gt; resolve(`${data} and processed!`), 1000);<br>    });<br>}<br><br>fetchData()<br>    .then(result =&gt; processData(result))<br>    .then(finalResult =&gt; console.log(finalResult))<br>    .catch(error =&gt; console.error(&quot;Error:&quot;, error));</pre><h4>2. Using Promise.all()</h4><p>Promise.all() is useful when you want to execute multiple promises in parallel and wait for all of them to resolve or for any to reject. It takes an array of promises and returns a single promise.</p><pre>const promiseA = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;Promise A resolved&quot;), 200));<br>const promiseB = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;Promise B resolved&quot;), 300));<br>const promiseC = new Promise((resolve, reject) =&gt; setTimeout(() =&gt; reject(&quot;Promise C rejected&quot;), 250));<br><br>Promise.all([promiseA, promiseB, promiseC])<br>    .then(results =&gt; {<br>        console.log(results); // This won&#39;t execute because one promise is rejected<br>    })<br>    .catch(error =&gt; {<br>        console.error(&quot;Error:&quot;, error); // Output: Error: Promise C rejected<br>    });</pre><h4>3. Using Promise.allSettled()</h4><p>Promise.allSettled() is similar to Promise.all(), but it waits for all promises to settle (either resolved or rejected), returning an array of objects describing the outcome of each promise.</p><pre>Promise.allSettled([promiseA, promiseB, promiseC])<br>    .then(results =&gt; {<br>        results.forEach((result, index) =&gt; {<br>            if (result.status === &quot;fulfilled&quot;) {<br>                console.log(`Promise ${index + 1} resolved with value: ${result.value}`);<br>            } else {<br>                console.log(`Promise ${index + 1} rejected with reason: ${result.reason}`);<br>            }<br>        });<br>    });</pre><h4>4. Using Promise.any()</h4><p>Promise.any() takes an iterable of Promise objects and, as soon as one of the promises in the iterable fulfills, returns a single promise that resolves with the value from that promise.</p><p>If no promises in the iterable fulfill (i.e., all are rejected), then it returns a single promise that rejects with an AggregateError, a new subclass of Error that groups together individual errors.</p><pre>const promiseD = Promise.reject(&quot;Promise D rejected&quot;);<br>const promiseE = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;Promise E resolved&quot;), 100));<br>const promiseF = new Promise((resolve) =&gt; setTimeout(() =&gt; resolve(&quot;Promise F resolved&quot;), 200));<br><br>Promise.any([promiseD, promiseE, promiseF])<br>    .then(result =&gt; {<br>        console.log(result); // Output: &quot;Promise E resolved&quot;<br>    })<br>    .catch(error =&gt; {<br>        console.error(&quot;All promises were rejected:&quot;, error);<br>    });</pre><h3>Best Practices for Asynchronous JavaScript</h3><p>To write efficient asynchronous code, consider these best practices:</p><ul><li><strong>Understand the Event Loop</strong>: Familiarize yourself with how JavaScript handles asynchronous tasks through its event loop.</li><li><strong>Limit Concurrency</strong>: Control the number of concurrent operations to avoid overwhelming resources.</li><li><strong>Use</strong> Promise.all <strong>for Parallel Execution</strong>: When executing multiple promises concurrently, use Promise.all() for better performance.</li><li><strong>Handle Errors Gracefully</strong>: Always implement error handling using try/catchwithin async functions.</li><li><strong>Avoid Blocking the Event Loop</strong>: Offload heavy computations or use worker threads to maintain responsiveness.</li></ul><h3>Conclusion</h3><p>Advanced usage of native promises in JavaScript allows developers to manage complex asynchronous workflows efficiently. By leveraging methods like Promise.all(), Promise.allSettled(), and async/await, you can create robust applications that handle multiple tasks seamlessly while maintaining readability and error management.</p><p>By understanding these advanced concepts will enhance your ability to write clean and efficient asynchronous code in JavaScript without relying on external libraries. Happy coding!</p><h3>Thank you for being a part of the community</h3><p><em>Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://cofeed.app/"><strong>Check out CoFeed, the smart way to stay up-to-date with the latest in tech</strong></a> <strong>🧪</strong></li><li><a href="https://differ.blog/"><strong>Start your own free AI-powered blog on Differ</strong></a> 🚀</li><li><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Join our content creators community on Discord</strong></a> 🧑🏻‍💻</li><li>For more content, visit <a href="https://plainenglish.io/"><strong>plainenglish.io</strong></a> + <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=89af6db8b42f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-asynchronous-javascript-promises-async-await-and-beyond-89af6db8b42f">Mastering Asynchronous JavaScript: Promises, Async/Await, and Beyond</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SOLID Principles in TypeScript Development]]></title>
            <link>https://javascript.plainenglish.io/understanding-solid-principles-in-typescript-development-97c57f4c5c26?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/97c57f4c5c26</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[better-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Sat, 23 Nov 2024 02:48:13 GMT</pubDate>
            <atom:updated>2024-11-25T16:01:49.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uvCFhJ9YmpFyQSt7" /><figcaption>Photo by <a href="https://unsplash.com/@oskaryil?utm_source=medium&amp;utm_medium=referral">Oskar Yildiz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In software development, writing code that not only works but is also easy to understand, extend, and maintain is an art. One of the most influential frameworks for achieving this goal is the <em>SOLID</em> principles. These principles help developers create cleaner and more structured code, making it easier to maintain and develop in the future.</p><h3>What Are SOLID Principles?</h3><p><em>SOLID</em> is an acronym that consists of five software design principles introduced by <em>Robert C. Martin</em> (Uncle Bob). Here’s a brief explanation of each principle:</p><ul><li><strong>S</strong>: Single Responsibility Principle (SRP)</li><li><strong>O</strong>: Open/Closed Principle (OCP)</li><li><strong>L</strong>: Liskov Substitution Principle (LSP)</li><li><strong>I:</strong> Interface Segregation Principle (ISP)</li><li><strong>D</strong>: Dependency Inversion Principle (DIP)</li></ul><h3>1. Single Responsibility Principle (SRP)</h3><p>This principle states that a class should have one reason to change. In other words, each class should have a clear responsibility.</p><p>For example, instead of having a UserManagerclass that handles all aspects of users, we can separate responsibilities into several classes like UserDataManager for managing user data and UserAuthenticationManagerfor user authentication.</p><pre>class UserDataManager {<br>    getUsers(): User[] {<br>        // Fetch and return user data<br>    }<br><br>    saveUser(user: User): void {<br>        // Save user data<br>    }<br>}<br><br>class UserAuthenticationManager {<br>    authenticateUser(user: User): boolean {<br>        // Authenticate user credentials<br>    }<br>}</pre><h3>2. Open/Closed Principle (OCP)</h3><p>This principle states that software entities should be open for extension but closed for modification. This means we can add new functionality without changing existing code.</p><p>For instance, we can create an interface for different types of databases and implement new functionality without modifying existing classes.</p><pre>interface Database {<br>    create(order: Order): void;<br>    update(order: Order): void;<br>}<br><br>class MySQLDatabase implements Database {<br>    create(order: Order) {<br>        // Logic to create and save to the database<br>    }<br><br>    update(order: Order) {<br>        // Logic to update the database<br>    }<br>}</pre><h3>3. Liskov Substitution Principle (LSP)</h3><p>This principle emphasizes that objects of a subclass should be able to replace objects of the superclass without affecting the correctness of the program.</p><p>In TypeScript, this means we should follow well-defined interfaces and not alter expected behavior.</p><pre>interface Shape {<br>    area(): number;<br>}<br><br>class Circle implements Shape {<br>    constructor(private radius: number) {}<br>    <br>    area(): number {<br>        return Math.PI * this.radius * this.radius;<br>    }<br>}<br><br>class Rectangle implements Shape {<br>    constructor(private width: number, private height: number) {}<br>    <br>    area(): number {<br>        return this.width * this.height;<br>    }<br>}</pre><h3>4. Interface Segregation Principle (ISP)</h3><p>This principle states that clients should not be forced to depend on interfaces they do not use.</p><p>In the context of TypeScript, we should break large interfaces into smaller, more specific ones.</p><pre>interface AudioPlayer {<br>    playAudio(): void;<br>}<br><br>interface VideoPlayer {<br>    playVideo(): void;<br>}<br><br>class MediaPlayer implements AudioPlayer, VideoPlayer {<br>    playAudio(): void {<br>        // Logic to play audio<br>    }<br><br>    playVideo(): void {<br>        // Logic to play video<br>    }<br>}</pre><h3>5. Dependency Inversion Principle (DIP)</h3><p>This principle states that high-level modules should not depend on low-level modules; both should depend on abstractions.</p><p>In TypeScript, we can use dependency injection to adhere to this principle.</p><pre>interface Logger {<br>    log(message: string): void;<br>}<br><br>class ConsoleLogger implements Logger {<br>    log(message: string): void {<br>        console.log(message);<br>    }<br>}<br><br>class UserManager {<br>    constructor(private logger: Logger) {}<br><br>    addUser(user: User): void {<br>        // Logic to add a user<br>        this.logger.log(`User ${user.name} added.`);<br>    }<br>}</pre><h3>Conclusion</h3><p>Applying <em>SOLID</em> principles in TypeScript development is crucial for creating code that is maintainable and extensible. By understanding and implementing these principles, you will be better equipped to build software that is not only functional but also ready for future changes. Remember that writing code is not just about making it work; it’s about creating engineering masterpieces that are durable and easy to understand.</p><p>By embracing <em>SOLID</em> principles, you can significantly improve the quality of your code, making it more modular, maintainable, and prepared for growth in the future.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97c57f4c5c26" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-solid-principles-in-typescript-development-97c57f4c5c26">Understanding SOLID Principles in TypeScript Development</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing OCR with Tesseract.js in Next.js]]></title>
            <link>https://javascript.plainenglish.io/implementing-ocr-with-tesseract-js-in-next-js-ac4143ff5218?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4143ff5218</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[optical-character-recogn]]></category>
            <category><![CDATA[ocr]]></category>
            <category><![CDATA[tesseract]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Mon, 18 Nov 2024 00:53:04 GMT</pubDate>
            <atom:updated>2024-11-19T09:28:58.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XXhDt5w2OowSjYPI" /><figcaption>Photo by <a href="https://unsplash.com/@ascalaphe?utm_source=medium&amp;utm_medium=referral">Nicolas Houdayer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Optical Character Recognition</em> (OCR) is a powerful technology that allows us to convert images of text into machine-encoded text. In this article, we will explore how to set up a Next.js application and implement <em>OCR</em> using <em>Tesseract.js</em>, a JavaScript library that performs <em>OCR</em> directly in the browser.</p><h3>Setting Up Your Next.js Project</h3><h4>1. Create a New Next.js Project</h4><p>First, we need to create a new Next.js application. Run the following command in your terminal:</p><pre>npx create-next-app@latest next-ocr<br>cd next-ocr</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*AvNlJepksKiP_qkxixzT2w.png" /></figure><h4>2. Install Required Packages</h4><p>Once the project is created, we need to install tesseract.js to support text recognition from images:</p><pre>yarn add tesseract.js</pre><h4>3. Configure Next.js</h4><p>To ensure Tesseract.js works properly, we need to add some configurations in next.config.js. Add the following code:</p><pre>/** @type {import(&#39;next&#39;).NextConfig} */<br><br>const nextConfig = {<br>  future: { webpack5: true },<br>  webpack: config =&gt; {<br>    config.resolve.alias.canvas = false;<br>    config.resolve.alias.encoding = false;<br>    return config;<br>  },<br>};<br><br>module.exports = nextConfig;</pre><h3>Implementing OCR with Tesseract.js</h3><h4>1. Create the OCR Component</h4><p>Next, we will create a component to handle the OCR process. Create a new file named OcrReader.tsx inside the app/components/ folder and add the following code:</p><pre>&#39;use client&#39;;<br><br>import { useState } from &#39;react&#39;;<br>import { createWorker } from &#39;tesseract.js&#39;;<br><br>const OcrReader = () =&gt; {<br>  const [selectedImage, setSelectedImage] = useState&lt;File | null&gt;(null);<br>  const [ocrResult, setOcrResult] = useState&lt;string&gt;(&#39;&#39;);<br>  const [ocrStatus, setOcrStatus] = useState&lt;string&gt;(&#39;&#39;);<br><br>  const handleImageChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    if (event.target.files &amp;&amp; event.target.files[0]) {<br>      setSelectedImage(event.target.files[0]);<br>      setOcrResult(&#39;&#39;); // Reset OCR result<br>      setOcrStatus(&#39;&#39;); // Reset status<br>    }<br>  };<br><br>  const readImageText = async () =&gt; {<br>    if (!selectedImage) return;<br><br>    setOcrStatus(&#39;Processing...&#39;);<br>    const worker = await createWorker(&#39;eng&#39;, 1, {<br>      logger: m =&gt; console.log(m), // Add logger here<br>    });<br><br>    try {<br>      const {<br>        data: { text },<br>      } = await worker.recognize(selectedImage);<br><br>      setOcrResult(text);<br>      setOcrStatus(&#39;Completed&#39;);<br>    } catch (error) {<br>      console.error(error);<br>      setOcrStatus(&#39;Error occurred during processing.&#39;);<br>    } finally {<br>      await worker.terminate();<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input type=&#39;file&#39; accept=&#39;image/*&#39; onChange={handleImageChange} /&gt;<br><br>      {selectedImage &amp;&amp; (<br>        &lt;img<br>          src={URL.createObjectURL(selectedImage)}<br>          alt=&#39;Uploaded content&#39;<br>          width={350}<br>          style={{ marginTop: 15 }}<br>        /&gt;<br>      )}<br><br>      &lt;div style={{ marginTop: 15 }}&gt;<br>        &lt;button<br>          onClick={readImageText}<br>          style={{<br>            background: &#39;#FFFFFF&#39;,<br>            borderRadius: 7,<br>            color: &#39;#000000&#39;,<br>            padding: 5,<br>          }}<br>        &gt;<br>          Submit<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br><br>      &lt;p style={{ marginTop: 20, fontWeight: 700 }}&gt;Status:&lt;/p&gt;<br>      &lt;p&gt;{ocrStatus}&lt;/p&gt;<br>      &lt;h3 style={{ marginTop: 10, fontWeight: 700 }}&gt;Extracted Text:&lt;/h3&gt;<br>      &lt;p<br>        dangerouslySetInnerHTML={{<br>          // clear html tags and or unwanted characters<br>          __html: ocrResult<br>            .replace(/\n/g, &#39;&lt;br /&gt;&#39;)<br>            .replace(/[=,—,-,+]/g, &#39; &#39;),<br>        }}<br>        style={{<br>          border: &#39;1px solid white&#39;,<br>          width: &#39;fit-content&#39;,<br>          padding: 10,<br>          marginTop: 10,<br>          borderRadius: 10,<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default OcrReader;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*62gYjzu7l9Sm-niOxq4QIg.png" /><figcaption>The initial UI for OCR with Tesseract.js in Next.js.</figcaption></figure><h4>2. Use the Component on the Home Page</h4><p>Now we need to use the OcrReader component on our application&#39;s home page. Open the file app/page.tsx and add the following code:</p><pre>import OcrReader from &#39;./components/OcrReader&#39;;<br><br>const Home = () =&gt; {<br>  return (<br>    &lt;div style={{ padding: 10}}&gt;<br>      &lt;h1 style={{ fontWeight: 800, fontSize: 20 }}&gt;<br>        OCR with Tesseract.js in Next.js<br>      &lt;/h1&gt;<br>      &lt;br /&gt;<br>      &lt;OcrReader /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Home;</pre><h3>Running Your Application</h3><p>After completing all the steps, run your Next.js application with the command:</p><pre>yarn dev</pre><p>Your application should now be able to accept images and extract the text using <em>Tesseract.js</em>. Simply upload an image, click the “Submit” button, and see the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*VcaOLMyRAS7lv0JWigZ-Wg.gif" /><figcaption>Demo of OCR with Tesseract.js in Next.js.</figcaption></figure><h3>Conclusion</h3><p>In this tutorial, we learned how to set up a Next.js project and implement <em>OCR</em> using <em>Tesseract.js</em>. By following these steps, you can create an application capable of recognizing text from images directly in the browser. This is a great starting point for exploring further capabilities of character recognition in your web applications.</p><p>For further exploration of this amazing library, you can take a look at the documentation <a href="https://github.com/naptha/tesseract.js/blob/master/docs/examples.md">here</a>.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4143ff5218" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/implementing-ocr-with-tesseract-js-in-next-js-ac4143ff5218">Implementing OCR with Tesseract.js in Next.js</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript: The Secrets Behind Variables, Hoisting, and the Magic of Closures]]></title>
            <link>https://javascript.plainenglish.io/mastering-javascript-the-secrets-behind-variables-hoisting-and-the-magic-of-closures-79c3ae10bda1?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/79c3ae10bda1</guid>
            <category><![CDATA[javascript-fundamental]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[closure-in-javascript]]></category>
            <category><![CDATA[hoisting-in-javascript]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Fri, 08 Nov 2024 02:11:04 GMT</pubDate>
            <atom:updated>2024-11-08T06:46:41.479Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y8WPqU-AgGXNZj6QyFV38A.png" /><figcaption>JS — Variables, Hoisting, and Closures Article Cover.</figcaption></figure><p><strong>JavaScript</strong> is a versatile programming language that is widely used for <em>web development</em>. Among its many features, understanding <em>variables</em>, <em>hoisting</em>, and <em>closures</em> is crucial for writing effective and efficient code. This article delves into these concepts to provide a comprehensive overview.</p><h3>Variables in JavaScript</h3><p>In JavaScript, <strong>variables</strong> are used to store data values. There are three main ways to declare variables:</p><ul><li>var: This keyword declares a variable that is <em>function-scoped</em> or <em>globally scoped</em>. It can be re-declared and updated.</li><li>let: Introduced in <em>ES6</em>, let allows you to declare <em>block-scoped</em> variables. Unlike var, let cannot be re-declared within the same scope.</li><li>const: Also introduced in <em>ES6</em>, const is used to declare <em>block-scoped</em> variables that cannot be re-assigned after their initial assignment.</li></ul><p>Understanding the scope of these variable types is essential for managing the visibility and lifetime of variables in your code.</p><h3>Hoisting in JavaScript</h3><p><strong>Hoisting</strong> is a fundamental concept in JavaScript that refers to the default behavior of moving declarations to the top of their containing scope during the compilation phase. This means that you can use variables before they are declared in the code.</p><h4>How Hoisting Works</h4><ul><li><strong>Variable Declarations</strong>: Only the declarations are <em>hoisted</em>, not the initializations. For example:</li></ul><pre>console.log(x); // undefined<br>var x = 5;</pre><p>In this case, x is hoisted but not its value, leading to undefined being logged.</p><ul><li><strong>Function Declarations</strong>: Functions declared using the function keyword are also hoisted:</li></ul><pre>greet(); // &quot;Hello&quot;<br>function greet() {<br>    console.log(&quot;Hello&quot;);<br>}</pre><ul><li><strong>Block Scoped Variables</strong>: Variables declared with let and const are also hoisted but remain uninitialized until their declaration is reached, resulting in a ReferenceError if accessed beforehand:</li></ul><pre>console.log(carName); // ReferenceError<br>let carName = &quot;Volvo&quot;;</pre><h3>Closures in JavaScript</h3><p>A <strong>closure</strong> is a powerful feature in JavaScript that allows a function to access variables from its outer (<em>enclosing</em>) scope even after that scope has finished executing. This is particularly useful for data encapsulation and creating private variables.</p><h4>How Closures Work</h4><p>When you define a function inside another function, the inner function forms a closure with its outer function’s scope. Here’s an example:</p><pre>function outerFunction() {<br>    let outerVariable = &quot;I&#39;m from outer scope!&quot;;<br>    <br>    function innerFunction() {<br>        console.log(outerVariable); // Accessing outerVariable<br>    }<br>    <br>    return innerFunction;<br>}<br><br>const myClosure = outerFunction();<br>myClosure(); // &quot;I&#39;m from outer scope!&quot;</pre><ul><li>outerFunction defines a variable outerVariable.</li><li>Inside outerFunction, we define innerFunction, which logs outerVariable.</li><li>When we call outerFunction, it returns innerFunction, which we assign to closureExample.</li><li>Calling closureExample() executes innerFunction, which still has access to outerVariable, demonstrating how closures work.</li></ul><p>In this example, it demonstrates how <em>closures</em> can maintain state even after the outer function has executed.</p><h4>Practical Example: Counter Using Closures</h4><p>Closures can be used to create private variables. Here’s how you can create a simple counter:</p><pre>function createCounter() {<br>    let count = 0; // Private variable<br><br>    return {<br>        increment: function() {<br>            count++;<br>            return count; // Return current count<br>        },<br>        decrement: function() {<br>            count--;<br>            return count; // Return current count<br>        },<br>        getCount: function() {<br>            return count; // Return current count without modifying it<br>        }<br>    };<br>}<br><br>const counter = createCounter();<br>console.log(counter.increment()); // Output: 1<br>console.log(counter.increment()); // Output: 2<br>console.log(counter.getCount());  // Output: 2<br>console.log(counter.decrement());  // Output: 1</pre><ul><li>The createCounter function initializes a private variable count.</li><li>It returns an object with methods (increment, decrement, and getCount) that can manipulate and access the count variable.</li><li>The variable count cannot be accessed directly from outside the returned object, ensuring encapsulation and privacy.</li></ul><h3>Conclusion</h3><p>Understanding <em>variables</em>, <em>hoisting</em>, and <em>closures</em> is essential for mastering JavaScript. These concepts not only help prevent common pitfalls but also empower developers to write cleaner and more maintainable code. By leveraging hoisting effectively and utilizing closures for data encapsulation, you can enhance your JavaScript programming skills significantly.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79c3ae10bda1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-javascript-the-secrets-behind-variables-hoisting-and-the-magic-of-closures-79c3ae10bda1">Mastering JavaScript: The Secrets Behind Variables, Hoisting, and the Magic of Closures</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortless File Uploads in Next.js with TypeScript: Track Progress with Axios]]></title>
            <link>https://javascript.plainenglish.io/effortless-file-uploads-in-next-js-with-typescript-track-progress-with-axios-10952c6f1f62?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/10952c6f1f62</guid>
            <category><![CDATA[upload]]></category>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[progress]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 03:37:10 GMT</pubDate>
            <atom:updated>2024-11-01T10:21:57.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GaCv2iciVNef0Gwt" /><figcaption>Photo by <a href="https://unsplash.com/@mike_van_den_bos?utm_source=medium&amp;utm_medium=referral">Mike van den Bos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Implementing file uploads in a Next.js application can be straightforward, especially when using TypeScript for type safety. This guide will walk you through creating a file upload component that tracks upload progress using Axios, ensuring a smooth user experience.</p><h3>Setting Up Your Next.js Project</h3><p>First, ensure you have a Next.js project set up with TypeScript. If you haven’t done this yet, you can create a new project by running:</p><pre>npx create-next-app@latest upload-progress --typescript</pre><p>In this example, I will be using the new <a href="https://nextjs.org/docs/app/building-your-application/routing">App Router</a> pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q6jbexE3kZJXVFOtkgEv4w.png" /><figcaption>create-next-app setup.</figcaption></figure><p>Next, navigate into your project directory:</p><pre>cd upload-progress</pre><p>Then, install Axios:</p><pre>npm install axios</pre><pre>yarn add axios</pre><h3>Creating the File Upload Component</h3><p>Now, let’s create a file upload component that utilizes Axios to handle file uploads and track progress.</p><h4><strong>FileUpload.tsx</strong></h4><p>Create a new file called FileUpload.tsx in the src/components directory:</p><pre>// components/FileUpload.tsx<br><br>&#39;use client&#39;;<br><br>import axios from &#39;axios&#39;;<br>import React, { useState } from &#39;react&#39;;<br><br>const FileUpload: React.FC = () =&gt; {<br>  const [file, setFile] = useState&lt;File | null&gt;(null);<br>  const [uploadProgress, setUploadProgress] = useState(0);<br>  const [uploadedFileURL, setUploadedFileURL] = useState&lt;string&gt;(&#39;&#39;);<br><br>  const handleChange = (event: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    if (event.target.files) {<br>      setFile(event.target.files[0]);<br>    }<br>  };<br><br>  const handleSubmit = async (event: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>    event.preventDefault();<br>    if (!file) return;<br><br>    const formData = new FormData();<br>    formData.append(&#39;file&#39;, file);<br><br>    try {<br>      const response = await axios.post(&#39;/upload&#39;, formData, {<br>        headers: {<br>          &#39;Content-Type&#39;: &#39;multipart/form-data&#39;,<br>        },<br>        onUploadProgress: progressEvent =&gt; {<br>          const percentCompleted = Math.round(<br>            (progressEvent.loaded * 100) / (progressEvent.total || 1)<br>          );<br>          setUploadProgress(percentCompleted);<br>        },<br>      });<br>      console.log(&#39;Upload Successful:&#39;, response.data);<br>      setUploadedFileURL(response.data.fileUrl); // Assuming the response contains the uploaded file URL<br>    } catch (error) {<br>      console.error(&#39;Error uploading file:&#39;, error);<br>    }<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;form onSubmit={handleSubmit}&gt;<br>        &lt;h2&gt;Upload a File&lt;/h2&gt;<br>        &lt;input type=&#39;file&#39; onChange={handleChange} /&gt;<br>        &lt;button type=&#39;submit&#39;&gt;Upload&lt;/button&gt;<br>        &lt;progress value={uploadProgress} max=&#39;100&#39;&gt;&lt;/progress&gt;<br>        {uploadProgress &gt; 0 &amp;&amp; &lt;p&gt;Upload Progress: {uploadProgress}%&lt;/p&gt;}<br>      &lt;/form&gt;<br>      {uploadedFileURL &amp;&amp; &lt;img src={uploadedFileURL} alt=&#39;Uploaded content&#39; /&gt;}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default FileUpload;</pre><h3>Creating the API Route for Uploads</h3><p>Next, you need to create an API route that handles the file upload. This will be located in the app folder, under the new <a href="https://nextjs.org/docs/app/building-your-application/routing">App Router Pattern in Next.js</a> pattern.</p><h4><strong>upload/route.ts</strong></h4><p>Create a new file called route.ts in the src/app directory:</p><pre>// app/upload/route.ts<br><br>import fs from &#39;fs&#39;;<br>import { NextResponse as NextServerResponse } from &#39;next/server&#39;;<br>import path from &#39;path&#39;;<br><br>export async function POST(req: Request) {<br>  const formData = await req.formData();<br>  const file = formData.get(&#39;file&#39;) as File;<br><br>  if (!file) {<br>    return new NextServerResponse(<br>      JSON.stringify({ message: &#39;No file uploaded&#39; }),<br>      { status: 400 }<br>    );<br>  }<br><br>  const targetPath = path.join(process.cwd(), &#39;public/uploads&#39;);<br><br>  try {<br>    // Ensure uploads directory exists<br>    fs.mkdirSync(targetPath, { recursive: true });<br><br>    const filePath = path.join(targetPath, file.name);<br><br>    // Read the file buffer directly instead of using FileReader<br>    const arrayBuffer = await file.arrayBuffer();<br>    const buffer = Buffer.from(arrayBuffer);<br><br>    fs.writeFileSync(filePath, buffer);<br><br>    return new NextServerResponse(<br>      JSON.stringify({<br>        message: &#39;File uploaded successfully&#39;,<br>        fileUrl: `/uploads/${file.name}`,<br>      }),<br>      { status: 200 }<br>    );<br>  } catch (error) {<br>    console.error(&#39;Error saving file:&#39;, error);<br>    return new NextServerResponse(<br>      JSON.stringify({<br>        message: &#39;Error uploading file&#39;,<br>      }),<br>      { status: 500 }<br>    );<br>  }<br>}</pre><p>This will upload the file into /publics/uploads folder.</p><h3><strong>Integrating the Component into Your Page</strong></h3><p>Now, you can use the FileUpload component in any of your pages. For example, let&#39;s add it to the homepage.</p><h4><strong>index.tsx</strong></h4><p>Edit yoursrc/app/pages.tsx page:</p><pre>// app/pages.tsx<br><br>import React from &#39;react&#39;;<br>import FileUpload from &#39;../components/FileUpload&#39;;<br><br>const HomePage: React.FC = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Welcome to the File Upload App!&lt;/h1&gt;<br>      &lt;FileUpload /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default HomePage;</pre><p>This will be our final project structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*7z_mraa7NB_wtW0Y6PM1Aw.png" /><figcaption>Final Project Structure.</figcaption></figure><h3>Running Your Application</h3><p>Finally, run your Next.js application:</p><pre>npm run dev</pre><pre>yarn dev</pre><p>Visit http://localhost:3000, and you should see your file upload form. You can select a file and track its upload progress!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8eRKj-IoJNZvXZpBHYbF7A.gif" /><figcaption>Upload Progress Demo.</figcaption></figure><h3>Conclusion</h3><p>This guide has shown you how to create an engaging file upload feature in a Next.js application using TypeScript and Axios. By tracking upload progress, you enhance user experience significantly. Feel free to expand upon this basic implementation by adding features such as error handling and user notifications for a more robust application.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10952c6f1f62" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/effortless-file-uploads-in-next-js-with-typescript-track-progress-with-axios-10952c6f1f62">Effortless File Uploads in Next.js with TypeScript: Track Progress with Axios</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Atomic Design: A Step-by-Step Guide to Building Scalable UI Components]]></title>
            <link>https://javascript.plainenglish.io/mastering-atomic-design-a-step-by-step-guide-to-building-scalable-ui-components-60b0d2a94cc3?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/60b0d2a94cc3</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[atomic-design]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 09:29:25 GMT</pubDate>
            <atom:updated>2024-10-30T02:35:53.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*waupqTD7hvK5EZb7" /><figcaption>Photo by <a href="https://unsplash.com/@amayli?utm_source=medium&amp;utm_medium=referral">Amélie Mourichon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Atomic Design is a methodology for creating design systems that breaks down user interface components into a hierarchical structure. Developed by <em>Brad Frost</em>, this approach draws inspiration from chemistry, where complex structures are built from simpler components. By understanding and applying Atomic Design principles, designers and developers can create consistent, efficient, and scalable user interfaces.</p><h3>The Five Levels of Atomic Design</h3><p>Atomic Design consists of five distinct levels: <em>Atoms</em>, <em>Molecules</em>, <em>Organisms</em>, <em>Templates,</em> and <em>Pages</em>. Each level serves as a building block for the next, facilitating a systematic approach to design.</p><h4>1. Atoms</h4><p>Atoms are the most basic building blocks of design. They represent individual elements that cannot be broken down further without losing their meaning. Common examples include:</p><ul><li>Buttons</li><li>Labels</li><li>Input fields</li><li>Helper</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/151/1*s9ie3PMYk0J9fz6zKpL9UA.png" /><figcaption>Atomic Button component.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/70/1*U2GCkdJKHi_c5ArmBDWWKQ.png" /><figcaption>Atomic Label component.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*CI5lvY3ItuX4Er9M9BfdVA.png" /><figcaption>Atomic Input Fields component.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/243/1*7KDyUx6Xx-vLw97bxIe_YQ.png" /><figcaption>Atomic HelperText component.</figcaption></figure><p>Atoms serve a single function and can be reused across different components, promoting consistency throughout the design system. For instance, a button atom might be styled in one place and used across various pages without needing to redefine its properties each time.</p><h4>2. Molecules</h4><p>Molecules are combinations of two or more atoms that form a more complex component. They encapsulate functionality and can be reused in various contexts. Examples include:</p><ul><li>A card component that combines an image atom with text atoms.</li><li>A search form made up of an input atom and a button atom.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*V5g0FcEoInRmJjXYk7Rx8A.png" /><figcaption>Molecule component example, combining Input, Label, Helper, and Button.</figcaption></figure><p>Molecules not only enhance functionality but also maintain the flexibility of individual atoms, allowing for easy updates and modifications.</p><h4>3. Organisms</h4><p>Organisms are relatively complex components that consist of groups of molecules and/or atoms functioning together as a cohesive unit. They can stand alone and often represent distinct sections of an interface. Examples include:</p><ul><li>A website header that combines a logo (<em>atom</em>), navigation links (<em>molecules</em>), and possibly a search form (<em>molecule</em>).</li><li>A Form that includes a button (<em>atom</em>), and input field (<em>molecules</em>).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*swr5xWZEmp0DFeJEfMLT-w.png" /><figcaption>Organism that are made of 2 organism fields component and 1 atomic button component.</figcaption></figure><p>Organisms help in structuring the interface while ensuring that all parts work harmoniously together.</p><h4>4. Templates</h4><p>Templates are comprised of groups of organisms arranged in a layout that defines the overall structure of a page without including specific content. They serve as blueprints for pages, showcasing how various components interact with one another.</p><p>In template usually serves as a <em>Dumb Component</em>, there will be no actual data displayed on the template component. For example:</p><ul><li>A article list page template might include a header (<em>organism</em>), a article list (<em>organism</em>), filtering (<em>molecule</em>) and a footer (<em>organism)</em>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*b92N2iYjMd7MIz8d.jpg" /><figcaption>Image Credit to: snowball.digital</figcaption></figure><p>Templates facilitate consistency across different pages while allowing for variations in content.</p><h4>5. Pages</h4><p>Pages are the final level in Atomic Design, representing specific instances of templates filled with real content. They showcase how the design system comes to life with actual data, providing insight into how users will interact with the interface.</p><p>Pages act as a <em>Smart Component </em>in which they will fetch and pass the actual data to be displayed from the template component. For instance:</p><ul><li>A filled-out article list page would display the header, filtering, footer, and article list with actual data displayed.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hDxxmiG06xEChSL2.jpg" /><figcaption>Image Credit to: snowball.digital</figcaption></figure><p>Pages help in assessing the effectiveness of the design system by demonstrating how well components work together in practice.</p><h3>Benefits of Atomic Design</h3><p>The Atomic Design methodology offers several advantages:</p><ul><li><strong>Consistency</strong>: By reusing atoms across molecules and organisms, designers ensure visual coherence.</li><li><strong>Efficiency</strong>: Changes made to an atom automatically propagate through all instances where it is used.</li><li><strong>Scalability</strong>: The hierarchical structure allows teams to easily expand their design systems as new components are needed.</li><li><strong>Collaboration</strong>: Clear definitions of components enhance communication between designers and developers, streamlining workflows.</li></ul><h3>Conclusion</h3><p>Atomic Design provides a robust framework for building user interfaces by emphasizing modularity and reusability. By understanding the relationships between <em>atoms</em>, <em>molecules</em>, <em>organisms</em>, <em>templates</em>, and <em>pages</em>, teams can create cohesive designs that enhance user experience while simplifying development processes. This methodology not only fosters creativity but also ensures that digital products meet modern usability standards effectively.</p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://x.com/inPlainEngHQ"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60b0d2a94cc3" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/mastering-atomic-design-a-step-by-step-guide-to-building-scalable-ui-components-60b0d2a94cc3">Mastering Atomic Design: A Step-by-Step Guide to Building Scalable UI Components</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Hooks in React]]></title>
            <link>https://medium.com/@m.faiznoeris/introduction-to-hooks-in-react-7c9f7026e8bc?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c9f7026e8bc</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functional-component]]></category>
            <category><![CDATA[usestate]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 02:15:39 GMT</pubDate>
            <atom:updated>2024-10-17T02:15:39.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*efd0P3VzJK6eUBeS" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hooks are a powerful feature introduced in <a href="https://github.com/facebook/react/blob/main/CHANGELOG.md#1680-february-6-2019">React 16.8</a> (February 6, 2019). Allowing developers to use state and other React features in <em>functional components</em> without the need for <em>class components</em>. This innovation simplifies the development process and enhances code readability and maintainability.</p><h3>The Need for Hooks</h3><h4>Before Hooks</h4><p>Prior to the introduction of hooks, <em>functional components</em> were limited in functionality, unable to manage state or lifecycle events. Developers had to rely on class components for these capabilities, which often led to increased complexity and less maintainable code. This limitation made it challenging for beginners and even experienced developers to manage component behavior effectively.</p><h4>After Hooks</h4><p>With hooks,<em> functional components</em> can now manage state and lifecycle methods directly, eliminating the need for<em> class components</em> in many scenarios. This shift has made it easier to write cleaner and more understandable code, encouraging the use of functional programming paradigms within React.</p><h3>Commonly Used Hooks</h3><p>React provides several built-in hooks that serve various purposes:</p><ul><li><strong>useState</strong></li></ul><p>Allows you to add state to functional components. It returns a stateful value and a function to update it</p><pre>const [count, setCount] = useState(0);</pre><ul><li><strong>useEffect</strong></li></ul><p>Manages side effects in <em>functional components</em>, similar to lifecycle methods like componentDidMount and componentWillUnmount. It can be used for data fetching, subscriptions, etc.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>const DataFetcher = () =&gt; {<br>    const [data, setData] = useState([]);<br><br>    useEffect(() =&gt; {<br>        fetch(&#39;https://api.example.com/data&#39;)<br>            .then(res =&gt; res.json())<br>            .then(data =&gt; setData(data));<br>    }, []); // Empty array means this effect runs once after the first render<br><br>    return (<br>        &lt;ul&gt;<br>            {data.map(item =&gt; (<br>                &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>            ))}<br>        &lt;/ul&gt;<br>    );<br>};<br><br>export default DataFetcher;</pre><ul><li><strong>useContext</strong></li></ul><p>Returns the current value of a context, allowing you to access global data without prop drilling.</p><pre>import React, { useContext } from &#39;react&#39;;<br><br>const ThemeContext = React.createContext(&#39;light&#39;);<br><br>const ThemedComponent = () =&gt; {<br>    const theme = useContext(ThemeContext);<br>    <br>    return &lt;div className={`theme-${theme}`}&gt;Current theme is {theme}&lt;/div&gt;;<br>};<br><br>export default ThemedComponent;</pre><ul><li><strong>useReducer</strong></li></ul><p>An alternative to useState for managing complex state logic by using reducers.</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>const initialState = { count: 0 };<br><br>const reducer = (state, action) =&gt; {<br>    switch (action.type) {<br>        case &#39;increment&#39;:<br>            return { count: state.count + 1 };<br>        case &#39;decrement&#39;:<br>            return { count: state.count - 1 };<br>        default:<br>            throw new Error();<br>    }<br>}<br><br>const CounterWithReducer = () =&gt; {<br>    const [state, dispatch] = useReducer(reducer, initialState);<br><br>    return (<br>        &lt;div&gt;<br>            Count: {state.count}<br>            &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39; })}&gt;+&lt;/button&gt;<br>            &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;-&lt;/button&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default CounterWithReducer;</pre><ul><li><strong>useCallback</strong></li></ul><p>Returns a memoized version of a callback function, preventing unnecessary re-renders of child components.</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>const ChildComponent = React.memo(({ onClick }) =&gt; {<br>    console.log(&quot;Child rendered&quot;);<br>    return &lt;button onClick={onClick}&gt;Click me&lt;/button&gt;;<br>});<br><br>const ParentComponent = () =&gt; {<br>    const [count, setCount] = useState(0);<br><br>    const handleClick = useCallback(() =&gt; {<br>        console.log(&#39;Button clicked&#39;);<br>    }, []); // Memoized function will not change unless dependencies change<br><br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>            &lt;ChildComponent onClick={handleClick} /&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment Count&lt;/button&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default ParentComponent;</pre><p>In this example, the handleClick function is memoized. The ChildComponent will only re-render when the ParentComponent&#39;s state changes (in this case, when the count is incremented), not when the button is clicked.</p><ul><li><strong>useMemo</strong></li></ul><p>Returns a memoized value that optimizes performance by recomputing only when dependencies change.</p><pre>import React, { useState, useMemo } from &#39;react&#39;;<br><br>const ExpensiveComputation = ({ number }) =&gt; {<br>    const computeFactorial = (n) =&gt; {<br>        console.log(&#39;Computing factorial...&#39;);<br>        return n &lt;= 0 ? 1 : n * computeFactorial(n - 1);<br>    };<br><br>    const factorial = useMemo(() =&gt; computeFactorial(number), [number]);<br><br>    return &lt;h2&gt;Factorial of {number} is {factorial}&lt;/h2&gt;;<br>};<br><br>const MemoExample = () =&gt; {<br>    const [count, setCount] = useState(0);<br>    const [number, setNumber] = useState(1);<br><br>    return (<br>        &lt;div&gt;<br>            &lt;ExpensiveComputation number={number} /&gt;<br>            &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Count: {count}&lt;/button&gt;<br>            &lt;input<br>                type=&quot;number&quot;<br>                value={number}<br>                onChange={(e) =&gt; setNumber(Number(e.target.value))}<br>            /&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>export default MemoExample;</pre><p>In this example, the factorial of a number is computed using an expensive recursive function. The result is memoized with useMemo, so the computation only occurs when the number changes. The component will re-render when the count is incremented, but it won&#39;t recompute the factorial unless the input number changes.</p><ul><li><strong>useRef</strong></li></ul><p>Provides a mutable ref object that persists for the full lifetime of the component, useful for accessing DOM elements directly.</p><pre>import React, { useRef, useEffect } from &#39;react&#39;;<br><br>const FocusInput = () =&gt; {<br>    const inputRef = useRef(null);<br><br>    useEffect(() =&gt; {<br>        inputRef.current.focus(); // Focus the input element on mount<br>    }, []);<br><br>    return &lt;input ref={inputRef} type=&quot;text&quot; placeholder=&quot;Focus me on load&quot; /&gt;;<br>};<br><br>export default FocusInput;</pre><h3>Creating Custom Hooks</h3><p>Custom hooks allow developers to extract component logic into reusable functions. A custom hook is simply a JavaScript function whose name starts with “use” and may call other hooks. For example:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br><br>const useFriendStatus = (friendID) =&gt; {<br>    const [isOnline, setIsOnline] = useState(null);<br><br>    useEffect(() =&gt; {<br>        const handleStatusChange = (status) =&gt; {<br>            setIsOnline(status.isOnline);<br>        };<br><br>        ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange);<br>        <br>        return () =&gt; {<br>            ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange);<br>        };<br>    }, [friendID]);<br><br>    return isOnline;<br>}<br><br>export default useFriendStatus;</pre><p>In this example, useFriendStatus encapsulates the logic for managing a friend&#39;s online status, making it reusable across different components.</p><h3>Conclusion</h3><p>Hooks have transformed how developers approach building applications with React by enabling them to manage state and side effects within functional components. This leads to cleaner code and promotes the reuse of logic through custom hooks.</p><p>As React continues to evolve, understanding hooks will be essential for any developer working with this popular library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c9f7026e8bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Arrow Functions in JavaScript, Node.js, and React]]></title>
            <link>https://medium.com/@m.faiznoeris/understanding-arrow-functions-in-javascript-node-js-and-react-64d15a9e36eb?source=rss-f3df4fcd5346------2</link>
            <guid isPermaLink="false">https://medium.com/p/64d15a9e36eb</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[curried-function]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Faiz Noeris]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 06:57:05 GMT</pubDate>
            <atom:updated>2024-10-14T11:10:16.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aYzyCM23zUcJDpp0" /><figcaption>Photo by <a href="https://unsplash.com/@jannerboy62?utm_source=medium&amp;utm_medium=referral">Nick Fewings</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Arrow functions, introduced in ES6, provide a concise syntax for writing function expressions. They are particularly useful in JavaScript environments such as Node.js and frameworks like React. This article explores their implementation, benefits, and best practices across these platforms.</p><h3>Syntax and Basic Usage</h3><p>Arrow functions simplify the syntax of traditional functions. Here’s how they differ:</p><ul><li><strong>Traditional Function</strong>:</li></ul><pre>function add(a, b) {<br>    return a + b;<br>}</pre><ul><li><strong>Arrow Function</strong>:</li></ul><pre>const add = (a, b) =&gt; a + b;</pre><p>In cases with a single parameter, parentheses can be omitted:</p><pre>const square = x =&gt; x * x;</pre><h3>Lexical `this` Binding</h3><p>One of the key features of arrow functions is their handling of the this keyword. Unlike regular functions that bind this based on the calling context, arrow functions lexically bind this to the surrounding context. This is particularly beneficial in React components where event handlers are used.</p><h4>Example in React:</h4><pre>class MyComponent extends React.Component {<br>    state = { message: &#39;Hello!&#39; };<br><br>    showMessage = () =&gt; {<br>        alert(this.state.message); // `this` refers to MyComponent<br>    };<br><br>    render() {<br>        return &lt;button onClick={this.showMessage}&gt;Show Message&lt;/button&gt;;<br>    }<br>}</pre><p>In this example, using an arrow function eliminates the need for explicit binding in the constructor.</p><h4>Example inside an Object:</h4><pre>const object = {<br>  val: &#39;1&#39;,<br>  objectFunction: () =&gt; {<br>    console.log(this) // return undefined <br>  },<br>  traditionalFunction: function() {<br>    function insideFunction() {<br>      console.log(this) // refers to &#39;window&#39; object<br>    }<br><br>    console.log(this) // refers to &#39;object&#39;<br>  }<br>}</pre><p>In another example, the difference between <strong>Arrow Function</strong> and <strong>Traditional Function</strong> is that when you create the function inside an object, ‘this’ become irrelevant when using <strong>Arrow Function</strong>, meanwhile, using <strong>Traditional Function</strong> will refer to the its object.</p><h3>Curried Function</h3><p>Currying is a functional programming technique where a function takes multiple arguments one at a time. Instead of taking all arguments at once, it returns a new function that takes the next argument.</p><h4>Example of a Curried Function:</h4><pre>const multiply = a =&gt; b =&gt; a * b;<br><br>const double = multiply(2); // Returns a function that multiplies by 2<br>console.log(double(5)); // Outputs: 10</pre><p>In this example, multiply is a curried function that first takes one argument (a) and then returns another function that takes the second argument (b). This allows for partial application of functions.</p><h3>Use Cases in React</h3><p>Arrow functions are commonly used in various scenarios within React:</p><ul><li><strong>Event Handlers</strong>: They allow for cleaner syntax without worrying about binding.</li></ul><pre>&lt;button onClick={() =&gt; console.log(&#39;Button clicked!&#39;)}&gt;Click Me&lt;/button&gt;</pre><ul><li><strong>Functional Components</strong>: Arrow functions can define stateless components succinctly.</li></ul><pre>const Greeting = () =&gt; &lt;h1&gt;Hello, React!&lt;/h1&gt;;</pre><ul><li><strong>Passing Callbacks</strong>: When passing functions as props, arrow functions help maintain the correct context.</li></ul><pre>&lt;ChildComponent onClick={() =&gt; this.handleClick()} /&gt;Using Curried Functions: Currying can be useful for creating reusable logic.</pre><ul><li><strong>Using Curried Functions</strong>: Currying can be useful for creating reusable logic.</li></ul><pre>const greet = greeting =&gt; name =&gt; `${greeting}, ${name}!`;<br><br>const sayHello = greet(&#39;Hello&#39;);<br><br>console.log(sayHello(&#39;Alice&#39;)); // Outputs: Hello, Alice!</pre><h3>Benefits of Using Arrow Functions</h3><ul><li><strong>Conciseness</strong>: Reduces boilerplate code, making it easier to read and write.</li><li><strong>Lexical Scoping</strong>: Automatically binds this, reducing errors related to context.</li><li><strong>Improved Readability</strong>: Simplifies the syntax for inline functions and event handlers.</li><li><strong>Reusability</strong>: Currying allows for more flexible and reusable code by enabling partial application of functions.</li></ul><h3>Considerations and Limitations</h3><p>While arrow functions offer many advantages, there are scenarios where their use may not be appropriate:</p><ul><li><strong>Class Methods</strong>: Avoid using arrow functions for lifecycle methods or methods that require access to the component instance (like render()).</li><li><strong>Performance Concerns</strong>: In certain cases (e.g., rendering lists), using arrow functions directly in JSX can lead to performance issues due to unnecessary re-renders.</li></ul><h3>Conclusion</h3><p>Arrow functions are a powerful feature in JavaScript that enhance code readability and maintainability, especially within frameworks like React. By understanding their syntax and behavior — particularly regarding this binding—developers can leverage them effectively in their applications. However, it&#39;s essential to recognize when traditional function expressions might be more suitable to avoid potential pitfalls related to context and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64d15a9e36eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>