<?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 Muhammad Aryandi on Medium]]></title>
        <description><![CDATA[Stories by Muhammad Aryandi on Medium]]></description>
        <link>https://medium.com/@aryandi?source=rss-e7edc030bb68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*utk3fVczfWyKVk2GJMTSaQ.jpeg</url>
            <title>Stories by Muhammad Aryandi on Medium</title>
            <link>https://medium.com/@aryandi?source=rss-e7edc030bb68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 07:19:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aryandi/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[Optimizing Performance and Enhancing Responsiveness in React Applications with useCallback and…]]></title>
            <link>https://medium.com/@aryandi/optimizing-performance-and-enhancing-responsiveness-in-react-applications-with-usecallback-and-4cbaac7dcc4b?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cbaac7dcc4b</guid>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Thu, 28 Sep 2023 09:55:13 GMT</pubDate>
            <atom:updated>2023-09-28T09:55:13.483Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing Performance and Enhancing Responsiveness in React Applications with useCallback and useMemo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5JunhjdkYQjNLGMoQabdaA.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/m_HRfLhgABo">https://unsplash.com/photos/m_HRfLhgABo</a></figcaption></figure><p>In the realm of web development, React has emerged as a leading JavaScript library for building interactive user interfaces. Before we dive into the specifics of how to optimize React applications with <strong><em>useCallback</em></strong> and <strong><em>useMemo</em></strong>, let’s lay the foundation by understanding the fundamental principles.</p><h4><strong>Let’s wrap up! How React Works</strong></h4><p>At its core, React operates on the concept of a Virtual DOM (Document Object Model). When you create a React application, you’re essentially building a virtual representation of your UI. React then takes care of efficiently updating the real DOM to reflect any changes in this virtual representation.</p><p>This virtual-real DOM interplay allows React to minimize the actual manipulation of the browser’s DOM, which can be a slow and resource-intensive process. By optimizing this process, React ensures a smoother user experience and improved application performance.</p><h3>The Importance of Performance and Responsiveness</h3><p>In today’s digital landscape, performance and responsiveness are paramount. Users expect web applications to load quickly, respond swiftly to interactions, and provide a seamless experience across devices. Any delays or lag can lead to user frustration and, ultimately, a high bounce rate.</p><p>As developers, it’s our responsibility to craft applications that meet these expectations. This is where React’s <strong><em>useCallback</em></strong> and <strong><em>useMemo</em></strong> hooks come into play. They offer tools to fine-tune the performance of your React components, ensuring that your application remains snappy and responsive.</p><h4><strong>What is useCallback, and Why Do You Need It?</strong></h4><p>Before we delve into the mechanics of <strong><em>useCallback</em></strong>, let’s establish its purpose. In React, components often include event handlers, functions that respond to user interactions like button clicks, form submissions, or mouse movements. These event handlers can be resource-intensive, especially in larger applications.</p><p><strong><em>useCallback</em></strong> is a React hook designed to address this challenge. It’s all about optimizing the performance of your components by memoizing event handler functions. Memoization is the process of storing the results of expensive function calls and returning the cached result when the same inputs occur again. By memoizing event handlers with <strong><em>useCallback</em></strong>, you can reduce the overhead of recreating functions on every render.</p><h4>How to Use it to Memoize Event Handler Functions</h4><p>Using <strong><em>useCallback</em></strong> is straightforward. You wrap your event handler function inside it, and it returns a memoized version of that function. Here’s a basic example:</p><pre>import React, { useCallback } from &#39;react&#39;;<br><br>const SampleComponent = ({ data }) =&gt; {<br>  const handleClick = useCallback(() =&gt; {<br>    // Your event handling logic here<br>  }, []); // Empty dependency array means no dependencies<br><br>  return (<br>    &lt;button onClick={handleClick}&gt;Click Me&lt;/button&gt;<br>  );<br>}</pre><p>In this example, the handleClick function is memoized using <strong><em>useCallback</em></strong>. The empty dependency array <strong><em>([])</em></strong> indicates that this function has no dependencies, so it won’t be recreated on subsequent renders unless the component itself is recreated.</p><h4>Simple Implementation Examples and Their Impact on Component Rendering</h4><p>Let’s consider a scenario where you have a list of items, and clicking on each item toggles its selection state. Without <strong><em>useCallback</em></strong>, you might write an event handler like this:</p><pre>function toggleItemSelection(item) {<br>  // Your logic to toggle item selection<br>}</pre><p>Each time this component re-renders, a new <strong><em>toggleItemSelection</em></strong> function is created, even if its dependencies (e.g., the item parameter) haven’t changed. This can lead to unnecessary re-renders and negatively impact performance.</p><p>With <strong><em>useCallback</em></strong>, you can optimize this scenario:</p><pre>const toggleItemSelection = useCallback((item) =&gt; {<br>  // Your logic to toggle item selection<br>}, []);</pre><p>By providing an empty dependency array, you ensure that <strong><em>toggleItemSelection</em></strong> remains the same between renders as long as the component itself doesn’t change. This optimization can significantly improve your application’s responsiveness, especially in components with complex logic and many event handlers.</p><h4>Choosing the Right Moments for useCallback</h4><p>Now that we’ve explored the ins and outs of <strong><em>useCallback</em></strong>, let’s dive into the pivotal question:</p><blockquote>When should you use it in your React projects?</blockquote><p>The answer lies in understanding its benefits and recognizing scenarios where it can make a substantial impact on your application’s performance and responsiveness.</p><p><strong><em>useCallback</em></strong> plays a crucial role in optimizing the performance of your React components, primarily by reducing unnecessary re-renders. But when does this optimization matter the most?</p><ol><li><strong>Event Handlers<br></strong>One of the most common use cases for useCallback is with event handlers. When you have components that rely on event listeners, such as button clicks, form submissions, or keyboard interactions, using useCallback can prevent the recreation of event handler functions on every render. This results in a more responsive user interface.</li><li><strong>Memoization of Expensive Functions<br></strong>Any function that performs complex calculations or fetches data from an external source can benefit from useCallback. By memoizing these functions, you ensure that they’re recalculated only when their dependencies change. This prevents redundant computations and enhances the overall efficiency of your application.</li></ol><h4>Case Studies and Appropriate Usage Examples</h4><p>To illustrate the impact of <strong><em>useCallback</em></strong>, let’s consider a couple of case studies:</p><p><strong>Case Study 1: Dynamic Lists</strong></p><p>Imagine you’re building a to-do list application where users can add, edit, and delete tasks. Each task item has its event handlers for interactions like editing or deleting. Without <strong><em>useCallback</em></strong>, these event handlers would be recreated whenever the list re-renders, even if the tasks themselves remain unchanged.</p><p>By wrapping these event handlers with <strong><em>useCallback</em></strong>, you ensure that they stay consistent between renders as long as the list structure doesn’t change. This optimization keeps your list responsive, even with a large number of tasks.</p><pre>const handleEditTask = useCallback((taskId) =&gt; {<br>  // Simulate editing a task by updating its status<br>  const updatedTasks = tasks.map((task) =&gt; {<br>    if (task.id === taskId) {<br>      return { ...task, status: &#39;edited&#39; };<br>    }<br>    return task;<br>  });<br><br>  // Update the tasks in the component state<br>  setTasks(updatedTasks);<br>}, [tasks, setTasks]);</pre><p>In this code, we have a <strong><em>handleEditTask</em></strong> function that takes a <em>taskId</em> as an argument. When called, it simulates editing a task in a to-do list by changing its status to <em>‘edited’</em>. The function updates the tasks in the component’s state, ensuring that the edited task remains consistent between renders as long as the list’s structure doesn’t change.</p><p>The <strong><em>useCallback</em></strong> is used here with the <strong><em>tasks</em></strong> and <strong><em>setTasks</em></strong> dependencies. It memoizes the <strong><em>handleEditTask</em></strong> function, preventing it from being recreated on each render when tasks and setTasks remain the same.</p><p><strong>Case Study 2: Data Fetching</strong></p><p>In a scenario where you fetch data from an API, you might have a function responsible for making API requests. Without memoization, this function would be recreated with each render, leading to unnecessary network requests.</p><p>By using <strong><em>useCallback</em></strong> in conjunction with <strong><em>useEffect</em></strong>, you can ensure that the data fetching function remains stable unless the dependencies, like query parameters, change.</p><pre>const fetchData = useCallback(async (query) =&gt; {<br>  try {<br>    // Simulate fetching data from an API<br>    const response = await fetch(`https://api.example.com/data?query=${query}`);<br>    const data = await response.json();<br><br>    // Handle the fetched data<br>    console.log(data);<br>  } catch (error) {<br>    // Handle errors<br>    console.error(error);<br>  }<br>}, []);<br><br>useEffect(() =&gt; {<br>  // Query comes from another input<br>  const query = &#39;your-query-value&#39;; // Example of the Query input<br>  fetchData(query);<br>}, [fetchData]);</pre><p>In this code, we have a <strong><em>fetchData</em></strong> function that takes a query parameter. When called, it simulates fetching data from an API using the provided query parameter. The function uses the fetch API to make the request and then handles the response by logging the data to the console.</p><p>The <strong><em>useCallback</em></strong> hook is used here with an empty dependency array (<strong><em>`[]`</em></strong>). This means that the <strong><em>fetchData</em></strong> function will remain stable between renders as long as there are no dependencies that change. This optimization prevents unnecessary recreations of the data fetching function on each render.</p><h4>The Balancing Act of useCallback</h4><p>While <strong><em>useCallback</em></strong> is a valuable tool in optimizing React components, there are scenarios where its excessive use can lead to unnecessary complexity. Let’s explore when it’s advisable to avoid going overboard with <strong><em>useCallback</em></strong> and understand the real benefits it offers.</p><h4><strong>Avoiding Excessive Use</strong></h4><ol><li><strong>Simple Event Handlers</strong></li></ol><p>If your event handlers are exceptionally simple and don’t rely on any external dependencies or computations, applying <strong><em>useCallback</em></strong> might be excessive. React’s built-in optimization mechanisms can efficiently handle such cases without the need for memoization.</p><pre>// Avoid excessive useCallback for simple event handlers<br>const handleButtonClick = () =&gt; {<br>  // Simple logic here<br>};</pre><p><strong>2. Components with Rare Re-Renders</strong></p><p>In some components, re-renders are infrequent, and the performance gains from <strong><em>useCallback</em></strong> might not be noticeable. In these cases, optimizing event handlers with <strong><em>useCallback</em></strong> may not provide substantial benefits.</p><p><strong>3. Maintainability</strong></p><p>Excessive use of <strong><em>useCallback</em></strong> can make your codebase harder to maintain. If every event handler is memoized, it might be challenging for other developers (or even your future self) to understand the purpose and flow of the code.</p><h4>Complexity and Real Benefits</h4><p>It’s essential to recognize that the complexity introduced by <strong><em>useCallback</em></strong> should be justified by tangible performance improvements. In simpler components or scenarios where re-renders are infrequent, the benefits of memoization might not outweigh the added code complexity.</p><p>Real benefits of <strong><em>useCallback</em></strong> shine when:</p><ul><li>You have a substantial number of components or a deep component tree, leading to frequent re-renders.</li><li>Event handlers rely on expensive computations or external dependencies.</li><li>Your application experiences responsiveness issues during interactions.</li></ul><h4>What is useMemo, and Why Do You Need It?</h4><p>In the world of React optimization, <strong><em>useMemo</em></strong> is a powerful tool that can help you take control of complex computations and optimize your components’ rendering process. But what exactly is <strong><em>useMemo</em></strong>, and why should you consider using it?</p><p>At its core, <strong><em>useMemo</em></strong> is a hook that allows you to memoize the results of expensive computations and store them for later use. Memoization, in this context, means caching the results of a function call based on its dependencies. By doing so, React can skip the re-computation of expensive operations on every render, which can significantly boost the performance of your application.</p><h4>How to Use it to Compute and Store Computation Results</h4><p>Using <strong><em>useMemo</em></strong> is relatively straightforward. You wrap your computationally intensive function inside it, and it returns the memoized result of that function. Here’s a basic example:</p><pre>import React, { useMemo } from &#39;react&#39;;<br><br>const SampleComponent =({ data }) =&gt; {<br>  const complexCalculation = useMemo(() =&gt; {<br>    // Your computationally expensive logic here<br>    return result;<br>  }, [data]); // Dependency array: recompute if &#39;data&#39; changes<br><br>  return (<br>    &lt;div&gt;{complexCalculation}&lt;/div&gt;<br>  );<br>}</pre><p>In this example, <strong><em>complexCalculation</em></strong> is computed using <strong><em>useMemo</em></strong>. The dependency array <em>[data]</em> specifies that if the data prop changes, the computation should be recomputed. Otherwise, the memoized result will be reused, improving performance by avoiding unnecessary calculations.</p><h4>Complex Implementation Examples with Computationally Expensive Calculations</h4><p>Let’s explore a scenario where <strong><em>useMemo</em></strong> shines. Imagine you’re building a data visualization component that processes a large dataset and generates a chart. Without memoization, the chart generation logic could be taxing on your application’s performance, especially if the data remains unchanged.</p><p>With useMemo, you can optimize this process:</p><pre>const chartData = useMemo(() =&gt; {<br>  // Complex data processing and chart generation logic<br>  return processedData;<br>}, [data]); // Recompute if &#39;data&#39; changes</pre><p>Here, the chart data is computed using <strong><em>useMemo</em></strong>. As long as the data prop remains the same, the expensive data processing and chart generation will only occur when necessary.</p><h4>Identifying Appropriate Use Cases</h4><p>1. Expensive Calculations</p><p><strong><em>useMemo</em></strong> is particularly beneficial when your components involve complex and resource-intensive calculations. If you have computations that are time-consuming or involve substantial data processing, consider using <strong><em>useMemo</em></strong> to cache results.</p><pre>// Using useMemo to cache the result of a costly computation<br>const expensiveResult = useMemo(() =&gt; {<br>  // Perform expensive calculations here<br>  return result;<br>}, [dependency1, dependency2]);</pre><p>2. Large Datasets</p><p>When working with large datasets or lists, <strong><em>useMemo</em></strong> can prevent unnecessary recalculations. For instance, if you’re filtering, sorting, or transforming data based on user interactions, caching the result can significantly enhance performance.</p><h4>Performance Benefits</h4><p>By memoizing values with <strong><em>useMemo</em></strong>, you prevent React from recomputing them on every render. This optimization reduces CPU and memory usage, resulting in a smoother and more responsive user experience, especially in components where calculations can be intensive.</p><h4>Case Studies and Usage Examples</h4><p><strong>Case Study 1: Dynamic Data Filtering</strong></p><p>Imagine you’re building a data-intensive application with dynamic filtering options. Users can apply various filters to a large dataset of products. Without <strong><em>useMemo</em></strong>, each filter change would recompute the filtered dataset from scratch, causing unnecessary delays.</p><p>By using <strong><em>useMemo</em></strong>, you can cache the filtered dataset based on user-selected filters. This ensures that only the necessary calculations are performed when filters change, leading to a more responsive application.</p><pre>const filteredData = useMemo(() =&gt; {<br>  // Filter data based on user-selected filters<br>  return filterData(data, filters);<br>}, [data, filters]);</pre><p><strong>Case Study 2: Expensive Chart Rendering</strong></p><p>In a dashboard application, you’re rendering complex data visualizations, like interactive charts. Calculating and rendering these charts can be computationally expensive. <strong><em>useMemo</em></strong> helps by caching the chart data and configuration, avoiding redundant calculations during rendering.</p><pre>const chartData = useMemo(() =&gt; {<br>  // Calculate and format chart data here<br>  return prepareChartData(data, chartConfig);<br>}, [data, chartConfig]);</pre><p>In these scenarios, <strong><em>useMemo</em></strong> significantly enhances performance, making your React application more efficient and user-friendly.</p><h4>When to Avoid Excessive Use of useMemo</h4><p>While <strong><em>useMemo</em></strong> is a valuable tool for performance optimization, there are scenarios where excessive use of it might not be necessary or may even lead to unnecessary complexity. Let’s explore when it’s advisable to avoid overusing <strong><em>useMemo</em></strong> and understand the nuances of simple and complex calculations.</p><h4>Identifying Suitable Use Cases</h4><p><strong>1. Simple Calculations</strong></p><p>For straightforward calculations that are not resource-intensive and don’t significantly impact performance, using <strong><em>useMemo</em></strong> might be overkill. React’s default rendering behavior is already efficient for handling such scenarios.</p><pre>// Avoid excessive use of useMemo for simple calculations<br>const result = useMemo(() =&gt; {<br>  return a + b;<br>}, [a, b]);</pre><p><strong>2. Frequent Updates</strong></p><p>If your data or dependencies change frequently, employing <strong><em>useMemo</em></strong> for every calculation can lead to a proliferation of memoized values. This can increase memory usage and introduce unnecessary complexity.</p><pre>// Using useMemo for calculating price change percentage<br>const priceChangePercentage = useMemo(() =&gt; {<br>  if (previousPrice === 0) return 0; // Avoid division by zero<br>  return ((currentPrice - previousPrice) / previousPrice) * 100;<br>}, [currentPrice, previousPrice]);<br><br>// Using useMemo for formatting the current price<br>const formattedPrice = useMemo(() =&gt; {<br>  return `$${currentPrice.toFixed(2)}`;<br>}, [currentPrice]);</pre><p>In the provided code snippets, <strong><em>useMemo</em></strong> is used to optimize the calculation of the price change percentage and the formatting of the current price within a React component. This optimization is valuable when dealing with frequently changing data.</p><p>For <strong><em>priceChangePercentage</em></strong>, it ensures that the calculation is performed only when the dependencies (<strong><em>currentPrice</em></strong> and <strong><em>previousPrice</em></strong>) change. This prevents unnecessary computations and division by zero errors, ultimately enhancing performance.</p><p>Similarly, for <strong><em>formattedPrice</em></strong>, <strong><em>useMemo</em></strong> efficiently formats the current price with two decimal places, recomputing it only when <strong><em>currentPrice</em></strong> changes. This memoization ensures that the formatting process doesn’t occur needlessly on every render.</p><h4>Balancing Complexity</h4><p>In some cases, the complexity introduced by excessive use of <strong><em>useMemo</em></strong> may outweigh its benefits. It’s essential to strike a balance between optimizing performance and maintaining code readability and maintainability. Keep these considerations in mind:</p><ul><li><strong>Code Readability:</strong> Excessive use of useMemo can make your code harder to understand, especially for developers who are not familiar with the codebase. Prioritize code readability and clarity.</li><li><strong>Maintenance:</strong> Memoized values can become stale if not updated correctly. Maintaining a large number of memoized values might lead to maintenance challenges.</li></ul><h4>Simple vs. Complex Calculations</h4><p>Understanding the nature of calculations is key to deciding whether to employ <strong><em>useMemo</em></strong>:</p><p><strong>Simple Calculations</strong><br>Simple calculations involve basic operations that are quick to compute, such as addition, subtraction, or simple transformations of data. React’s default behavior is efficient for these calculations.</p><pre>// Simple calculation without useMemo<br>const result = a + b;</pre><p><strong>Complex Calculations</strong><br>Complex calculations are those that require substantial processing time, involve multiple steps, or deal with large datasets. These are the scenarios where <strong><em>useMemo</em></strong> shines by preventing redundant computations.</p><pre>const expensiveResult = useMemo(() =&gt; {<br>  // Simulate a complex calculation that depends on data and factor<br>  let result = 0;<br>  for (let i = 0; i &lt; data.length; i++) {<br>    result += data[i] * factor;<br>  }<br>  // Introduce a delay to simulate a computationally expensive task<br>  const start = performance.now();<br>  while (performance.now() - start &lt; 1000) {<br>    // Simulate a delay of 1000 milliseconds (1 second)<br>  }<br>  return result;<br>}, [data, factor]);</pre><h4>Striking the Right Balance</h4><p>In practice, finding the right balance between using and avoiding useMemo depends on your specific application and performance requirements. Consider the complexity of your calculations, the frequency of updates, and the overall maintainability of your codebase.</p><p>I think that is all of my explanation. Stay tuned for more insights into optimizing your React applications!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L44Gnq1yHiOdcPcxIq1_uQ.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/VyC0YSFRDTU">https://unsplash.com/photos/VyC0YSFRDTU</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cbaac7dcc4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Belajar Struktur Data: Linked list]]></title>
            <link>https://medium.com/@aryandi/belajar-struktur-data-linked-list-115fff677253?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/115fff677253</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Tue, 23 May 2023 00:04:16 GMT</pubDate>
            <atom:updated>2023-05-23T00:04:16.069Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2fYOm5ppRTqffnAP5nvuw.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/O2MdroNurVw">https://unsplash.com/photos/O2MdroNurVw</a></figcaption></figure><p>Linked list adalah salah satu struktur data dasar dalam pemrograman. Ini adalah kumpulan elemen-elemen data yang terhubung satu sama lain melalui penggunaan referensi atau pointer. Setiap elemen dalam linked list, yang disebut node, terdiri dari dua bagian utama: data dan referensi ke node berikutnya dalam urutan.</p><p>Salah satu keunggulan utama linked list adalah kemampuannya untuk mengatasi perubahan ukuran secara dinamis. Ketika kita ingin menambahkan atau menghapus elemen dari linked list, kita dapat melakukannya dengan mudah tanpa mempengaruhi elemen-elemen lain dalam struktur data tersebut.</p><p>Dalam linked list, elemen pertama disebut head, dan elemen terakhir disebut tail. Head menyimpan referensi ke node pertama dalam linked list, sedangkan tail menyimpan referensi ke node terakhir. Jika sebuah linked list kosong, head dan tail akan memiliki nilai null atau tidak ada referensi yang valid.</p><p>Selain itu, linked list dapat dibagi menjadi dua jenis utama: linked list tunggal (singly linked list) dan linked list ganda (doubly linked list). Pada linked list tunggal, setiap node hanya memiliki referensi ke node berikutnya. Sedangkan pada linked list ganda, setiap node memiliki referensi ke node sebelumnya dan node berikutnya.</p><h3>Definisi linked list dan konsep dasar</h3><p>Linked list adalah struktur data linier yang terdiri dari sejumlah node yang saling terhubung melalui referensi atau pointer. Setiap node dalam linked list menyimpan data dan referensi ke node berikutnya. Ini berbeda dengan array, di mana elemen-elemen data disimpan secara berurutan dalam memori.</p><p>Setiap node dalam linked list terdiri dari dua komponen utama: data dan pointer. Komponen data menyimpan nilai atau informasi yang ingin kita simpan dalam linked list. Misalnya, jika kita ingin membuat linked list untuk menyimpan angka, komponen data akan menyimpan nilai angka tersebut. Sedangkan pointer menyimpan referensi atau alamat memori dari node berikutnya dalam linked list.</p><p>Node pertama dalam linked list disebut head, dan node terakhir disebut tail. Head menyimpan referensi ke node pertama, sedangkan tail menyimpan referensi ke node terakhir. Dengan menggunakan head, kita dapat mengakses elemen pertama dalam linked list dan melakukan operasi seperti penambahan, penghapusan, atau pencarian data.</p><p>Sebagai struktur data yang dinamis, linked list memungkinkan kita untuk menambahkan atau menghapus elemen dengan mudah. Ketika kita ingin menambahkan elemen baru, kita dapat membuat node baru dan mengubah referensi yang sesuai. Demikian pula, ketika kita ingin menghapus elemen, kita dapat memperbarui referensi sehingga node yang dihapus tidak lagi terhubung dalam urutan.</p><p>Linked list dapat digunakan dalam berbagai aplikasi, seperti implementasi daftar tautan, antrian, tumpukan, dan representasi struktur data seperti graph dan tree. Memahami konsep dasar linked list akan memberi Anda dasar yang kuat dalam mempelajari struktur data lain dan memecahkan masalah dengan efisien.</p><p>Untuk memahami konsep linked list secara lebih jelas, mari kita lihat ilustrasi visual bagaimana node-node terhubung satu sama lain dalam struktur data ini.</p><p>Bayangkan sebuah linked list dengan empat node: A, B, C, dan D. Setiap node memiliki dua komponen, yaitu data dan pointer ke node berikutnya. Kita dapat menggambarkan linked list ini seperti berikut:</p><pre>A -&gt; B -&gt; C -&gt; D</pre><p>Di sini, A adalah head, karena itu adalah elemen pertama dalam linked list. D adalah tail, karena itu adalah elemen terakhir dalam linked list.</p><p>Ketika kita ingin mengakses data di setiap node, kita dapat mengikuti referensi atau pointer yang terhubung. Misalnya, jika kita ingin mengakses data pada node B, kita akan mengikuti referensi dari node A ke node B.</p><p>Selain itu, kita juga dapat menambahkan dan menghapus node dalam linked list dengan mudah. Misalkan kita ingin menambahkan node E setelah node C. Untuk melakukannya, kita dapat membuat node baru dengan data E, dan mengatur referensi pada node C sehingga mengarah ke node E. Dengan demikian, kita mendapatkan linked list berikut:</p><pre>A -&gt; B -&gt; C -&gt; E -&gt; D</pre><p>Demikian pula, jika kita ingin menghapus node C, kita hanya perlu mengubah referensi pada node B sehingga mengarah langsung ke node E. Dengan demikian, node C tidak lagi terhubung dalam urutan, dan kita memiliki linked list seperti berikut:</p><pre>A -&gt; B -&gt; E -&gt; D</pre><p>Ilustrasi visual linked list ini membantu kita memahami bagaimana node-node terhubung satu sama lain dan bagaimana operasi penambahan dan penghapusan node dapat mempengaruhi struktur linked list secara keseluruhan.</p><h3>Operasi dasar pada linked list (insert, delete, search)</h3><p>Linked list menyediakan beberapa operasi dasar yang memungkinkan kita untuk memanipulasi data dalam struktur ini. Beberapa operasi dasar yang umum dilakukan pada linked list adalah operasi penambahan (insertion), penghapusan (deletion), dan pencarian (search).</p><h4><strong>Insertion (Penambahan)</strong></h4><p>Operasi penambahan memungkinkan kita untuk menyisipkan node baru ke dalam linked list. Ada beberapa metode penambahan yang umum digunakan, seperti:</p><ul><li><strong>Penambahan di awal (insert at beginning):</strong> Menambahkan node baru sebagai elemen pertama atau head dari linked list.</li><li><strong>Penambahan di akhir (insert at end): </strong>Menambahkan node baru sebagai elemen terakhir atau tail dari linked list.</li><li><strong>Penambahan di posisi tertentu (insert at position): </strong>Menambahkan node baru di antara dua node yang sudah ada, pada posisi yang ditentukan.</li></ul><h4><strong>Deletion (Penghapusan)</strong></h4><p>Operasi penghapusan memungkinkan kita untuk menghapus node dari linked list. Beberapa metode penghapusan yang umum digunakan, antara lain:</p><ul><li><strong>Penghapusan di awal (delete at beginning): </strong>Menghapus elemen pertama atau head dari linked list.</li><li><strong>Penghapusan di akhir (delete at end): </strong>Menghapus elemen terakhir atau tail dari linked list.</li><li><strong>Penghapusan di posisi tertentu (delete at position): </strong>Menghapus node pada posisi tertentu dalam linked list.</li></ul><h4><strong>Search (Pencarian)</strong></h4><p>Operasi pencarian memungkinkan kita untuk mencari data tertentu dalam linked list. Untuk melakukan pencarian, kita perlu melintasi linked list dari elemen pertama (head) hingga elemen terakhir (tail) sambil membandingkan nilai data pada setiap node.</p><p>Ketiga operasi dasar ini memungkinkan kita untuk melakukan manipulasi data dalam linked list sesuai dengan kebutuhan. Dalam implementasi linked list, penting untuk memperhatikan pembaruan referensi atau pointer untuk memastikan keterhubungan yang benar antara node-node dalam linked list.</p><p>Berikut adalah contoh kode dalam bahasa Java untuk operasi dasar pada linked list, yaitu insert, delete, dan search:</p><pre>public class LinkedList {<br>    Node head;<br><br>    // Inner class untuk merepresentasikan node dalam linked list<br>    class Node {<br>        int data;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>            next = null;<br>        }<br>    }<br><br>    // Method untuk menambahkan node di awal linked list<br>    public void insertAtBeginning(int data) {<br>        Node newNode = new Node(data);<br>        newNode.next = head;<br>        head = newNode;<br>    }<br><br>    // Method untuk menambahkan node di akhir linked list<br>    public void insertAtEnd(int data) {<br>        Node newNode = new Node(data);<br><br>        if (head == null) {<br>            head = newNode;<br>            return;<br>        }<br><br>        Node current = head;<br>        while (current.next != null) {<br>            current = current.next;<br>        }<br>        current.next = newNode;<br>    }<br><br>    // Method untuk menghapus node dari linked list<br>    public void deleteNode(int data) {<br>        Node temp = head;<br>        Node prev = null;<br><br>        if (temp != null &amp;&amp; temp.data == data) {<br>            head = temp.next;<br>            return;<br>        }<br><br>        while (temp != null &amp;&amp; temp.data != data) {<br>            prev = temp;<br>            temp = temp.next;<br>        }<br><br>        if (temp == null) {<br>            return;<br>        }<br><br>        prev.next = temp.next;<br>    }<br><br>    // Method untuk mencari node dengan nilai tertentu dalam linked list<br>    public boolean searchNode(int data) {<br>        Node current = head;<br><br>        while (current != null) {<br>            if (current.data == data) {<br>                return true;<br>            }<br>            current = current.next;<br>        }<br><br>        return false;<br>    }<br>}</pre><h3>Perbedaan antara linked list tunggal dan ganda</h3><p>Linked list memiliki dua varian utama, yaitu linked list tunggal (singly linked list) dan linked list ganda (doubly linked list). Perbedaan utama antara keduanya terletak pada jumlah pointer yang dimiliki oleh setiap node.</p><h4>Linked List Tunggal (Singly Linked List)</h4><p>Pada linked list tunggal, setiap node hanya memiliki satu pointer yang mengarah ke node berikutnya dalam urutan. Pointer ini dikenal sebagai “next” atau “next pointer”. Dengan menggunakan pointer ini, kita dapat bergerak maju melalui linked list dari elemen pertama (head) hingga elemen terakhir (tail). Namun, untuk mencari node sebelumnya dari suatu node, kita perlu melintasi linked list secara linier dari awal hingga mencapai node yang diinginkan.</p><p>Berikut adalah contoh kode dalam bahasa Java untuk linked list tunggal (singly linked list)</p><pre>public class SinglyLinkedList {<br>    Node head;<br><br>    class Node {<br>        int data;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>            next = null;<br>        }<br>    }<br><br>    // Method untuk menambahkan node di akhir linked list<br>    public void insert(int data) {<br>        Node newNode = new Node(data);<br><br>        if (head == null) {<br>            head = newNode;<br>        } else {<br>            Node current = head;<br>            while (current.next != null) {<br>                current = current.next;<br>            }<br>            current.next = newNode;<br>        }<br>    }<br><br>    // Method untuk menghapus node dengan nilai tertentu<br>    public void delete(int data) {<br>        Node temp = head;<br>        Node prev = null;<br><br>        if (temp != null &amp;&amp; temp.data == data) {<br>            head = temp.next;<br>            return;<br>        }<br><br>        while (temp != null &amp;&amp; temp.data != data) {<br>            prev = temp;<br>            temp = temp.next;<br>        }<br><br>        if (temp == null) {<br>            return;<br>        }<br><br>        prev.next = temp.next;<br>    }<br>}</pre><h4>Linked List Ganda (Doubly Linked List)</h4><p>Pada linked list ganda, setiap node memiliki dua pointer. Pointer pertama adalah “next” yang mengarah ke node berikutnya dalam urutan, sedangkan pointer kedua adalah “previous” atau “prev” yang mengarah ke node sebelumnya. Dengan menggunakan kedua pointer ini, kita dapat bergerak maju maupun mundur dalam linked list. Hal ini memungkinkan kita untuk dengan mudah mencari node sebelum dan sesudah suatu node tertentu tanpa perlu melintasi seluruh linked list.</p><p>Berikut adalah contoh kode dalam bahasa Java untuk linked list ganda (doubly linked list)</p><pre>public class DoublyLinkedList {<br>    Node head;<br><br>    class Node {<br>        int data;<br>        Node prev;<br>        Node next;<br><br>        Node(int data) {<br>            this.data = data;<br>            prev = null;<br>            next = null;<br>        }<br>    }<br><br>    // Method untuk menambahkan node di awal linked list<br>    public void insertAtBeginning(int data) {<br>        Node newNode = new Node(data);<br><br>        if (head == null) {<br>            head = newNode;<br>        } else {<br>            newNode.next = head;<br>            head.prev = newNode;<br>            head = newNode;<br>        }<br>    }<br><br>    // Method untuk menambahkan node di akhir linked list<br>    public void insertAtEnd(int data) {<br>        Node newNode = new Node(data);<br><br>        if (head == null) {<br>            head = newNode;<br>        } else {<br>            Node current = head;<br>            while (current.next != null) {<br>                current = current.next;<br>            }<br>            current.next = newNode;<br>            newNode.prev = current;<br>        }<br>    }<br><br>    // Method untuk menghapus node dengan nilai tertentu<br>    public void delete(int data) {<br>        Node temp = head;<br><br>        while (temp != null &amp;&amp; temp.data != data) {<br>            temp = temp.next;<br>        }<br><br>        if (temp == null) {<br>            return;<br>        }<br><br>        if (temp.prev != null) {<br>            temp.prev.next = temp.next;<br>        } else {<br>            head = temp.next;<br>        }<br><br>        if (temp.next != null) {<br>            temp.next.prev = temp.prev;<br>        }<br>    }<br>}</pre><p>Perbedaan ini membawa konsekuensi pada implementasi dan kompleksitas operasi pada linked list. Linked list ganda memerlukan penggunaan memori yang lebih besar karena setiap node menyimpan dua pointer. Namun, keuntungan dari linked list ganda adalah kemampuan untuk bergerak maju dan mundur dengan mudah, serta kemudahan dalam melakukan operasi penghapusan dan penambahan di berbagai posisi dalam linked list.</p><p>Pemilihan antara linked list tunggal dan ganda tergantung pada kebutuhan dan skenario penggunaan. Jika kita hanya memerlukan pergerakan maju dalam linked list dan tidak membutuhkan akses mundur, maka linked list tunggal sudah cukup. Namun, jika kita seringkali membutuhkan akses maju dan mundur, serta operasi penghapusan dan penambahan yang kompleks, maka linked list ganda dapat menjadi pilihan yang lebih sesuai.</p><h4>Keuntungan dan Kerugian Menggunakan Linked List</h4><p>Linked list merupakan salah satu struktur data yang memiliki kelebihan dan kekurangan tertentu. Memahami keuntungan dan kerugian penggunaan linked list dapat membantu kita dalam memilih struktur data yang tepat untuk kebutuhan kita. Berikut ini adalah beberapa keuntungan dan kerugian menggunakan linked list:</p><p><strong>Keuntungan:</strong></p><ol><li><strong>Fleksibilitas dalam Penambahan dan Penghapusan Elemen: </strong>Linked list memungkinkan penambahan dan penghapusan elemen dengan mudah. Kita dapat menambahkan atau menghapus elemen di tengah-tengah linked list tanpa harus memindahkan elemen-elemen lainnya. Hal ini membuat linked list menjadi pilihan yang baik dalam situasi di mana operasi penambahan atau penghapusan sering dilakukan.</li><li><strong>Dinamis dalam Ukuran: </strong>Linked list memiliki ukuran dinamis, yang berarti kita dapat menambahkan atau menghapus elemen sesuai kebutuhan tanpa batasan ukuran yang tetap. Ini memungkinkan pengelolaan memori yang efisien dan menghindari pemborosan memori.</li><li><strong>Efisiensi pada Operasi Pengecekan Kedekatan: </strong>Linked list cocok digunakan dalam situasi di mana operasi pengecekan kedekatan elemen diperlukan. Misalnya, pada implementasi stack atau queue, pengecekan elemen teratas atau elemen depan dapat dilakukan dengan efisien menggunakan linked list.</li></ol><p><strong>Kerugian:</strong></p><ol><li><strong>Akses Acak yang Lambat: </strong>Linked list memiliki keterbatasan dalam melakukan akses acak terhadap elemen. Untuk mencapai elemen di indeks tertentu, kita harus mengunjungi setiap elemen dari awal linked list. Hal ini membuat operasi akses acak pada linked list menjadi lebih lambat dibandingkan dengan struktur data seperti array.</li><li><strong>Memerlukan Memori Tambahan: </strong>Setiap elemen dalam linked list memerlukan memori tambahan untuk menyimpan alamat referensi ke elemen berikutnya (dan sebelumnya dalam linked list ganda). Jumlah memori yang digunakan oleh linked list bisa lebih besar dibandingkan dengan struktur data seperti array, terutama jika linked list memiliki jumlah elemen yang besar.</li><li><strong>Ketergantungan pada Alamat Memori: </strong>Linked list sangat tergantung pada alamat memori untuk menghubungkan elemen-elemen. Jika ada kesalahan atau kerusakan pada alamat memori, dapat menyebabkan kesalahan serius dalam linked list.</li></ol><p>Meskipun linked list memiliki kelebihan dan kekurangan tersebut, keputusan penggunaan linked list atau struktur data lainnya tergantung pada kebutuhan spesifik dari aplikasi atau masalah yang ingin diselesaikan. Dalam beberapa kasus, linked list bisa menjadi pilihan yang baik, terutama ketika operasi penambahan atau penghapusan elemen sering terjadi, atau ketika fleksibilitas dalam ukuran diperlukan. Namun, dalam kasus lain, struktur data lain mungkin lebih cocok, terutama jika akses acak atau penggunaan memori yang efisien menjadi prioritas.</p><p>Sekian Dan Terima Kasih</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115fff677253" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering TDD in React: Boost Your Development Process with React Testing Library (RTL)]]></title>
            <link>https://medium.com/@aryandi/mastering-tdd-in-react-boost-your-development-process-with-react-testing-library-rtl-b979fda6476d?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/b979fda6476d</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Wed, 12 Apr 2023 06:57:56 GMT</pubDate>
            <atom:updated>2023-04-15T14:53:11.879Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RulxxV_h8V1j7kBhGzAaOg.jpeg" /><figcaption><strong><em>source: </em></strong><a href="https://unsplash.com/photos/pCqzMe04s8g"><strong><em>unsplash.com</em></strong></a></figcaption></figure><p>Test-driven development (TDD) has become an integral part of modern software development. In this method, developers write unit tests before writing code. This approach helps ensure that the resulting code works as expected and meets user requirements.</p><p>TDD brings many benefits to both developers and end-users. In terms of development, TDD helps developers better understand requirements, find and fix bugs faster, and reduce the risk of developing unreliable applications. In terms of end-users, TDD can improve software quality, speed up development time, and reduce maintenance costs.</p><p>React Testing Library (RTL) is the right choice for implementing TDD in React projects. RTL allows developers to write tests that mimic the way users interact with the application, making tests more realistic and easier to understand. Additionally, RTL is specifically designed to work with React applications, making it easier for developers to test React components and ensure that the application works correctly.</p><h3>Basic Concepts of TDD</h3><p>In Test-Driven Development (TDD), tests are an integral part of the development process. TDD involves writing tests before writing the actual code, and then developing the code to fulfill the requirements of the tests.</p><p>The TDD cycle consists of three stages: red, green, and refactor. In the red stage, the developer writes tests that will evaluate the behavior of the system that has not been created yet. In the green stage, the developer writes the code that meets the requirements of the tests that have been created. In the refactor stage, the developer improves the code and ensures that all tests are still functioning properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bIQFr8k8laY1f9qgyvdaw.png" /><figcaption>resource: <a href="https://marsner.com/wp-content/uploads/test-driven-development-TDD.png">https://marsner.com/wp-content/uploads/test-driven-development-TDD.png</a></figcaption></figure><p>The benefits of using TDD include improving the quality of the software by finding and fixing bugs earlier in the development cycle. This also speeds up development time by minimizing the time spent on debugging and manual testing. Additionally, by writing tests first, developers ensure that the code has comprehensive and reliable testing.</p><h3>Introduction to React Testing Library</h3><p>React Testing Library (RTL) is one of the most popular testing libraries for developing web applications with React. RTL makes it easy for developers to test React components and user interactions in an environment similar to a browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jw0M68r_EVHuJ43ktxbpiA.png" /><figcaption>source: <a href="https://dev.to/bahdcoder_47/testing-react-components-the-right-way-with-react-testing-library-5h8d">https://dev.to/bahdcoder_47/testing-react-components-the-right-way-with-react-testing-library-5h8d</a></figcaption></figure><p>What is React Testing Library? React Testing Library is a testing library for React that is designed to help developers test React components more easily and efficiently. It provides a simple API that allows developers to access and manipulate DOM elements and user behavior with the application. RTL also provides utilities and helper functions that make it easier for developers to test React components.</p><p>Advantages of React Testing Library React Testing Library has many advantages, including:</p><ul><li><strong>Easy to learn:</strong> RTL is designed to make it easier for developers to write and run tests on React components, making it easy to learn for developers who do not have experience in testing web applications.</li><li><strong>Focus on the user:</strong> RTL is designed to allow developers to test user interaction behavior with the application. This can help developers ensure that the application being developed meets the needs of users.</li><li><strong>Similar to a browser environment:</strong> RTL provides an API that is similar to a browser environment, making it easier for developers to write more realistic and accurate tests.</li><li><strong>Support for React Hooks:</strong> RTL supports testing of React Hooks, making it easier for developers to test complex behavior on React components.</li><li><strong>Integration with other testing libraries:</strong> RTL can be used together with other testing libraries such as Jest and Cypress, making it easier for developers to test the application thoroughly.</li></ul><p>By using React Testing Library, developers can improve the quality of the software being developed and accelerate development time. Next, this article will discuss how to start TDD with RTL and some testing techniques that can be used to improve the effectiveness of TDD in developing React applications.</p><h3>Getting Started with TDD using React Testing Library</h3><p>After understanding the basic concept of TDD and introduction to React Testing Library in the previous section, it’s time to get started with TDD using RTL. In this section, we will discuss how to start TDD using RTL, which involves installing RTL and creating the first test.</p><h4>Installing React Testing Library</h4><p>Before we can start TDD using RTL, we need to install it first. React Testing Library can be installed using package managers such as npm or yarn.</p><p>If we use npm, we can install RTL by running the following command in the terminal:</p><pre>npm install --save-dev @testing-library/react</pre><p>While if we use yarn, we can run the following command:</p><pre>yarn add --dev @testing-library/react</pre><p>After installing RTL, we are ready to create the first test.</p><h4>Creating the First Test with RTL</h4><p>First, we will create a simple test to check whether a component is rendered correctly or not. To do this, we will create a new file named Component.test.js in the same directory as the component file to be tested.</p><p>Here is an example code for a simple test that checks whether a component is rendered correctly:</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react&#39;;<br>import Component from &#39;./Component&#39;;<br><br>describe(&#39;Component&#39;, () =&gt; {<br>  it(&#39;renders correctly&#39;, () =&gt; {<br>    const { getByText } = render(&lt;Component /&gt;);<br>    const linkElement = getByText(/Hello World/i);<br>    expect(linkElement).toBeInTheDocument();<br>  });<br>});</pre><p>In the above code, we use the render function from RTL to render the component to be tested. Next, we use the getByText function to find an element with the text “Hello World” in the rendered component. Finally, we use the expect function to ensure that the element is in the document.</p><p>In the TDD cycle, this test is still in the “red” stage because there is no implementation of the tested component yet. After we implement it, we can execute this test, and if the test passes the “green” stage, we can move on to the “refactor” stage.</p><p>Here are the steps to apply TDD with RTL in this case:</p><h4>Write Unit Test (Red)</h4><pre>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react&#39;;<br>import TextComponent from &#39;./TextComponent&#39;;<br><br>describe(&#39;TextComponent&#39;, () =&gt; {<br>  it(&#39;should render text correctly&#39;, () =&gt; {<br>    const text = &#39;Hello World&#39;;<br>    const { getByText } = render(&lt;TextComponent text={text} /&gt;);<br>    const textElement = getByText(text);<br>    expect(textElement).toBeInTheDocument();<br>  });<br>});</pre><p>In this step, we write a test that checks if the component renders the correct text based on the props passed to it. We use the render function from RTL to render the component and then use the getByText function to find the element with the text we expect. We then use the expect function to check if the element is in the document. As I said before, that test should be error because we need to create the code in Green step.</p><h4>Write Production Code (Green)</h4><pre>import React from &#39;react&#39;;<br><br>const TextComponent = ( props ) =&gt; {<br>  const { text } = props;<br>  return (<br>    &lt;div&gt;<br>      {text}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default TextComponent;</pre><p>In this step, we write the production code that satisfies the test we wrote in the previous step. We define a simple functional component that renders the text passed to it as a prop.</p><h4>Refactor Code</h4><pre>import React from &#39;react&#39;;<br><br>const TextComponent = ({ text }) =&gt; (<br>  &lt;div&gt;{text}&lt;/div&gt;<br>);<br><br>// In this step, we refactor the code by removing any duplication and improving the quality of the code.<br>// Since this is a simple example, there is no need for further refactoring.<br>export default TextComponent;</pre><p>By starting TDD using RTL, we can ensure that every feature in the application we develop has been tested and works correctly. Additionally, we can find problems early, so we can fix them before they become more complex and difficult to solve.</p><h3>Improving TDD with React Testing Library</h3><p>After learning the basic concept of TDD and starting to use React Testing Library (RTL), there are several techniques and methods that can be used to improve the effectiveness of TDD in developing React applications using RTL.</p><h4>Mocking and Stubbing</h4><p>Mocking and Stubbing are techniques used to isolate unit tests from external environments such as APIs, databases, or other modules. In React, mocking and stubbing can be done using libraries such as jest.fn() and jest.mock(). With this technique, developers can determine if the code is integrated correctly with dependencies and behaves as expected.</p><p>Here is an example of mocking and stubbing code:</p><pre>import { fetchData } from &#39;./api&#39;;<br><br>jest.mock(&#39;./api&#39;);<br><br>test(&#39;fetchData() returns the correct data&#39;, () =&gt; {<br>  const mockedData = {name: &#39;John&#39;, age: 25};<br>  fetchData.mockResolvedValue(mockedData);<br>  // execute the test and expect the mocked data to be returned<br>});</pre><h4>Snapshot Testing</h4><p>Snapshot Testing is a technique used to compare the rendered results of a React component before and after changes are made to the code. This technique can help developers ensure that there are no unwanted changes to the user interface. React Testing Library has an easy-to-use snapshot testing feature that compares the component snapshot before and after changes are made.</p><p>Here is an example of snapshot testing code:</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react&#39;;<br>import Component from &#39;./Component&#39;;<br><br>test(&#39;Component snapshot matches&#39;, () =&gt; {<br>  const { asFragment } = render(&lt;Component /&gt;);<br>  expect(asFragment()).toMatchSnapshot();<br>});</pre><h4>Integration Testing</h4><p>Integration Testing is a technique used to test the interaction between different components in a React application. In developing React applications, integration testing can help developers ensure that all components interact as expected and that there are no conflicts between components.</p><p>Here is an example of integration testing code:</p><pre>import React from &#39;react&#39;;<br>import { render } from &#39;@testing-library/react&#39;;<br>import ParentComponent from &#39;./ParentComponent&#39;;<br><br>test(&#39;ParentComponent renders ChildComponent&#39;, () =&gt; {<br>  const { getByTestId } = render(&lt;ParentComponent /&gt;);<br>  expect(getByTestId(&#39;child-component&#39;)).toBeInTheDocument();<br>});</pre><h4>Testing React Hooks</h4><p>React Hooks is a new feature of React that allows developers to use state and functions within functional components. Testing React Hooks is crucial because using React Hooks can affect the behavior of the component. In React Testing Library, developers can test React Hooks using the renderHook() function.</p><p>Here is an example of testing React Hooks code:</p><pre>import { renderHook, act } from &#39;@testing-library/react-hooks&#39;;<br>import useCounter from &#39;./useCounter&#39;;<br><br>test(&#39;useCounter hook increments count&#39;, () =&gt; {<br>  const { result } = renderHook(() =&gt; useCounter());<br>  expect(result.current.count).toBe(0);<br><br>  act(() =&gt; {<br>    result.current.incrementCount();<br>  });<br><br>  expect(result.current.count).toBe(1);<br>});</pre><p>By using the above techniques and methods, developers can improve the effectiveness of using TDD in developing React applications using React Testing Library. Therefore, it is essential for developers to understand and master these techniques to improve the quality of software and speed up development time.</p><p>In conclusion, implementing TDD with React Testing Library can provide significant benefits to software development. It is important to understand the basic concepts of TDD and master React Testing Library to effectively implement TDD in React projects and achieve success in software development. By detecting bugs early in the development cycle and fixing them before entering the production stage, you can save time and development costs while increasing user confidence and satisfaction.</p><p>It is also important to pay attention to best practices such as mocking and stubbing, snapshot testing, integration testing, and testing React Hooks to further enhance the effectiveness of TDD.</p><p>Thank you for reading and we hope this article has been informative and helpful in your journey towards successful software development.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b979fda6476d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React State Management: Redux or Context, Which are you use with?]]></title>
            <link>https://medium.com/@aryandi/react-state-management-redux-or-context-which-are-you-use-with-dac3ce19bca3?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac3ce19bca3</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Wed, 05 Apr 2023 07:26:09 GMT</pubDate>
            <atom:updated>2023-04-05T07:26:09.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1NJM3fvtWI7KSik42y2gmA.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/FGXqbqbGt5o">unsplash.com</a></figcaption></figure><p>React is a popular JavaScript library for building user interfaces, which has become increasingly popular in recent years. As the complexity of React applications grows, so does the need for managing state. In this article, we will explore two popular state management solutions for React — Context API and Redux, and discuss which one to use in different scenarios.</p><h3>How State Management Works in React</h3><p>State is used in React to keep track of data that can change over time, and is used to render components dynamically. The state of a component can change due to user interactions, server responses, or other events, and React provides an easy way to manage this state.</p><p>When a component’s state changes, React automatically updates the UI to reflect the new state. This is done by re-rendering the component, which involves updating the virtual DOM and then comparing it with the actual DOM. If there are any differences, React updates the actual DOM to match the virtual DOM.</p><p>While this process is efficient for small applications, it can become slow and unwieldy for larger applications. This is where state management comes in — it helps to manage state across multiple components, and makes it easier to share data between them.</p><h4>Why React Needs State Management</h4><p>State management becomes necessary in React when you have multiple components that need to access the same data. For example, consider a shopping cart application with multiple components like a product list, a shopping cart, and a checkout form. All these components need to access the same data, such as the user’s shopping cart items, their shipping address, and so on.</p><p>Without state management, it would be difficult to keep track of this data and update it in real-time. Each component would need to manage its own state, which could lead to inconsistencies and bugs. State management provides a centralized way of managing state, making it easier to update data across components and ensure that they remain in sync.</p><p>In the next sections, we will explore two popular state management solutions for React — Context API and Redux, and discuss which one to use in different scenarios.</p><p>Stay tuned for the next parts of this article where we will delve into each solution and provide step-by-step instructions on how to use them in your React application.</p><h3>Context API</h3><p>Context API is a state management system that is built-in in React. It is used to share data between components without the need to pass props down through every level of the component tree. Context API is a great alternative to prop drilling and it can make your code more maintainable and easier to comprehend. Here are the steps to use Context API in your React application.</p><h4>Step 1: Create a Context in a Separate File</h4><p>To create a context, you need to import the createContext method from the React library. You can then define an interface to describe the shape of the data that you want to share between components. Here’s an example:</p><pre>import React, { createContext } from &#39;react&#39;;<br><br>interface ThemeContextProps {<br>  theme: string;<br>  setTheme: (theme: string) =&gt; void;<br>}<br><br>const ThemeContext = createContext&lt;ThemeContextProps&gt;({<br>  theme: &#39;light&#39;,<br>  setTheme: () =&gt; {}<br>});<br><br>export default ThemeContext;</pre><p>In this example, we’re creating a context to share the theme and a function to set the theme. We’ve defined an interface ThemeContextProps to describe the shape of the data.</p><h4>Step 2: Create a Provider for the Context That You Have Created in Step 1</h4><p>The next step is to create a Provider component to wrap around the components that will use the context. In the Provider component, you need to define the state that you want to share and a function to update the state. Here’s an example:</p><pre>import React, { useState } from &#39;react&#39;;<br>import ThemeContext from &#39;./ThemeContext&#39;;<br><br>const ThemeProvider = ({ children }: { children: React.ReactNode }) =&gt; {<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, setTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}<br><br>export default ThemeProvider;</pre><p>In this example, we’re creating a ThemeProvider component to wrap around the child components that will use the theme. We’ve defined the initial state of the theme as light and a function to update the theme. We&#39;re passing an object with the theme and setTheme properties to the Provider component.</p><h4>Step 3: Use the Context in Your React Component</h4><p>To use the context in your React component, you need to import the useContext method from the React library and the context that you have created. Here’s an example:</p><pre>import React, { useContext } from &#39;react&#39;;<br>import ThemeContext from &#39;./ThemeContext&#39;;<br><br>const ThemeToggler = () =&gt; {<br>  const { theme, setTheme } = useContext(ThemeContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button<br>        onClick={() =&gt;<br>          setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;)<br>        }<br>      &gt;<br>        Toggle Theme<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ThemeToggler;</pre><p>In this example, we’re importing the ThemeContext and useContext methods from the React library. We’re using the useContext method to access the theme and setTheme properties that we passed to the Provider component.</p><h4>Step 4: Wrap Your Component with the Provider That You Have Created in Step 2</h4><p>Finally, you need to wrap your component with the Provider component that you have created in step 2. Here’s an example:</p><pre>import React from &#39;react&#39;;<br>import ThemeProvider from &#39;./ThemeProvider&#39;;<br>import ThemeToggler from &#39;./ThemeToggler&#39;;<br><br>const App = () =&gt; {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;ThemeToggler /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this example, we’re going to create a theme toggle feature using Context API. First, let’s create a new file called ThemeContext.tsx and define our context.</p><pre>import React, { createContext, useState } from &#39;react&#39;;<br><br>type Theme = &#39;light&#39; | &#39;dark&#39;;<br><br>interface ThemeContextProps {<br>  theme: Theme;<br>  toggleTheme: () =&gt; void;<br>}<br><br>export const ThemeContext = createContext&lt;ThemeContextProps&gt;({<br>  theme: &#39;light&#39;,<br>  toggleTheme: () =&gt; {},<br>});<br><br>export const ThemeProvider: React.FC = ({ children }) =&gt; {<br>  const [theme, setTheme] = useState&lt;Theme&gt;(&#39;light&#39;);<br><br>  const toggleTheme = () =&gt; {<br>    setTheme(theme === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;);<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={{ theme, toggleTheme }}&gt;<br>      {children}<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>};</pre><p>In this code, we define a ThemeContext and ThemeProvider component. ThemeContext is the context object that we will use to pass the theme and toggleTheme function down to child components. The initial theme state is set to light, and we define a toggleTheme function that will toggle the theme state between light and dark.</p><p>Next, let’s use the ThemeContext in our App component.</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { ThemeProvider, ThemeContext } from &#39;./ThemeContext&#39;;<br><br>const App: React.FC = () =&gt; {<br>  const { theme, toggleTheme } = useContext(ThemeContext);<br><br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;div className={theme === &#39;light&#39; ? &#39;App&#39; : &#39;App dark&#39;}&gt;<br>        &lt;button onClick={toggleTheme}&gt;Toggle Theme&lt;/button&gt;<br>        &lt;h1&gt;{`Current Theme: ${theme}`}&lt;/h1&gt;<br>      &lt;/div&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>};<br><br>export default App;</pre><p>In this code, we import the ThemeContext and ThemeProvider from ThemeContext.tsx. We then use the useContext hook to access the theme and toggleTheme function from the ThemeContext. We render a button that will toggle the theme when clicked and display the current theme on the screen.</p><p>Finally, we wrap our App component with the ThemeProvider component so that the theme and toggleTheme function are available to all child components.</p><pre>import React from &#39;react&#39;;<br>import App from &#39;./App&#39;;<br>import { ThemeProvider } from &#39;./ThemeContext&#39;;<br><br>const Root: React.FC = () =&gt; {<br>  return (<br>    &lt;ThemeProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/ThemeProvider&gt;<br>  );<br>};<br><br>export default Root;</pre><p>And that’s it! We’ve successfully implemented a theme toggle feature using Context API in our React application. By using Context API, we can avoid prop drilling and easily share data and functions across our component tree.</p><h3>Redux</h3><p>Redux is a popular state management library for JavaScript applications, including React. It provides a centralized store to manage the application state and enables unidirectional data flow, making it easier to build and maintain large and complex applications. In this section, we’ll explain how to use Redux with React and provide steps to set it up.</p><h4>Step 1: Install Redux Library</h4><p>The first step to using Redux in a React application is to install the Redux library. You can do this by running the following command in your terminal:</p><pre>npm install @reduxjs/toolkit react-redux</pre><h4>Step 2: Create a Slice</h4><p>After installing Redux, the next step is to create a slice. A slice is a part of the Redux store that contains the state and logic for a specific feature or section of the application. You can create a slice using the createSlice() function provided by the @reduxjs/toolkit package.</p><p>Here’s an example of creating a slice for a counter feature:</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;;<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState: { value: 0 },<br>  reducers: {<br>    increment: (state) =&gt; {<br>      state.value += 1;<br>    },<br>    decrement: (state) =&gt; {<br>      state.value -= 1;<br>    },<br>    reset: (state) =&gt; {<br>      state.value = 0;<br>    },<br>  },<br>});<br><br>export const { increment, decrement, reset } = counterSlice.actions;<br>export default counterSlice.reducer;</pre><p>In this example, we’ve created a slice named “counter” with an initial state of { value: 0 }. We&#39;ve also defined three reducers - increment, decrement, and reset - that modify the counter state.</p><h4>Step 3: Create a Redux Store with the Slice</h4><p>Once you’ve created a slice, the next step is to create a Redux store that uses the slice. You can create a store using the configureStore() function provided by the @reduxjs/toolkit package.</p><p>Here’s an example of creating a store that uses the counter slice we created earlier:</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import counterReducer from &#39;./counterSlice&#39;;<br><br>const store = configureStore({<br>  reducer: {<br>    counter: counterReducer,<br>  },<br>});<br><br>export default store;</pre><p>In this example, we’ve imported the configureStore() function and the counter slice reducer we created earlier. We then passed the counter reducer to the configureStore() function, along with an object that defines the store&#39;s initial state.</p><h4>Step 4: <strong>Connect the Store to Your React Components</strong></h4><p>After creating a store, you can connect it to your React components using the useSelector() and useDispatch() hooks provided by the react-redux package.</p><p>Here’s an example of a React component that uses the counter state from the Redux store:</p><pre>import { useSelector, useDispatch } from &#39;react-redux&#39;;<br>import { increment, decrement, reset } from &#39;./counterSlice&#39;;<br><br>function Counter() {<br>  const count = useSelector((state) =&gt; state.counter.value);<br>  const dispatch = useDispatch();<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Counter&lt;/h2&gt;<br>      &lt;p&gt;{count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch(increment())}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch(decrement())}&gt;-&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch(reset())}&gt;Reset&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>In this example, we’ve imported the useSelector() and useDispatch() hooks from react-redux and the action creators we defined in the previous step. useSelector() is a hook that allows us to extract data from the Redux store state, and useDispatch() is a hook that returns a reference to the dispatch function from the Redux store.</p><p>Next, we defined two callback functions: handleIncrement() and handleDecrement(). These functions are responsible for dispatching the increment() and decrement() actions, respectively. We used the useCallback() hook to ensure that the functions are not recreated every time the component re-renders.</p><p>Finally, we returned the JSX for our Counter component, which includes a paragraph element that displays the current count value from the Redux store, and two button elements that trigger the handleIncrement() and handleDecrement() functions when clicked.</p><h4>Step 5: Wrap the component with a Provider from Redux</h4><p>Now that we have our Counter component and Redux store set up, we need to connect them by wrapping the component with a Provider from the react-redux library.</p><p>To do this, we’ll create a new component called App that renders our Counter component wrapped in a Provider component.</p><p>Here’s what the code for App.js looks like:</p><pre>import React from &#39;react&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import store from &#39;./store&#39;;<br>import Counter from &#39;./Counter&#39;;<br><br>function App() {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;Counter /&gt;<br>    &lt;/Provider&gt;<br>  );<br>}<br><br>export default App;</pre><p>In this code, we import the Provider component from react-redux and our store from the store.js file. We then define a new function component called App that returns our Counter component wrapped in the Provider component. We pass our store to the Provider component as a prop.</p><p>With this setup, our Counter component now has access to the Redux store and can dispatch actions to update the state.</p><h3>Context API or Redux, which one is the best?</h3><p>React provides two primary ways to manage state: Context API and Redux. While both are capable of state management, each has its strengths and weaknesses that make it better suited for certain use cases. In this section, we’ll compare the two approaches across several criteria to help you decide which one is the best fit for your project.</p><h4>1.Purposes</h4><p>Context API is primarily used for managing state within a small section of an application, while Redux is better suited for managing the state of an entire application. If your application is small and doesn’t require complex state management, then Context API may be the better option. However, if your application is large and has complex state management requirements, then Redux may be the better choice.</p><h4>2. Complexity</h4><p>Context API is less complex than Redux because it doesn’t require as much boilerplate code or setup. Context API is built into React, so there’s no need to install any additional libraries. On the other hand, Redux requires more setup and boilerplate code to get started.</p><h4>3. Performance</h4><p>When it comes to performance, Context API may be faster than Redux because it doesn’t rely on a centralized store like Redux does. Context API uses a provider-consumer pattern, which allows components to subscribe to changes in state directly, whereas Redux requires all state changes to be routed through the centralized store.</p><h4>4. Development</h4><p>Both Context API and Redux can improve development speed by making it easier to manage state in a React application. However, Redux provides better debugging tools and dev tools than Context API, which can help speed up development and debugging.</p><h4>5. Integration</h4><p>Context API integrates well with other React libraries, whereas Redux may require more work to integrate with other libraries. However, Redux has a larger ecosystem of plugins and extensions that can be used to extend its functionality.</p><p>Ultimately, the choice between Context API and Redux depends on the needs of your application. If you have a small application with simple state management requirements, then Context API may be the best choice. However, if you have a larger application with complex state management requirements, then Redux may be the better option.</p><h3>Summary</h3><p>In this article, we’ve discussed two popular state management options in React: Context API and Redux. We’ve learned that Context API is a built-in feature in React that allows you to share state between components without the need for props drilling. We’ve also learned that Redux is a separate library that provides a centralized and predictable way to manage state in your React applications.</p><p>To use Context API, we first create a context in a separate file, create a provider for that context, use the context in our components, and wrap our components with the provider we created. On the other hand, to use Redux, we install the Redux library, create a slice, create a store with that slice, connect the store to our components, and wrap our components with a provider from the Redux library.</p><p>In comparing Context API and Redux, we’ve learned that Context API is simpler and easier to use for smaller applications that require less complex state management. Redux, on the other hand, is more suitable for larger applications with more complex state management requirements, as it provides better scalability, performance, and developer tooling. However, Redux can be more complex to set up and use, especially for beginners.</p><p>Overall, both Context API and Redux have their advantages and disadvantages, and choosing between them depends on your application’s requirements and your personal preferences. We hope this article has provided you with a better understanding of state management in React and helped you make an informed decision on which state management option to use in your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac3ce19bca3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Menggunakan useCallback dengan Bijak di React]]></title>
            <link>https://medium.com/@aryandi/menggunakan-usecallback-dengan-bijak-di-react-64e390caa91a?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e390caa91a</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 13:44:54 GMT</pubDate>
            <atom:updated>2023-09-28T07:54:59.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uj-rjbr2G2Bj5p2rTksW3g.jpeg" /><figcaption><strong>source: unsplash.com</strong></figcaption></figure><p>React adalah salah satu framework JavaScript yang sangat populer digunakan oleh developer untuk membangun aplikasi web. Salah satu fitur yang disediakan oleh React adalah useCallback. useCallback adalah salah satu hooks yang digunakan untuk mengoptimalkan performa aplikasi React dengan menghindari rendering yang tidak perlu.</p><p>Secara umum, ketika state atau props suatu komponen berubah, React akan melakukan rendering ulang pada seluruh komponen turunannya. Namun, terkadang perubahan tersebut tidak memerlukan rendering ulang pada semua komponen turunannya, sehingga useCallback digunakan untuk menghindari rendering yang tidak perlu.</p><p>Pada dasarnya, useCallback memungkinkan kita untuk menyimpan instance dari sebuah fungsi dan mengeksekusinya hanya ketika nilai dependensi telah berubah. Dengan demikian, kita bisa mempercepat performa aplikasi dengan menghindari eksekusi fungsi yang tidak perlu.</p><p>Contoh penggunaan useCallback:</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>function MyComponent(props) {<br>  const [count, setCount] = useState(0);<br><br>  // ini hanya contoh yang menggunakan useCallback<br>  // tetapi secara konsep penggunaannya kurang tepat<br>  // akan di jelaskan didalam artikel ini<br>  const incrementCount = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;{count}&lt;/h1&gt;<br>      &lt;button onClick={incrementCount}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Pada contoh kode di atas, useCallback digunakan untuk menyimpan instance dari fungsi incrementCount dan hanya akan di-eksekusi ketika nilai count berubah. Dengan demikian, kita bisa menghindari eksekusi fungsi yang tidak perlu dan mempercepat performa aplikasi.</p><h3>Penggunaan useCallback di React</h3><p>useCallback adalah salah satu hook yang disediakan oleh React untuk memperbaiki kinerja aplikasi yang menggunakan komponen dengan banyak fungsi callback. Ketika sebuah komponen memiliki banyak fungsi callback, maka setiap kali state komponen berubah, semua fungsi callback tersebut akan dijalankan ulang. Hal ini dapat mempengaruhi kinerja aplikasi dan menyebabkan aplikasi menjadi lambat.</p><p>Untuk mengatasi masalah tersebut, useCallback digunakan untuk menghindari pengalokasian memori yang berlebihan. useCallback berfungsi untuk membuat instance dari sebuah fungsi yang tidak berubah, sehingga dapat menghindari re-render yang tidak perlu.</p><p>Berikut adalah contoh penggunaan useCallback di React:</p><pre>import React, { useState, useCallback } from &#39;react&#39;;<br><br>function App() {<br>  const [count, setCount] = useState(0);<br>  <br>  const increment = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]);<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Pada contoh kode di atas, fungsi increment yang digunakan untuk menambah nilai state count akan dijaga agar tidak dijalankan ulang ketika terjadi perubahan state yang tidak mempengaruhinya. Dalam hal ini, useCallback diatur dengan dependensi count agar fungsi tersebut hanya dijalankan ketika nilai count berubah.</p><p>Dengan menggunakan useCallback, fungsi increment hanya akan dihitung ulang ketika nilai count berubah, sehingga dapat meningkatkan kinerja aplikasi.</p><h3>Kesalahan Umum dalam Menggunakan useCallback</h3><p>useCallback adalah salah satu hooks yang sangat berguna di React, tetapi seperti halnya dengan hooks lainnya, kesalahan dalam penggunaannya dapat menyebabkan masalah yang serius dalam kinerja aplikasi. Berikut adalah beberapa kesalahan umum yang harus dihindari saat menggunakan useCallback:</p><h4>1. Menggunakan useCallback pada setiap fungsi</h4><p>Kesalahan umum yang dilakukan adalah menggunakan useCallback pada setiap fungsi yang dipanggil dalam komponen, bahkan pada fungsi yang tidak perlu dioptimalkan. Hal ini dapat menyebabkan overhead pada kinerja aplikasi dan tidak memberikan manfaat yang signifikan pada kinerja. Berikut contoh kodenya:</p><pre>const MyComponent = () =&gt; {<br>  const handleClick = useCallback(() =&gt; {<br>    console.log(&quot;Clicked!&quot;);<br>  }, []);<br><br>  const handleInputChange = (event) =&gt; {<br>    console.log(event.target.value);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; onChange={handleInputChange} /&gt;<br>      &lt;button onClick={handleClick}&gt;Click me!&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>2. Menyimpan state di dalam useCallback</h4><p>Kesalahan lain yang sering dilakukan adalah menyimpan state di dalam useCallback. Hal ini dapat menyebabkan masalah ketika state diubah karena callback akan dipanggil ulang, meskipun tidak perlu. Contoh kode:</p><pre>const MyComponent = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  const handleClick = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={handleClick}&gt;Click me!&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Dalam contoh di atas, useCallback digunakan untuk handleClick meskipun state count disimpan di dalamnya. Karena state tersebut berubah setiap kali handleClick dipanggil, callback akan dipanggil ulang secara berulang-ulang, bahkan ketika tidak perlu.</p><p>Dampak buruk dari kesalahan ini adalah penurunan kinerja aplikasi dan memperburuk pengalaman pengguna.</p><h3>Kapan Menggunakan useCallback</h3><p>useCallback sebaiknya digunakan ketika:</p><ul><li>Mencegah komponen yang tidak perlu di-render ulang: Ketika kita memasukkan suatu fungsi ke dalam useCallback, maka fungsi tersebut akan selalu menghasilkan nilai referensi yang sama. Sehingga, apabila kita mengirimkan fungsi tersebut sebagai prop ke komponen turunan, dan komponen induk mengalami update, hanya komponen turunan yang menerima nilai prop dari useCallback yang akan di-render ulang.</li><li>Memperbaiki kinerja aplikasi: Ketika kita menggunakan useCallback untuk menghindari pembuatan fungsi baru pada setiap pemanggilan, maka kita dapat menghindari penggunaan CPU yang berlebihan untuk membuat fungsi tersebut. Sehingga, hal ini dapat memperbaiki kinerja aplikasi.</li></ul><p>Contoh penggunaan useCallback untuk mencegah rendering komponen yang tidak perlu:</p><pre>function ParentComponent() {<br>  const [count, setCount] = useState(0);<br><br>  const handleButtonClick = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]);<br><br>  return (<br>    &lt;&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;ChildComponent onButtonClick={handleButtonClick} /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>function ChildComponent({ onButtonClick }) {<br>  return (<br>    &lt;button onClick={onButtonClick}&gt;Increment Count&lt;/button&gt;<br>  );<br>}</pre><p>Pada contoh di atas, kita menggunakan useCallback untuk menyimpan fungsi handleButtonClick agar selalu menghasilkan nilai referensi yang sama. Sehingga, pada saat ParentComponent di-render ulang karena adanya perubahan pada state count, hanya ChildComponent yang menerima nilai prop dari useCallback yang akan di-render ulang.</p><h3>Kapan Tidak Menggunakan useCallback</h3><p>useCallback tidak sebaiknya digunakan ketika:</p><ul><li>Memaksa pembuatan fungsi baru: Jika kita memang membutuhkan pembuatan fungsi baru pada setiap pemanggilan, seperti pada kasus animasi atau event handler yang selalu berubah, maka penggunaan useCallback dapat memaksa pembuatan fungsi baru yang sebenarnya tidak diperlukan.</li></ul><p>Contoh penggunaan event handler yang tidak cocok untuk menggunakan useCallback:</p><pre>function MyComponent() {<br>  const [count, setCount] = useState(0);<br><br>  function handleClick() {<br>    setCount(count + 1);<br>  }<br><br>  return (<br>    &lt;button onClick={handleClick}&gt;Increment Count&lt;/button&gt;<br>  );<br>}</pre><p>Pada contoh di atas, kita tidak perlu menggunakan useCallback untuk handleClick karena event handler tersebut selalu berubah pada setiap pemanggilan. Sehingga, penggunaan useCallback hanya akan memaksa pembuatan fungsi baru yang sebenarnya tidak diperlukan.</p><h3>Memperbaiki Kinerja dengan useCallback dengan menghubungkan dengan useEffect dan useMemo</h3><p>Jika Anda sudah memahami bagaimana cara menggunakan useCallback dengan bijak, maka saatnya untuk mengoptimalkan kinerja aplikasi React Anda. Salah satu cara untuk melakukannya adalah dengan menghubungkan useCallback dengan useEffect dan useMemo.</p><p>useEffect digunakan untuk mengatur efek samping di React. Misalnya, ketika komponen di-mount atau di-unmount, kita bisa menggunakan useEffect untuk mengeksekusi kode yang diperlukan. useEffect juga digunakan untuk mengatur pembaruan komponen saat ada perubahan pada prop atau state.</p><p>useMemo, di sisi lain, digunakan untuk melakukan memoization pada <strong>rich computation</strong> (“<strong>rich</strong>” disini merujuk pada operasi komputasi yang memerlukan waktu dan sumber daya yang signifikan untuk dihitung). Dengan menggunakan useMemo, kita bisa menyimpan nilai hasil komputasi yang sama, sehingga saat prop atau state tidak berubah, kita tidak perlu menghitung ulang nilainya.</p><p>Kita bisa mengkombinasikan useCallback dengan useEffect dan useMemo untuk mengoptimalkan kinerja aplikasi React. Contohnya adalah sebagai berikut:</p><pre>import React, { useState, useEffect, useCallback, useMemo } from &#39;react&#39;;<br><br>function App() {<br>  const [count, setCount] = useState(0);<br><br>  const handleClick = useCallback(() =&gt; {<br>    setCount(count + 1);<br>  }, [count]);<br><br>  const doubleCount = useMemo(() =&gt; {<br>    return count * 2;<br>  }, [count]);<br><br>  useEffect(() =&gt; {<br>    // kode yang akan dijalankan saat komponen di-mount atau di-unmount<br>    return () =&gt; {<br>      // kode yang akan dijalankan saat komponen di-unmount<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleClick}&gt;Click Me!&lt;/button&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;p&gt;Double Count: {doubleCount}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>Pada contoh kode di atas, useCallback digunakan untuk membuat handleClick yang merupakan fungsi yang dijalankan saat tombol diklik. useCallback juga memiliki dependency count, sehingga hanya akan dihitung ulang ketika count berubah.</p><p>Kemudian, useMemo digunakan untuk menghitung doubleCount yang merupakan hasil perhitungan count * 2. useMemo juga memiliki dependency count, sehingga hanya akan dihitung ulang ketika count berubah.</p><p>Terakhir, useEffect digunakan untuk mengeksekusi kode yang diperlukan saat komponen di-mount atau di-unmount. Pada contoh di atas, useEffect tidak memiliki dependency, sehingga hanya akan dijalankan sekali saat komponen di-mount. Dengan mengkombinasikan useCallback, useEffect, dan useMemo, kita bisa membuat aplikasi React yang lebih optimal dan efisien.</p><p>Dalam artikel ini, kita telah membahas tentang penggunaan useCallback di React. useCallback digunakan untuk mengoptimalkan kinerja aplikasi dengan cara menghindari re-render yang tidak perlu pada komponen-komponen tertentu.</p><p>Penting untuk diingat bahwa useCallback bukanlah solusi untuk semua masalah kinerja aplikasi. Saat menggunakan useCallback, ada beberapa kesalahan yang sering dilakukan seperti menggunakan useCallback terlalu sering, tidak memahami cara kerja useCallback, dan lain-lain.</p><p>Kita juga telah membahas kapan sebaiknya menggunakan useCallback, antara lain saat kita ingin mencegah komponen yang tidak berubah dirender ulang, dan kapan tidak sebaiknya menggunakan useCallback, seperti saat kita tidak perlu menyimpan fungsi yang berubah-ubah di dalam state.</p><p>Terakhir, kita juga telah membahas cara menggunakan useCallback bersama dengan useEffect dan useMemo untuk memperbaiki kinerja aplikasi.</p><p>Dalam penggunaan useCallback, kita perlu memperhatikan performa aplikasi dan memahami bagaimana useCallback bekerja. Dengan mengimplementasikan useCallback dengan bijak, kita dapat meningkatkan kinerja aplikasi kita secara signifikan.</p><p>Semoga artikel ini dapat membantu Anda dalam mengimplementasikan useCallback di aplikasi React Anda. Jika Anda ingin belajar lebih lanjut, Anda dapat merujuk ke sumber referensi di bagian akhir artikel ini.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e390caa91a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux vs React Context, Pilih yang mana ?]]></title>
            <link>https://medium.com/@aryandi/redux-vs-react-context-pilih-yang-mana-20f4c90f84bc?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f4c90f84bc</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-context]]></category>
            <category><![CDATA[context]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 20:53:29 GMT</pubDate>
            <atom:updated>2023-04-02T21:10:08.309Z</atom:updated>
            <content:encoded><![CDATA[<h3>Redux vs React Context, Pilih yang mana ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*Gwb8jli51Iv7YluJcpPNag.jpeg" /></figure><p>React telah menjadi salah satu framework terpopuler di dunia front-end development. Namun, ketika aplikasi React tumbuh semakin besar dan kompleks, mengelola state bisa menjadi tantangan. Itulah sebabnya, beberapa library dan teknologi muncul untuk membantu mengelola state dalam aplikasi React, salah satunya adalah Redux dan React Context.</p><p>Redux adalah library untuk mengelola state aplikasi secara global, terlepas dari komponen-komponen yang terlibat. Redux menyediakan arsitektur yang jelas dan terstruktur dalam mengelola state, yang membuatnya mudah dipahami dan digunakan dalam aplikasi React.</p><p>Sementara itu, React Context adalah API untuk membagikan data ke komponen-komponen React dalam pohon komponen tanpa harus melewati prop secara manual. Dengan React Context, data bisa disimpan dalam konteks dan diakses oleh komponen yang membutuhkannya, tanpa harus melewati komponen-komponen yang tidak membutuhkannya.</p><p>Tujuan dibuatnya Redux dan React Context adalah untuk membantu mengelola state dalam aplikasi React dengan lebih efektif dan efisien. Redux dan React Context memudahkan kita dalam membagikan data ke seluruh komponen dalam aplikasi, sehingga memudahkan kita dalam mengelola state yang kompleks. Dalam artikel ini, kita akan membahas tentang Redux dan React Context lebih lanjut dan membandingkannya agar kamu bisa memilih yang paling sesuai dengan kebutuhan kamu.</p><h3>Redux</h3><p>Redux merupakan salah satu library state management yang paling populer di dunia React. Redux digunakan untuk mengelola state yang kompleks pada aplikasi React. Redux memiliki beberapa konsep dasar seperti state, action, reducer, dan store yang harus dipahami.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNe10lUT684lR8gwHl6-fA.jpeg" /><figcaption><strong>source: scalablepath.com / contoh sederhana penggunaan redux</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EV1KQifr5KwiupJ9q7tdxA.png" /><figcaption><strong>source: freecodecamp.org</strong></figcaption></figure><ul><li><strong>State: </strong>state adalah data yang akan diatur pada aplikasi React. Pada Redux, state disimpan dalam satu store dan dapat diakses dari berbagai komponen.</li><li><strong>Action: </strong>action adalah sebuah objek yang mengindikasikan sebuah perubahan pada state. Action berisi informasi tentang jenis perubahan yang dilakukan serta data yang dibutuhkan untuk melakukan perubahan.</li><li><strong>Reducer: </strong>reducer adalah sebuah fungsi yang mengambil state dan action sebagai parameter, lalu menghasilkan state baru. Reducer bertugas mengubah state sesuai dengan action yang diterima.</li><li><strong>Store: </strong>store adalah tempat dimana state disimpan dan diatur. Store menyediakan beberapa method untuk melakukan perubahan pada state seperti dispatch, subscribe, dan getState.</li></ul><p>Kelebihan Redux antara lain:</p><ul><li>Redux memudahkan pengelolaan state pada aplikasi React yang kompleks.</li><li>Redux memiliki alat debugging yang kuat sehingga memudahkan developer untuk menemukan kesalahan pada aplikasi.</li><li>Redux memudahkan sharing state antara komponen yang berbeda.</li></ul><p>Namun, Redux juga memiliki kekurangan seperti:</p><ul><li>Redux memiliki kurva belajar yang cukup tinggi, sehingga membutuhkan waktu untuk memahami konsep dasarnya.</li><li>Penggunaan Redux pada aplikasi yang sederhana bisa terlalu kompleks dan memakan banyak waktu.</li></ul><h4>Kapan sebaiknya menggunakan Redux?</h4><p>Redux sebaiknya digunakan pada aplikasi React yang memiliki state yang kompleks dan data yang harus di-share antara komponen yang berbeda. Redux juga cocok digunakan pada aplikasi yang besar dengan banyak pengguna, karena memudahkan dalam debugging dan maintenance. Namun, Redux sebaiknya tidak digunakan pada aplikasi yang sederhana dan tidak membutuhkan state management yang kompleks.</p><h3><strong>Contoh kode penggunaan Redux:</strong></h3><h4><strong>Membuat store</strong></h4><p>Untuk membuat store, kita perlu membuat reducer yang akan mengatur state pada aplikasi. Berikut adalah contoh pembuatan reducer dengan Redux Toolkit:</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState: {<br>    value: 0,<br>  },<br>  reducers: {<br>    increment: state =&gt; {<br>      state.value++<br>    },<br>    decrement: state =&gt; {<br>      state.value--<br>    }<br>  }<br>})<br><br>export const { increment, decrement } = counterSlice.actions<br>export default counterSlice.reducer</pre><p>Setelah itu, kita bisa membuat store dengan createStore dari redux dan mengimpor reducer yang telah dibuat:</p><pre>import { createStore } from &#39;redux&#39;<br>import counterReducer from &#39;./counterSlice&#39;<br><br>const store = createStore(counterReducer)</pre><h4><strong>Menghubungkan store dengan komponen</strong></h4><p>React Setelah store dibuat, kita bisa menghubungkannya dengan komponen React dengan bantuan provider dari react-redux. Berikut adalah contoh penggunaannya:</p><pre>import { Provider } from &#39;react-redux&#39;<br>import store from &#39;./store&#39;<br>import Counter from &#39;./Counter&#39;<br><br>function App() {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;Counter /&gt;<br>    &lt;/Provider&gt;<br>  )<br>}</pre><h4><strong>Menggunakan state dan action pada komponen</strong></h4><p>Setelah store dihubungkan dengan komponen, kita bisa menggunakan state dan action dengan bantuan hooks useSelector dan useDispatch dari react-redux. Berikut contoh penggunaannya di komponen Counter:</p><pre>import { useSelector, useDispatch } from &#39;react-redux&#39;<br>import { increment, decrement } from &#39;./counterSlice&#39;<br><br>function Counter() {<br>  const count = useSelector(state =&gt; state.value)<br>  const dispatch = useDispatch()<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; dispatch(increment())}&gt;+&lt;/button&gt;<br>      &lt;p&gt;{count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch(decrement())}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Dalam contoh di atas, kita menggunakan useSelector untuk mengambil state dari store, dan useDispatch untuk mengirim action ke store. Ketika tombol + atau — ditekan, action increment atau decrement akan dikirim ke store dan state akan diupdate secara otomatis.</p><h3>React Context</h3><p>React Context adalah salah satu fitur dari React yang memungkinkan data dapat di-pass ke komponen-komponen di dalam sebuah tree tanpa harus melewati setiap komponen secara explicit. Dengan menggunakan React Context, data bisa di-pass melalui sebuah “provider” dan kemudian diakses oleh sebuah “consumer”. Provider merupakan komponen yang memungkinkan data dapat di-pass ke dalam tree, sementara consumer merupakan komponen yang memungkinkan data tersebut bisa diakses. React Context biasanya digunakan untuk membuat theme, language, atau data-data yang bersifat global dan dibutuhkan oleh banyak komponen.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xoLMihJaFsFgNZ6S37l5ow.jpeg" /><figcaption><strong>source: scalablepath.com</strong></figcaption></figure><p>Berikut contoh penggunaan React Context:</p><pre>import React, { createContext, useContext, useState } from &quot;react&quot;;<br><br>const ThemeContext = createContext(&quot;light&quot;);<br><br>function App() {<br>  const [theme, setTheme] = useState(&quot;light&quot;);<br><br>  const handleThemeChange = () =&gt; {<br>    setTheme(theme === &quot;light&quot; ? &quot;dark&quot; : &quot;light&quot;);<br>  };<br><br>  return (<br>    &lt;ThemeContext.Provider value={theme}&gt;<br>      &lt;Header onThemeChange={handleThemeChange} /&gt;<br>      &lt;Main /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}<br><br>function Header(props) {<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;header&gt;<br>      &lt;h1&gt;My App&lt;/h1&gt;<br>      &lt;button onClick={props.onThemeChange}&gt;Change Theme&lt;/button&gt;<br>      &lt;p&gt;Current theme: {theme}&lt;/p&gt;<br>    &lt;/header&gt;<br>  );<br>}<br><br>function Main() {<br>  const theme = useContext(ThemeContext);<br><br>  return (<br>    &lt;main&gt;<br>      &lt;p&gt;Some content here with {theme} theme&lt;/p&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><h4>Kelebihan dan kekurangan React Context</h4><p>Kelebihan dari React Context adalah memudahkan dalam transfer data antar komponen, terutama untuk data yang bersifat global. Selain itu, penggunaan React Context tidak membutuhkan library tambahan seperti Redux sehingga memungkinkan untuk membuat aplikasi yang lebih ringan. Namun, kekurangan dari React Context adalah tidak mendukung fitur-fitur seperti time travel debugging dan middleware seperti pada Redux.</p><h4>Kapan sebaiknya menggunakan React Context?</h4><p>React Context sebaiknya digunakan pada aplikasi React yang memiliki state yang sederhana dan tidak membutuhkan state management yang kompleks. Selain itu, React Context juga cocok digunakan pada aplikasi dengan pohon komponen yang dalam dan kompleks, sehingga dapat menghindari penggunaan prop drilling.</p><p>Berikut ini adalah contoh kode penggunaan React Context pada aplikasi React:</p><pre>// Inisialisasi React Context<br>import React from &#39;react&#39;;<br>const MyContext = React.createContext();<br><br>// Komponen Provider yang menyediakan data state dan fungsi pada aplikasi<br>function MyProvider(props) {<br>  const [state, setState] = React.useState({<br>    count: 0,<br>    incrementCount: () =&gt; setState({ ...state, count: state.count + 1 })<br>  });<br>  return (<br>    &lt;MyContext.Provider value={state}&gt;<br>      {props.children}<br>    &lt;/MyContext.Provider&gt;<br>  );<br>}<br><br>// Komponen consumer yang mengambil data dan fungsi dari provider<br>function MyConsumer() {<br>  const { count, incrementCount } = React.useContext(MyContext);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {count}&lt;/p&gt;<br>      &lt;button onClick={incrementCount}&gt;Increment Count&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>// Penggunaan komponen provider dan consumer<br>function App() {<br>  return (<br>    &lt;MyProvider&gt;<br>      &lt;MyConsumer /&gt;<br>    &lt;/MyProvider&gt;<br>  );<br>}</pre><p>Pada contoh kode di atas, React Context digunakan untuk menyediakan state count dan fungsi incrementCount pada komponen MyConsumer. Pada komponen MyProvider, state tersebut diberikan nilai awal 0 dan fungsi incrementCount akan menambahkan nilai state count sebanyak 1 setiap kali dipanggil. Dalam hal ini, MyProvider digunakan sebagai parent komponen yang menyediakan state dan fungsi yang dapat diakses oleh child komponen yang terhubung dengan MyConsumer.</p><h3>Perbandingan Redux dan React Context</h3><p>Redux dan React Context merupakan dua pilihan state management yang populer digunakan pada aplikasi React. Namun, keduanya memiliki perbedaan dan kelebihan masing-masing yang harus dipertimbangkan sebelum memilih mana yang sesuai dengan kebutuhan proyek.</p><p><strong>Perbedaan antara Redux dan React Context:</strong></p><ul><li>Redux memisahkan state dari komponen, sehingga state dapat diakses dan dimutakhirkan dari mana saja di dalam aplikasi. Sedangkan React Context menyediakan state yang dapat di-share pada komponen yang berbeda, namun state tersebut hanya dapat diakses oleh komponen yang berada dalam hierarki di bawahnya.</li><li>Redux menggunakan action dan reducer untuk mengubah state, sedangkan React Context dapat langsung dimutakhirkan melalui setState atau useContext hook.</li><li>Redux memiliki devtools yang berguna dalam debugging dan maintenance, sedangkan React Context tidak memiliki fitur serupa.</li></ul><p><strong>Contoh kasus penggunaan Redux dan React Context pada aplikasi React:</strong></p><ul><li>Jika aplikasi memiliki state yang kompleks dan data yang harus di-share pada banyak komponen yang berbeda, sebaiknya menggunakan Redux. Misalnya, pada aplikasi e-commerce yang memiliki keranjang belanja, daftar produk, dan informasi pengguna yang harus diakses dan dimutakhirkan dari banyak halaman dan komponen yang berbeda.</li><li>Jika aplikasi sederhana dan tidak membutuhkan state management yang kompleks, sebaiknya menggunakan React Context. Misalnya, pada aplikasi to-do list yang hanya memiliki beberapa state seperti daftar tugas dan status selesai/belum selesai, dan tidak memerlukan banyak interaksi antara state dan komponen yang berbeda.</li></ul><p>Dalam memilih antara Redux dan React Context, perlu dipertimbangkan juga faktor-faktor seperti skala proyek, tim yang terlibat, dan kebutuhan pengguna.</p><h4>Apa yang sudah kita pahami dari penjelasan diatas ?</h4><p>Setelah mempelajari Redux dan React Context secara mendalam, dapat disimpulkan bahwa kedua library ini memiliki tujuan yang sama, yaitu untuk mengatur state management pada aplikasi React. Namun, keduanya memiliki pendekatan yang berbeda dalam memanage state.</p><p>Redux digunakan untuk mengatur state yang kompleks pada aplikasi React dan memungkinkan untuk memudahkan debugging dan maintenance. Kelebihan dari Redux adalah pengelolaan state yang terpusat dan memungkinkan penggunaan middleware. Namun, kekurangan dari Redux adalah setup yang cukup kompleks dan memerlukan waktu yang lebih lama.</p><p>Sementara itu, React Context digunakan untuk mengatur state yang sederhana pada aplikasi React dan memungkinkan sharing state antar komponen yang berbeda secara langsung. Kelebihan dari React Context adalah penggunaan yang mudah dan fleksibel, serta tidak memerlukan setup yang rumit. Namun, kekurangan dari React Context adalah pengelolaan state yang terdesentralisasi dan tidak memiliki fitur middleware.</p><p>Untuk menentukan kapan sebaiknya menggunakan Redux dan kapan sebaiknya menggunakan React Context, tergantung pada kompleksitas dari state pada aplikasi React yang sedang dibuat. Jika state pada aplikasi React tergolong sederhana, maka penggunaan React Context lebih disarankan. Namun, jika state pada aplikasi React kompleks dan memerlukan middleware, maka Redux lebih cocok digunakan.</p><p>Sumber referensi yang bisa digunakan untuk belajar lebih lanjut tentang Redux dan React Context adalah dokumentasi resmi dari kedua library tersebut, serta berbagai tutorial dan artikel yang tersedia di internet.</p><p>Dalam contoh kasus penggunaan Redux dan React Context pada aplikasi React, misalnya dalam aplikasi e-commerce yang memiliki fitur keranjang belanja. Pada aplikasi yang kompleks, penggunaan Redux lebih disarankan karena memungkinkan penggunaan middleware untuk memproses data transaksi belanja. Namun, jika aplikasi tersebut hanya memiliki sedikit fitur keranjang belanja, penggunaan React Context dapat lebih mudah dan fleksibel untuk digunakan.</p><p>Kesimpulannya, baik Redux maupun React Context memiliki kelebihan dan kekurangan masing-masing, tergantung pada kompleksitas dari state pada aplikasi React yang sedang dibuat. Oleh karena itu, sebaiknya mempertimbangkan dengan baik sebelum memilih untuk menggunakan Redux atau React Context dalam mengatur state pada aplikasi React.</p><p>Untuk belajar lebih lanjut tentang Redux dan React Context, ada banyak sumber referensi yang dapat dijadikan acuan, seperti dokumentasi resmi, buku, artikel, dan video tutorial. Dengan memahami perbedaan antara Redux dan React Context serta kelebihan dan kekurangannya, pengembang dapat membuat keputusan yang tepat dalam memilih teknologi yang cocok untuk aplikasi yang sedang dibuat.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f4c90f84bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Panduan Lengkap Menggunakan Redux Toolkit di Next.js]]></title>
            <link>https://medium.com/@aryandi/panduan-lengkap-menggunakan-redux-toolkit-di-next-js-d54ad5a466f2?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/d54ad5a466f2</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nextjs-tutorial]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 03:10:20 GMT</pubDate>
            <atom:updated>2023-04-02T03:10:20.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipaKHi-03hF8yD-wXjGzRA.jpeg" /><figcaption><strong>Source: unsplash.com</strong></figcaption></figure><p>Jika Anda sudah mengenal Redux sebelumnya, Anda mungkin merasa sedikit kesulitan dalam mengatur state yang kompleks pada aplikasi React. Hal ini karena implementasi Redux yang sebelumnya membutuhkan boilerplate code yang cukup banyak, terutama saat menangani state yang kompleks dan melakukan asinkronisitas. Namun, dengan hadirnya Redux Toolkit, proses ini menjadi lebih mudah dan lebih efisien.</p><p>Redux Toolkit adalah sebuah package yang menyediakan pendekatan baru dalam menggunakan Redux. Redux Toolkit memberikan tools yang berguna untuk membuat aplikasi dengan state management yang lebih mudah dan cepat. Redux Toolkit menyediakan beberapa fitur tambahan yang dapat memudahkan pengguna dalam mengelola state di aplikasi mereka, seperti menyediakan utilities untuk menghasilkan reducers dan actions secara otomatis, menyederhanakan pembuatan store, dan menyederhanakan pembuatan kode.</p><h4>Apa perbedaan Redux Toolkit dengan Redux biasa?</h4><p>Redux Toolkit memberikan beberapa peningkatan yang dapat memudahkan pengguna dalam menggunakan Redux, di antaranya:</p><ul><li><strong>Mengurangi boilerplate code</strong></li></ul><p>Dalam implementasi Redux sebelumnya, terdapat banyak boilerplate code yang harus ditulis untuk membuat sebuah store, reducer, dan action creator. Redux Toolkit menyederhanakan proses ini dengan mengurangi boilerplate code yang perlu ditulis. Redux Toolkit menyediakan createSlice dan createAsyncThunk untuk membuat slice dan action secara otomatis.</p><ul><li><strong>Mendukung Immutable State</strong></li></ul><p>Immutable State adalah state yang tidak dapat diubah setelah dibuat. Redux Toolkit mendukung Immutable State, sehingga memudahkan pengguna dalam memanipulasi state dengan mudah tanpa merusak data aslinya.</p><ul><li><strong>Menyederhanakan proses pembuatan store</strong></li></ul><p>Redux Toolkit menyederhanakan proses pembuatan store dengan menggunakan configureStore. configureStore menyediakan beberapa middleware, seperti redux-thunk, redux-logger, dan redux-devtools, yang dapat digunakan untuk mempercepat proses development.</p><ul><li><strong>Mendukung pembuatan kode yang lebih sederhana</strong></li></ul><p>Redux Toolkit memberikan banyak utility functions yang memudahkan pengguna dalam membuat kode yang lebih sederhana. Dengan menggunakan createSlice dan createAsyncThunk, pengguna dapat membuat kode yang lebih efisien dan lebih mudah untuk dibaca dan dimengerti.</p><p>Dalam keseluruhan, Redux Toolkit memberikan banyak keuntungan dalam mengelola state di aplikasi Anda dengan mudah dan cepat.</p><p>Sebelum kita membahas cara menggunakan Redux Toolkit di Next.js, saya akan memberikan sedikit penjelasan mengenai Next.js bagi yang belum familiar.</p><h4><strong>Sedikit ringkasan tentang Nextjs</strong></h4><p>Next.js adalah sebuah framework yang dibangun di atas React yang memungkinkan kita untuk membuat aplikasi web yang efisien dan powerful. Dalam pengembangan web modern, performance dan efisiensi sangatlah penting. Next.js menawarkan solusi untuk masalah ini dengan memberikan beberapa keuntungan, di antaranya:</p><p><strong>Apa itu Next.js?</strong><br>Next.js adalah sebuah framework yang mengintegrasikan berbagai fitur dan kemampuan React untuk membangun aplikasi web modern. Dalam pengembangan web, Next.js menyediakan beberapa fitur seperti routing, rendering pada sisi server (server-side rendering), pengaturan bundling dan optimasi, dan masih banyak lagi.</p><p>Dalam penggunaannya, Next.js memungkinkan kita untuk membuat aplikasi web dengan lebih mudah, cepat, dan efisien. Dalam pengembangan web modern, performa sangatlah penting, terutama dengan semakin meningkatnya kebutuhan akan aplikasi yang responsif dan cepat.</p><p><strong>Keuntungan Menggunakan Next.js</strong><br>Ada beberapa keuntungan yang bisa kita dapatkan dengan menggunakan Next.js dalam pengembangan aplikasi web:</p><ul><li><strong>Server-side rendering (SSR)</strong><br>Salah satu fitur utama dari Next.js adalah kemampuannya dalam melakukan server-side rendering. Dalam pengembangan aplikasi web, SSR memungkinkan kita untuk mengoptimalkan performa dan kecepatan tampilan halaman dengan cara merender halaman di sisi server sebelum dikirim ke client.</li><li><strong>Static site generation (SSG)</strong><br>Next.js juga mendukung static site generation, yaitu menghasilkan situs statis dengan konten yang dinamis. Hal ini memungkinkan kita untuk membangun situs web yang responsif dan cepat, dengan cara membangun halaman HTML statis untuk setiap rute.</li><li><strong>Automatic code splitting</strong><br>Next.js secara otomatis memecah kode aplikasi menjadi beberapa bagian (code splitting), sehingga halaman dapat dimuat secara lebih cepat dan performa aplikasi lebih baik.</li><li><strong>Routing yang mudah</strong><br>Next.js memiliki sistem routing yang sederhana dan mudah digunakan, sehingga memudahkan kita dalam membuat navigasi di dalam aplikasi.</li><li><strong>Pengaturan optimasi</strong><br>Next.js telah dilengkapi dengan berbagai optimasi, seperti optimasi gambar dan lazy loading, yang membuat performa aplikasi semakin baik.</li></ul><p>Dengan keuntungan-keuntungan di atas, Next.js menjadi framework yang powerful dan efisien dalam pengembangan aplikasi web modern.</p><h4><strong>Implementasi Redux Toolkit di Next.js</strong></h4><p>Oke, Here we go, selanjutnya kita akan membahas bagaimana cara menggunakan Redux Toolkit di Next.js.</p><p>Untuk memulai membuat proyek Next.js, Anda bisa mengikuti dokumentasi resmi di situs Next.js. Namun, sebagai permulaan, kita bisa menggunakan perintah create-next-app dari npm:</p><pre>npx create-next-app my-app</pre><p>Setelah membuat proyek Next.js, langkah selanjutnya adalah menginstal Redux Toolkit. Anda bisa melakukan instalasi dengan menjalankan perintah:</p><pre>npm install @reduxjs/toolkit</pre><p>Sama seperti pada penggunaan Redux pada umumnya, langkah selanjutnya adalah membuat store. Namun, Redux Toolkit menyediakan API yang lebih mudah digunakan yaitu configureStore(). Kita bisa membuat store dengan kode berikut:</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br><br>const store = configureStore({<br>  reducer: {<br>    // set reducer disini<br>  }<br>})</pre><p>Setelah membuat store, selanjutnya adalah menghubungkan slice dengan store dan menggunakan state serta action di komponen Next.js.</p><ul><li><strong>Membuat slice untuk mengatur state tertentu</strong></li></ul><p>Pada Redux Toolkit, state diatur dalam slice. Slice adalah fungsi yang menghasilkan reducer dan action creator untuk suatu bagian dari state. Berikut adalah contoh pembuatan slice untuk mengatur state theme:</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;<br><br>const themeSlice = createSlice({<br>  name: &#39;theme&#39;,<br>  initialState: {<br>    value: &#39;light&#39;,<br>  },<br>  reducers: {<br>    toggleTheme: state =&gt; {<br>      state.value = state.value === &#39;light&#39; ? &#39;dark&#39; : &#39;light&#39;<br>    }<br>  }<br>})<br><br>export const { toggleTheme } = themeSlice.actions<br>export default themeSlice.reducer</pre><ul><li><strong>Menghubungkan slice dengan store</strong></li></ul><p>Setelah membuat slice, kita perlu menghubungkannya dengan store agar bisa digunakan di komponen Next.js. Caranya dengan mengimpor slice tersebut dan menambahkannya pada parameter reducer di configureStore() seperti contoh berikut:</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>import themeReducer from &#39;./themeSlice&#39;<br><br>const store = configureStore({<br>  reducer: {<br>    theme: themeReducer<br>  }<br>})</pre><ul><li><strong>Menggunakan state dan action di komponen Next.js</strong></li></ul><p>Setelah slice dihubungkan dengan store, kita bisa menggunakan state dan action di komponen Next.js dengan bantuan hooks useSelector dan useDispatch dari react-redux. Berikut contoh penggunaannya di komponen:</p><pre>import { useSelector, useDispatch } from &#39;react-redux&#39;<br>import { toggleTheme } from &#39;../redux/themeSlice&#39;<br><br>function MyApp() {<br>  const theme = useSelector(state =&gt; state.theme.value)<br>  const dispatch = useDispatch()<br><br>  const handleThemeToggle = () =&gt; {<br>    dispatch(toggleTheme())<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleThemeToggle}&gt;Toggle Theme&lt;/button&gt;<br>      &lt;p&gt;Current theme: {theme}&lt;/p&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Menyimpan data pada server side dengan getServerSideProps</p><p>Next.js menyediakan fitur untuk melakukan rendering pada sisi server. Pada sisi server, kita bisa menggunakan data yang diperoleh dari API atau database untuk dirender menjadi HTML. Fitur ini disebut server-side rendering (SSR). Untuk mengambil data pada sisi server, kita bisa menggunakan fungsi getServerSideProps yang disediakan oleh Next.js. Fungsi ini dijalankan pada sisi server dan mengembalikan props yang akan digunakan pada saat rendering.</p><p>Berikut contoh penggunaan getServerSideProps untuk mengambil data dari API:</p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;<br>import { Provider } from &#39;react-redux&#39;<br>import themeReducer from &#39;./themeSlice&#39;<br><br>const store = configureStore({<br>  reducer: {<br>    theme: themeReducer<br>  }<br>})<br><br>function MyApp({ theme }) {<br>  const dispatch = useDispatch()<br><br>  const handleThemeToggle = () =&gt; {<br>    dispatch(toggleTheme())<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleThemeToggle}&gt;Toggle Theme&lt;/button&gt;<br>      &lt;p&gt;Current theme: {theme}&lt;/p&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export async function getServerSideProps() {<br>  // fetch data from API<br>  const res = await fetch(&#39;https://example.com/api/theme&#39;)<br>  const data = await res.json()<br><br>  // return data as props<br>  return {<br>    props: {<br>      theme: data.theme<br>    }<br>  }<br>}<br><br>export default function App() {<br>  return (<br>    &lt;Provider store={store}&gt;<br>      &lt;MyApp /&gt;<br>    &lt;/Provider&gt;<br>  )<br>}</pre><p>Pada contoh di atas, kita mengambil data theme dari API dengan fungsi getServerSideProps dan mengirimnya sebagai props ke komponen MyApp. Selanjutnya, kita bisa menggunakan data tersebut di komponen dengan hooks useSelector dan useDispatch seperti contoh sebelumnya. Perlu diingat bahwa fungsi getServerSideProps hanya berjalan pada sisi server, sehingga kita tidak bisa menggunakan hooks seperti useState pada fungsi tersebut.</p><p>Okeeee, Setelah mempelajari pengenalan Redux Toolkit dan implementasinya di Next.js, kita dapat menyimpulkan beberapa kelebihan dari menggunakan Redux Toolkit di Next.js dan memberikan rekomendasi untuk belajar lebih lanjut tentang kedua teknologi tersebut.</p><ol><li>Kelebihan menggunakan Redux Toolkit di Next.js<br>- Lebih mudah digunakan dan dipelajari daripada Redux pada umumnya.<br>- Menyediakan API yang lebih sederhana seperti configureStore() dan createSlice() yang memudahkan penggunaan Redux.<br>- Mengurangi boilerplate code yang harus ditulis.<br>- Lebih aman dari kesalahan penulisan kode dan bugs di Redux.</li><li>Rekomendasi belajar lebih lanjut tentang Redux Toolkit dan Next.js<br>- Pelajari dokumentasi resmi dari Redux Toolkit dan Next.js untuk memahami fitur dan fungsionalitas yang lebih dalam.<br>- Ikuti kursus online atau tutorial yang menyediakan pengenalan dan implementasi Redux Toolkit di Next.js.<br>- Terus latih diri untuk mengimplementasikan Redux Toolkit di projek-projek yang lebih kompleks untuk menguasai teknologi ini dengan lebih baik.</li></ol><p>Dalam projek-projek Next.js yang kompleks dan memerlukan manajemen state yang terstruktur dan mudah diimplementasikan, Redux Toolkit dapat menjadi pilihan yang tepat untuk digunakan. Dengan fitur-fiturnya yang sederhana dan mudah dipelajari, Redux Toolkit dapat membantu kita menghemat waktu dalam menulis kode dan mengurangi kesalahan yang mungkin terjadi di dalamnya. Oleh karena itu, sangat direkomendasikan untuk mempelajari dan mengimplementasikan Redux Toolkit di Next.js.</p><p>Dalam artikel ini, kita telah membahas pengenalan Redux Toolkit, Next.js, serta implementasi Redux Toolkit di Next.js secara lengkap dan jelas. Kita juga telah mengetahui kelebihan menggunakan Redux Toolkit di Next.js dan diberikan rekomendasi untuk belajar lebih lanjut tentang kedua teknologi ini. Semoga artikel ini dapat membantu Anda dalam memahami cara menggunakan Redux Toolkit di Next.js untuk mengatur state secara efisien dan mudah. 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d54ad5a466f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Redux: Memahami Data Flow pada React]]></title>
            <link>https://medium.com/@aryandi/simplifying-redux-memahami-data-flow-pada-react-87126e2d4a9c?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/87126e2d4a9c</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 02:13:03 GMT</pubDate>
            <atom:updated>2023-04-04T05:25:59.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fClA95TjSzEbadpjj9LHtA.jpeg" /><figcaption><strong>Source: unsplash.com</strong></figcaption></figure><p>Jika Anda sudah pernah mengembangkan aplikasi dengan React, mungkin Anda sudah tidak asing lagi dengan Redux. Redux adalah sebuah library state management yang memungkinkan Anda mengatur state aplikasi secara terpusat. Namun, jika Anda baru memulai belajar React, mungkin Anda masih bingung dengan konsep Redux.</p><p>Sebelum kita memahami konsep Redux, mari kita bahas terlebih dahulu bagaimana <em>state management</em> dilakukan di React tanpa Redux. <em>State management</em> merupakan salah satu hal yang penting dalam pengembangan aplikasi, karena state dapat memengaruhi tampilan dan interaksi pengguna dengan aplikasi.</p><p>Dalam React, state dapat diatur pada komponen dan diubah menggunakan fungsi <em>setState()</em>. Sebagai contoh, kita memiliki sebuah komponen <em>Counter</em> yang dapat menampilkan angka dan tombol untuk menambah atau mengurangi angka tersebut:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>function Counter() {<br>  // State: a counter value<br>  const [count, setCount] = useState(0);<br><br>  // Action: code that causes an update to the state when something happens<br>  const handleIncrement = () =&gt; {<br>    setCounter(prevCounter =&gt; prevCounter + 1)<br>  }<br><br>  // Action: code that causes an update to the state when something happens<br>  const handleDecrement = () =&gt; {<br>    setCounter(prevCounter =&gt; prevCounter - 1)<br>  }<br><br>  // View: the UI definition<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;<br>      &lt;button onClick={handleIncrement&gt;+&lt;/button&gt;<br>      &lt;button onClick={handleDecrement&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>Kode di atas menunjukkan bahwa state diatur pada variabel count dengan nilai awal 0. Ketika tombol + atau - ditekan, fungsi <em>setCount</em> akan dipanggil untuk mengubah nilai <em>count</em> sesuai dengan operasi yang dilakukan.</p><p>Namun, ketika aplikasi semakin kompleks dan state semakin banyak, penanganan state menggunakan <em>setState()</em> di setiap komponen dapat menjadi sulit dan tidak efisien. Inilah alasan mengapa Redux dibutuhkan di React.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*PBgAz9U9SrkINPo-n5glgw.gif" /></figure><p>Untuk memperjelas, mari kita gambarkan aplikasi React tanpa Redux. Aplikasi ini terdiri dari beberapa komponen dan memiliki state yang harus dikelola. State disimpan pada komponen paling atas (<em>root</em>) dan kemudian dilewatkan sebagai props ke komponen-komponen lainnya. Ketika state diubah, fungsi <em>setState()</em> harus dipanggil di komponen root dan dilewatkan kembali sebagai props ke komponen-komponen lainnya.</p><p>Ini disebut “<em>one-way data flow</em>”, karena data hanya dapat mengalir dari root ke komponen-komponen lainnya, dan bukan sebaliknya. Hal ini dapat membuat penanganan state menjadi rumit dan sulit dipelihara ketika aplikasi semakin kompleks. Inilah masalah yang dipecahkan oleh Redux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mD6hH2jyPWoyKeE-r-ptxw.png" /><figcaption><strong>Source: redux.js.org</strong></figcaption></figure><h4>Jadi, Apa Itu Redux?</h4><p>Redux adalah <em>library open-source</em> JavaScript yang memungkinkan Anda mengelola state aplikasi dengan mudah. Redux menyimpan seluruh state aplikasi pada satu tempat yang disebut sebagai store, yang kemudian dapat diakses dan dikelola dari mana saja dalam aplikasi. Dengan Redux, state dapat diperbarui dengan cara yang terstruktur dan terprediksi melalui tiga konsep utama: <strong><em>state, action, dan reducer.</em></strong></p><h4>Kenapa Redux dibutuhkan di React?</h4><p>Pada saat membangun aplikasi dengan React, mungkin Anda pernah mengalami kesulitan dalam mengelola state. Dalam beberapa kasus, state perlu diakses oleh banyak komponen dalam aplikasi, dan memperbarui state pada satu komponen dapat memengaruhi tampilan komponen lainnya. Dalam kasus seperti ini, Redux dapat membantu mengelola state secara terpusat dan menyederhanakan alur data dalam aplikasi Anda.</p><p>Dengan Redux, Anda dapat menyimpan state pada store, yang dapat diakses dan diperbarui dari mana saja dalam aplikasi. Komponen-komponen dalam aplikasi hanya perlu melakukan <em>subscribe</em> pada store untuk mengakses state yang dibutuhkan, dan Redux akan secara otomatis memperbarui komponen-komponen tersebut ketika terjadi perubahan pada state.</p><h4>State, Action, dan Reducer</h4><p>Redux terdiri dari tiga konsep dasar, yaitu state, action, dan reducer. Dalam artikel ini, kita akan membahas secara singkat mengenai ketiga konsep tersebut.</p><ul><li><strong>State</strong></li></ul><p>State adalah sebuah objek yang merepresentasikan seluruh kondisi dari aplikasi pada sebuah waktu tertentu. State di Redux dapat disebut juga sebagai global state atau application state. Redux memisahkan state dari komponen React, sehingga state tidak lagi disimpan di dalam komponen, namun disimpan di dalam store.</p><ul><li><strong>Action</strong></li></ul><p>Action adalah objek sederhana yang mengandung informasi mengenai sebuah event yang terjadi di dalam aplikasi. Setiap action harus memiliki sebuah properti ‘type’ yang menjelaskan tipe dari action tersebut. Type ini biasanya dinyatakan dalam bentuk string.</p><p>Action digunakan untuk memberitahu reducer tentang perubahan state yang akan terjadi. Ketika action di-dispatch, reducer akan menerima action tersebut dan mengembalikan state yang baru berdasarkan action tersebut.</p><p>Contoh sederhana penggunaan action pada Redux:</p><pre>const ADD_TODO = &#39;ADD_TODO&#39;<br><br>const addTodo = (text) =&gt; {<br>  return {<br>    type: ADD_TODO,<br>    text<br>  }<br>}</pre><p>Pada contoh di atas, kita membuat sebuah action creator bernama addTodo yang digunakan untuk menambahkan sebuah todo ke dalam list. Action tersebut memiliki sebuah properti <em>type</em> yang bernilai ‘<strong><em>ADD_TODO</em></strong>’ dan sebuah properti ‘<strong><em>text</em></strong>’ yang berisi teks todo.</p><ul><li><strong>Reducer</strong></li></ul><p>Reducer adalah sebuah fungsi yang digunakan untuk mengubah state menjadi state yang baru berdasarkan action yang diterima. Reducer harus bersifat pure, artinya fungsi tersebut tidak boleh melakukan perubahan pada argumen yang diterima dan tidak boleh memiliki efek samping yang tidak diinginkan.</p><p>Reducer biasanya memiliki dua argumen, yaitu state dan action. State pada reducer merupakan state sebelumnya yang akan diubah menjadi state yang baru. Sedangkan action merupakan objek yang berisi informasi mengenai perubahan state yang akan terjadi.</p><p>Contoh sederhana penggunaan reducer pada Redux:</p><pre>const initialState = {<br>  todos: []<br>}<br><br>const todoReducer = (state = initialState, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;ADD_TODO&#39;:<br>      return {<br>        ...state,<br>        todos: [...state.todos, {text: action.text}]<br>      }<br>    default:<br>      return state<br>  }<br>}</pre><p>Pada contoh di atas, kita membuat sebuah reducer bernama todoReducer yang memiliki sebuah state awal bernama initialState. Reducer tersebut memiliki sebuah switch statement yang mengecek tipe dari action yang diterima. Jika tipe action adalah ‘ADD_TODO’, reducer akan mengembalikan state yang baru dengan menambahkan todo baru pada state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*T_Q66EkNEhca6TyrvY1xBQ.gif" /></figure><h4>Data Flow dalam Redux</h4><p>Redux memiliki tiga konsep utama dalam mengatur alur data, yaitu store, dispatch, dan subscribe. Ketiga konsep ini berperan penting dalam memastikan alur data berjalan dengan baik di aplikasi yang menggunakan Redux.</p><ul><li><strong>Store</strong></li></ul><p>Store adalah tempat penyimpanan state secara global. Redux mengatur state aplikasi secara terpusat di dalam store, sehingga memudahkan kita untuk mengelola dan memperbarui state aplikasi.</p><p>Pada contoh kode berikut, kita membuat store dengan menggunakan fungsi createStore() dari Redux:</p><pre>import { createStore } from &#39;redux&#39;;<br><br>const initialState = {<br>  counter: 0<br>};<br><br>const counterReducer = (state = initialState, action) =&gt; {<br>  if (action.type === &#39;increment&#39;) {<br>    return {<br>      counter: state.counter + 1<br>    };<br>  }<br><br>  if (action.type === &#39;decrement&#39;) {<br>    return {<br>      counter: state.counter - 1<br>    };<br>  }<br><br>  return state;<br>};<br><br>const store = createStore(counterReducer);</pre><p>Dalam contoh kode di atas, kita membuat store dengan menggunakan createStore() dari Redux. createStore() menerima satu parameter yaitu reducer, yang sudah dibahas pada bagian sebelumnya. initialState digunakan untuk menyimpan nilai awal dari state, dalam contoh ini kita menginisialisasi counter dengan nilai 0.</p><ul><li><strong>Dispatch</strong></li></ul><p>Dispatch digunakan untuk memperbarui state di dalam store. Dispatch akan mengirim sebuah objek yang berisi informasi tentang perubahan yang akan dilakukan pada state.</p><p>Pada contoh kode berikut, kita menggunakan dispatch untuk menambah nilai counter pada state:</p><pre>store.dispatch({ type: &#39;increment&#39; });</pre><p>Dalam contoh kode di atas, kita menggunakan dispatch untuk menambah nilai counter pada state dengan mengirimkan sebuah objek yang berisi type yang bernilai ‘increment’. Nantinya reducer akan menerima objek tersebut dan melakukan perubahan sesuai dengan action yang diterima.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYkitaR24SuFNXYyTxL1xA.gif" /><figcaption><strong>source: redux.js.org</strong></figcaption></figure><h4>Implementasi Redux di React</h4><p>Sekarang, kita sudah mempelajari konsep dasar Redux dan data flow di Redux. Pada bagian ini, kita akan membahas bagaimana mengimplementasikan Redux di React. Ada beberapa tahapan yang harus dilakukan untuk mengimplementasikan Redux di React, yaitu membuat store, membuat reducer, membuat action creator, dan menghubungkan React dengan Redux.</p><ul><li><strong>Membuat Store</strong></li></ul><p>Store adalah tempat penyimpanan state aplikasi secara terpusat. State di Redux disebut sebagai store, dan semua data yang ada di dalam store dapat diakses dan dimanipulasi melalui reducer dan action creator. Untuk membuat store, kita perlu mengimpor createStore dari redux dan reducer yang telah kita buat sebelumnya. Berikut contohnya:</p><pre>const initialState = {<br>  counter: 0,<br>};<br><br>const reducer = (state = initialState, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return {<br>        counter: state.counter + 1,<br>      };<br>    case &#39;DECREMENT&#39;:<br>      return {<br>        counter: state.counter - 1,<br>      };<br>    default:<br>      return state;<br>  }<br>};</pre><p>Pada contoh di atas, kita mengimpor createStore dari redux dan reducer yang telah kita buat sebelumnya. Selanjutnya, kita membuat store dengan createStore(reducer).</p><ul><li><strong>Membuat Reducer</strong></li></ul><p>Reducer adalah sebuah function yang memproses action dan mengembalikan state baru. Reducer menerima dua parameter, yaitu state saat ini dan action yang dipanggil. Setiap kali action dipanggil, reducer akan memproses action tersebut dan mengembalikan state yang baru. Berikut contohnya:</p><pre>const initialState = {<br>  counter: 0,<br>};<br><br>const reducer = (state = initialState, action) =&gt; {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return {<br>        counter: state.counter + 1,<br>      };<br>    case &#39;DECREMENT&#39;:<br>      return {<br>        counter: state.counter - 1,<br>      };<br>    default:<br>      return state;<br>  }<br>};</pre><p>Pada contoh di atas, initialState adalah nilai awal dari state, dan reducer adalah function yang memproses action dan mengembalikan state yang baru. Reducer menerima dua parameter, yaitu state saat ini dan action yang dipanggil. Setiap kali action dipanggil, reducer akan memproses action tersebut dan mengembalikan state yang baru.</p><ul><li><strong>Membuat Action Creator</strong></li></ul><p>Action creator adalah sebuah function yang menghasilkan action yang akan dipanggil oleh reducer. Action creator mengembalikan object yang memiliki tipe dan payload sebagai properti. Tipe adalah tanda bahwa action tersebut dipanggil, dan payload adalah data yang dikirimkan bersama action. Berikut contohnya:</p><pre>const increment = () =&gt; {<br>  return {<br>    type: &#39;INCREMENT&#39;,<br>  };<br>};<br><br>const decrement = () =&gt; {<br>  return {<br>    type: &#39;DECREMENT&#39;,<br>  };<br>};</pre><p>Pada contoh di atas, increment dan decrement adalah action creator yang menghasilkan action INCREMENT dan DECREMENT. Action INCREMENT dan DECREMENT memiliki tipe yang berbeda, namun keduanya tidak memiliki payload.</p><ul><li><strong>Menghubungkan React dengan Redux</strong></li></ul><p>Untuk menghubungkan React dengan Redux, kita perlu mengimpor Provider dari react-redux dan store yang telah kita buat sebelumnya. Setelah itu, kita harus melapisi komponen utama dengan Provider dan melewatkan store sebagai properti. Berikut contohnya:</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import { Provider } from &#39;react-redux&#39;;<br>import store from &#39;./store&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><p>Di dalam kode di atas, kita mengimpor Provider dari react-redux dan store dari file ./store yang telah kita buat sebelumnya. Kita kemudian melapisi komponen App dengan Provider dan melewatkan store sebagai properti. Setelah itu, kita merender komponen App dengan ReactDOM.render() dan melewatkan hasilnya ke dalam elemen dengan id “root”. Dengan cara ini, kita telah berhasil menghubungkan React dengan Redux.</p><p>Setelah kita berhasil mengimplementasikan Redux di React, kita dapat membuat komponen yang terhubung dengan store yang kita buat sebelumnya. Berikut adalah contoh implementasi komponen Counter yang terhubung dengan store Redux:</p><pre>import React from &#39;react&#39;;<br>import { connect } from &#39;react-redux&#39;;<br>import { increment, decrement } from &#39;../redux/actions&#39;;<br><br>const Counter = ({ count, increment, decrement }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Counter: {count}&lt;/h1&gt;<br>      &lt;button onClick={increment}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={decrement}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>const mapStateToProps = (state) =&gt; ({<br>  count: state.count,<br>});<br><br>const mapDispatchToProps = {<br>  increment,<br>  decrement,<br>};<br><br>export default connect(mapStateToProps, mapDispatchToProps)(Counter);</pre><p>Pada kode di atas, kita mengimport React dan dua fungsi dari react-redux yaitu connect dan Provider. Kita juga mengimport dua action creator yaitu increment dan decrement dari file actions.js yang sudah kita buat sebelumnya.</p><p>Selanjutnya, kita membuat komponen Counter yang menerima props count, increment, dan decrement. Pada fungsi mapStateToProps, kita mengambil state.count dari store dan melewatkan nilai tersebut ke dalam props count. Pada fungsi mapDispatchToProps, kita melewatkan dua action creator yaitu increment dan decrement ke dalam props sehingga kita dapat mengaksesnya di dalam komponen Counter.</p><p>Terakhir, kita menghubungkan komponen Counter dengan store Redux menggunakan fungsi connect. Fungsi mapStateToProps akan mengambil state dari store dan melewatkan props count ke dalam komponen Counter. Fungsi mapDispatchToProps akan menghubungkan action creator increment dan decrement ke dalam props sehingga kita dapat mengaksesnya di dalam komponen Counter.</p><p>Dengan mengimplementasikan komponen Counter yang terhubung dengan store Redux, kita dapat dengan mudah menambahkan fitur-fitur baru seperti menambahkan kondisi ketika count mencapai nilai tertentu, menambahkan tombol reset, dan masih banyak lagi.</p><p>Setelah kita mempelajari konsep dasar Redux dan melihat contoh implementasinya dalam aplikasi React, sekarang kita tahu bagaimana Redux dapat membantu kita mengelola state aplikasi secara efektif dan efisien. Namun, perlu diingat bahwa Redux memiliki learning curve yang cukup curam dan membutuhkan banyak boilerplate code untuk mengatur store, action, reducer, dan sebagainya.</p><p>Untuk mengatasi masalah tersebut, Redux menyediakan sebuah library bernama Redux Toolkit. Redux Toolkit menyederhanakan proses pengaturan store, menyediakan utility functions untuk membuat action dan reducer, serta menyediakan beberapa fitur lain yang membantu dalam pengembangan aplikasi menggunakan Redux.</p><p>Dengan menggunakan Redux Toolkit, kita dapat menghemat waktu dan usaha dalam membangun aplikasi dengan Redux. Namun, kita masih perlu memahami konsep dasar Redux terlebih dahulu sebelum mulai menggunakan Redux Toolkit.</p><p>Semoga artikel ini dapat membantu pemula untuk memahami konsep Redux dan dapat memberikan wawasan tambahan bagi yang sudah terbiasa menggunakan Redux sebelumnya.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jipzCYTOS4HSpSAY_ceLKQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87126e2d4a9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Asynchronous and Synchronous in Javascript]]></title>
            <link>https://medium.com/@aryandi/understanding-asynchronous-and-synchronous-in-javascript-55ae032aa3ef?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/55ae032aa3ef</guid>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Sat, 01 Apr 2023 21:12:16 GMT</pubDate>
            <atom:updated>2023-04-01T21:12:16.630Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6zXwgaA0Madbw7E8yk7uw.jpeg" /><figcaption>source: <a href="https://unsplash.com/photos/tvHtIGbbjMo">https://unsplash.com/photos/tvHtIGbbjMo</a></figcaption></figure><p>Asynchronous and synchronous are two terms that are commonly used in programming, including in JavaScript. Synchronous refers to the process in which each task is executed sequentially, one after another. In other words, the program has to complete the first task before moving on to the next task. This is also known as blocking, because each task blocks the execution of the next task until it is completed.</p><p>On the other hand, asynchronous refers to the process in which multiple tasks are executed simultaneously or at the same time. Unlike synchronous programming, the program does not have to wait for each task to finish before moving on to the next task. Instead, tasks are executed independently of each other, allowing for greater efficiency and speed in executing multiple tasks at once.</p><p>Understanding the difference between asynchronous and synchronous is important because it can affect program performance and functionality. In JavaScript, for example, asynchronous processes can help prevent the program from freezing or crashing while waiting for a specific task to complete. By allowing multiple tasks to run simultaneously, the program can continue to execute other functions, resulting in a more responsive and efficient application.</p><p>Overall, asynchronous and synchronous are two important concepts in programming, and mastering these concepts can help developers build faster, more efficient, and more reliable applications.</p><h3>Synchronous</h3><p>Synchronous is a method of executing code sequentially, or one after the other. This means that the program has to complete one task before moving on to the next in a predetermined order. Synchronous can cause the program to get stuck for a long time while completing a task before moving on to the next. This often results in slow and unresponsive program performance.</p><p>A simple example of synchronous is when we create a function that takes a long time to execute, such as requesting data from a server. In this example, the program will wait until the data request is complete before continuing with the execution of other code. If there are several data requests to be made, then the program will pause at the first request until it is complete, before moving on to the next request.</p><p>Synchronous is usually used when a clear sequence of code execution is required, or when waiting for a specific task to complete is an important part of the program.</p><p>Here is a simple example of using synchronous in JavaScript. In this example, we will create two functions that take a long time to execute, then execute them one after the other:</p><pre>function fungsiA() {<br>  console.log(&#39;Memulai fungsi A&#39;);<br>  for (let i = 0; i &lt; 5; i++) {<br>    console.log(i);<br>  }<br>  console.log(&#39;Selesai fungsi A&#39;);<br>}<br>function fungsiB() {<br>  console.log(&#39;Memulai fungsi B&#39;);<br>  for (let i = 0; i &lt; 5; i++) {<br>    console.log(i);<br>  }<br>  console.log(&#39;Selesai fungsi B&#39;);<br>}<br>fungsiA();<br>fungsiB();</pre><p>The output produced is:</p><pre>Memulai fungsi A<br>0<br>1<br>2<br>3<br>4<br>Selesai fungsi A<br>Memulai fungsi B<br>0<br>1<br>2<br>3<br>4<br>Selesai fungsi B</pre><p>Because functions A and B are executed sequentially, function B will not be executed until function A has finished executing.</p><h3>Asynchronous</h3><p>Before we dive into a detailed explanation of asynchronous, let’s first understand the concept of synchronous that we discussed earlier. As explained earlier, in synchronous, the process of executing code is done gradually and one by one, so one command must wait for the previous command to finish executing.</p><p>However, in asynchronous, code execution is done simultaneously and does not have to wait for the previous command to finish executing. This means that multiple commands can be executed simultaneously, without having to wait for each other.</p><p>To understand asynchronous, let’s look at a simple example below:</p><pre>console.log(&#39;Program dimulai&#39;);<br>setTimeout(function() {<br>  console.log(&#39;Fungsi 1 selesai dieksekusi&#39;);<br>}, 2000);<br>console.log(&#39;Ini adalah fungsi 2&#39;);</pre><p>In the above example, we use the setTimeout() function to provide a delay of 2 seconds before executing the next command. In this case, we provide a delay of 2 seconds before executing the command inside the given function.</p><p>In asynchronous programming, we use callbacks to execute functions after another function has finished executing. In the example above, we provide a callback function to the setTimeout() function to execute the command after the other function has finished executing.</p><p>By using asynchronous programming, our program becomes more efficient and responsive. We can perform multiple tasks simultaneously without having to wait for one task to finish before starting another.</p><h4>Asynchronous and Synchronous, when should they be used?</h4><p>After understanding the basic concepts of Asynchronous and Synchronous, it’s time to discuss when we should use each of these concepts. We need to understand that each situation has different needs. Therefore, as a developer, we must understand the situation and needs of each project we are working on before deciding to use the Asynchronous or Synchronous concept.</p><p>Generally, Synchronous is suitable when we need accurate results and the correct order of code execution. For example, when we want to perform complex mathematical calculations, we must wait until the calculation is complete before moving on to the next stage. An example of using Synchronous in code can be seen in the simple addition function example below:</p><pre>function addNumbers(a, b) {<br>  return a + b;<br>}<br>let result = addNumbers(2, 3);<br>console.log(result); // Output: 5</pre><p>On the other hand, Asynchronous is more suitable when we want to perform multiple tasks simultaneously without having to wait for one task to finish before executing the next task. For example, when we want to retrieve data from a database and display that data on a website page. We can use Asynchronous to allow the website to continue running without having to wait for the data retrieval to finish. An example of using Asynchronous in code can be seen in the following simple setTimeout() function:</p><pre>console.log(&quot;Start&quot;);<br><br>// menjalankan setTimeout dalam callback function<br>setTimeout(() =&gt; {<br>  console.log(&quot;Finish&quot;);<br>}, 3000);<br><br>console.log(&quot;Next Task&quot;);</pre><p>In the example above, after executing the function console.log(“Start”), the program will wait for 3 seconds before executing the functions console.log(“Finish”) and console.log(“Next Task”). The code execution process is not blocked during the 3 seconds wait.</p><p>You may wonder why we used setTimeout() as an example. setTimeout() is used to simulate a 3-second wait time. With setTimeout(), the program will execute the callback function after the specified wait time without having to wait for the process to complete, allowing the code execution process in the program to remain unblocked and continue running.</p><p>We can also use both concepts together to improve program performance, such as when we want to retrieve data from multiple APIs simultaneously and display the data in order. We can use Asynchronous to retrieve data from multiple APIs simultaneously, and then use Synchronous to sort and display the data on the website page. Here is an example to make it clearer 😄</p><pre>// Asynchronous: mengambil data dari dua API secara bersamaan<br>const getData = async () =&gt; {<br>  const response1 = await fetch(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;);<br>  const data1 = await response1.json();<br>  <br>  const response2 = await fetch(&#39;https://jsonplaceholder.typicode.com/todos/2&#39;);<br>  const data2 = await response2.json();<br>  <br>  return [data1, data2];<br>}<br><br>// Synchronous: menampilkan data secara terurut<br>const showData = async () =&gt; {<br>  const data = await getData();<br>  <br>  // mengurutkan data berdasarkan id<br>  const sortedData = data.sort((a, b) =&gt; a.id - b.id);<br>  <br>  // menampilkan data<br>  sortedData.forEach(item =&gt; console.log(`ID: ${item.id}, Title: ${item.title}`));<br>}<br><br>// menjalankan fungsi untuk menampilkan data<br>showData();</pre><p>In conclusion, a good understanding of Asynchronous and Synchronous is important for a developer. We need to understand the needs and situations of the project we are working on before deciding to use Asynchronous or Synchronous concepts. In some cases, we may need to use both concepts together to achieve optimal performance.</p><p>In developing an application, choosing between asynchronous and synchronous programming is crucial to achieve the desired application goals. Although both methods have their own advantages and disadvantages, a developer must be able to choose the right method to maximize efficiency, speed, and application performance. Keep learning and developing your programming skills to create better and more effective applications. 🙌 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jipzCYTOS4HSpSAY_ceLKQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55ae032aa3ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous dan Synchronous pada Javascript]]></title>
            <link>https://medium.com/@aryandi/asynchronous-dan-synchronous-pada-javascript-3bbd62136e3f?source=rss-e7edc030bb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bbd62136e3f</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Muhammad Aryandi]]></dc:creator>
            <pubDate>Sat, 01 Apr 2023 15:54:47 GMT</pubDate>
            <atom:updated>2023-04-01T21:13:36.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ketika Javascript menjadi tidak Sabar: Memahami Asynchronous dan Synchronous pada Javascript</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6zXwgaA0Madbw7E8yk7uw.jpeg" /><figcaption><em>source: </em><a href="https://unsplash.com/photos/tvHtIGbbjMo"><em>https://unsplash.com/photos/tvHtIGbbjMo</em></a></figcaption></figure><p>Hi, sebelum membaca artikel ini, anda dapat melihat artikel dalam bahasa inggris, <a href="https://medium.com/@aryandi/understanding-asynchronous-and-synchronous-in-javascript-55ae032aa3ef">Lihat Disini</a></p><p><em>Asynchronous</em> dan <em>synchronous</em> adalah dua istilah yang sering digunakan dalam pemrograman, termasuk dalam JavaScript. <em>Synchronous</em> mengacu pada proses di mana setiap tugas dieksekusi secara berurutan, satu per satu. Dengan kata lain, program harus menyelesaikan tugas pertama sebelum melanjutkan ke tugas berikutnya. Ini juga dikenal sebagai blocking, karena setiap tugas memblokir eksekusi tugas berikutnya sampai tugas tersebut selesai.</p><p>Di sisi lain, asynchronous mengacu pada proses di mana beberapa tugas dieksekusi secara bersamaan atau sekaligus. Berbeda dengan pemrograman synchronous, program tidak harus menunggu setiap tugas selesai sebelum melanjutkan ke tugas berikutnya. Sebaliknya, tugas dieksekusi secara independen satu sama lain, memungkinkan efisiensi dan kecepatan yang lebih besar dalam mengeksekusi beberapa tugas sekaligus.</p><p>Memahami perbedaan antara asynchronous dan synchronous penting karena dapat mempengaruhi performa dan fungsionalitas program. Dalam JavaScript, misalnya, proses asynchronous dapat membantu mencegah program mengalami freeze atau crash saat menunggu tugas tertentu selesai. Dengan memungkinkan beberapa tugas dijalankan secara bersamaan, program dapat terus mengeksekusi fungsi lain, menghasilkan aplikasi yang lebih responsif dan efisien.</p><p>Secara keseluruhan, asynchronous dan synchronous adalah dua konsep penting dalam pemrograman, dan menguasai konsep-konsep ini dapat membantu para pengembang membangun aplikasi yang lebih cepat, lebih efisien, dan lebih andal.</p><h3>Synchronous</h3><p><em>Synchronous</em> adalah sebuah metode eksekusi kode yang dilakukan secara sekuensial, atau satu per satu. Artinya, program harus menyelesaikan tugas satu per satu secara berurutan. <em>Synchronous</em> bisa menyebabkan program terjebak dalam waktu yang lama dalam menyelesaikan satu tugas, sebelum akhirnya melanjutkan ke tugas berikutnya. Hal ini seringkali mengakibatkan kinerja program menjadi lambat dan kurang responsif.</p><p>Contoh sederhana dari <em>synchronous</em> adalah ketika kita membuat fungsi yang mengambil waktu yang lama untuk dieksekusi, seperti melakukan request data ke server. Dalam contoh ini, program akan menunggu sampai request data selesai dijalankan sebelum melanjutkan eksekusi kode yang lain. Jika ada beberapa request data yang harus dilakukan, maka program akan terhenti pada request pertama hingga selesai, baru kemudian dilanjutkan pada request yang berikutnya.</p><p><em>Synchronous</em> biasanya digunakan ketika urutan eksekusi kode yang jelas dibutuhkan atau ketika menunggu tugas tertentu selesai adalah bagian penting dari program.</p><p>Berikut adalah contoh sederhana penggunaan synchronous pada JavaScript. Dalam contoh ini, kita akan membuat dua fungsi yang mengambil waktu yang lama untuk dieksekusi, kemudian menjalankan keduanya secara berurutan:</p><pre>function fungsiA() {<br>  console.log(&#39;Memulai fungsi A&#39;);<br>  for (let i = 0; i &lt; 5; i++) {<br>    console.log(i);<br>  }<br>  console.log(&#39;Selesai fungsi A&#39;);<br>}</pre><pre>function fungsiB() {<br>  console.log(&#39;Memulai fungsi B&#39;);<br>  for (let i = 0; i &lt; 5; i++) {<br>    console.log(i);<br>  }<br>  console.log(&#39;Selesai fungsi B&#39;);<br>}</pre><pre>fungsiA();<br>fungsiB();</pre><p>Output yang dihasilkan adalah:</p><pre>Memulai fungsi A<br>0<br>1<br>2<br>3<br>4<br>Selesai fungsi A<br>Memulai fungsi B<br>0<br>1<br>2<br>3<br>4<br>Selesai fungsi B</pre><p>Karena fungsi A dan fungsi B dijalankan secara berurutan, maka fungsi B tidak akan dieksekusi sampai fungsi A selesai dieksekusi.</p><h3><strong>Asynchronous</strong></h3><p>Sebelum kita membahas penjelasan lengkap tentang asynchronous, mari kita terlebih dahulu memahami konsep yang telah dibahas sebelumnya tentang synchronous. Seperti yang telah dijelaskan sebelumnya, pada synchronous, proses eksekusi kode dilakukan secara bertahap dan satu per satu, sehingga satu perintah harus menunggu perintah sebelumnya selesai dijalankan.</p><p>Namun, pada asynchronous, eksekusi kode dilakukan secara bersamaan dan tidak harus menunggu perintah sebelumnya selesai dijalankan. Ini berarti, beberapa perintah dapat dijalankan secara bersamaan, tanpa harus menunggu satu sama lain.</p><p>Untuk memahami asynchronous, mari kita lihat contoh sederhana di bawah ini:</p><pre>console.log(&#39;Program dimulai&#39;);<br>setTimeout(function() {<br>  console.log(&#39;Fungsi 1 selesai dieksekusi&#39;);<br>}, 2000);<br>console.log(&#39;Ini adalah fungsi 2&#39;);</pre><p>Pada contoh di atas, kita menggunakan fungsi setTimeout() untuk memberikan jeda selama 2 detik sebelum mengeksekusi perintah berikutnya. Dalam kasus ini, kita memberikan jeda selama 2 detik sebelum mengeksekusi perintah di dalam fungsi yang diberikan.</p><p>Dalam asynchronous, kita menggunakan callback untuk mengeksekusi fungsi setelah fungsi lain selesai dieksekusi. Dalam contoh di atas, kita memberikan callback function ke dalam fungsi setTimeout() untuk mengeksekusi perintah setelah fungsi lainnya selesai dieksekusi.</p><p>Dengan menggunakan asynchronous, program kita menjadi lebih efisien dan responsif. Kita dapat melakukan beberapa tugas secara bersamaan tanpa harus menunggu satu tugas selesai terlebih dahulu.</p><h4><strong>Asynchronous dan Synchronous, kapan mereka digunakan ?</strong></h4><p>Setelah kita memahami konsep dasar dari <em>Asynchronous</em> dan <em>Synchronous</em>, sekarang saatnya kita membahas kapan kita harus menggunakan masing-masing konsep ini. Kita harus memahami bahwa setiap situasi memiliki kebutuhan yang berbeda-beda. Oleh karena itu, sebagai seorang developer, kita harus memahami situasi dan kebutuhan dari setiap project yang sedang kita kerjakan sebelum memutuskan menggunakan konsep Asynchronous atau Synchronous.</p><p>Pada umumnya, <em>Synchronous</em> cocok digunakan ketika kita membutuhkan hasil yang akurat dan urutan yang tepat dalam eksekusi kode. Misalnya, ketika kita ingin melakukan perhitungan matematika yang rumit, kita harus menunggu hingga perhitungan selesai sebelum melanjutkan ke tahap berikutnya. Contoh penggunaan Synchronous pada kode dapat dilihat pada contoh fungsi penjumlahan sederhana di bawah ini:</p><pre>function addNumbers(a, b) {<br>  return a + b;<br>}<br>let result = addNumbers(2, 3);<br>console.log(result); // Output: 5</pre><p>Sedangkan <em>Asynchronous</em> lebih cocok digunakan ketika kita ingin melakukan beberapa tugas secara bersamaan tanpa harus menunggu satu tugas selesai terlebih dahulu sebelum menjalankan tugas berikutnya. Misalnya, ketika kita ingin mengambil data dari <em>database</em> dan menampilkan data tersebut pada halaman website. Kita bisa menggunakan <em>Asynchronous</em> untuk memungkinkan website terus berjalan tanpa harus menunggu data selesai diambil. Contoh penggunaan <em>Asynchronous</em> pada kode dapat dilihat pada contoh fungsi <em>setTimeout()</em> di bawah ini:</p><pre>console.log(&quot;Start&quot;);<br><br>// menjalankan setTimeout dalam callback function<br>setTimeout(() =&gt; {<br>  console.log(&quot;Finish&quot;);<br>}, 3000);<br><br>console.log(&quot;Next Task&quot;);</pre><p>Dalam contoh kode di atas, setelah mengeksekusi fungsi <em>console.log(“Start”)</em>, program akan menunggu selama 3 detik sebelum mengeksekusi fungsi <em>console.log(“Finish”)</em> dan <em>console.log(“Next Task”)</em>. Proses eksekusi kode tidak terblokir dan program didalam <em>setTimeout</em> tereksekusi selama 3 detik.</p><p>Mungkin Anda bingung kenapa menggunakan <em>setTimeout()</em> sebagai contoh. <em>setTimeout()</em> digunakan sebagai simulasi waktu tunggu selama 3 detik. Dengan <em>setTimeout()</em>, program akan menjalankan <em>callback function</em> setelah jeda waktu yang ditentukan tanpa harus menunggu proses selesai terlebih dahulu, sehingga proses eksekusi kode pada program tidak terblokir dan tetap berjalan.</p><p>Kita juga dapat menggunakan kedua konsep ini bersama-sama untuk meningkatkan performa program, seperti ketika kita ingin mengambil data dari beberapa <em>API</em> secara bersamaan dan menampilkan data tersebut secara terurut. Kita dapat menggunakan <em>Asynchronous</em> untuk mengambil data dari beberapa API secara bersamaan, lalu menggunakan <em>Synchronous</em> untuk mengurutkan dan menampilkan data tersebut pada halaman website. Berikut contoh supaya lebih paham 😄</p><pre>// Asynchronous: mengambil data dari dua API secara bersamaan<br>const getData = async () =&gt; {<br>  const response1 = await fetch(&#39;https://jsonplaceholder.typicode.com/todos/1&#39;);<br>  const data1 = await response1.json();<br>  <br>  const response2 = await fetch(&#39;https://jsonplaceholder.typicode.com/todos/2&#39;);<br>  const data2 = await response2.json();<br>  <br>  return [data1, data2];<br>}<br><br>// Synchronous: menampilkan data secara terurut<br>const showData = async () =&gt; {<br>  const data = await getData();<br>  <br>  // mengurutkan data berdasarkan id<br>  const sortedData = data.sort((a, b) =&gt; a.id - b.id);<br>  <br>  // menampilkan data<br>  sortedData.forEach(item =&gt; console.log(`ID: ${item.id}, Title: ${item.title}`));<br>}<br><br>// menjalankan fungsi untuk menampilkan data<br>showData();</pre><p>Dalam kesimpulannya, pemahaman yang baik tentang <em>Asynchronous</em> dan <em>Synchronous</em> adalah penting bagi seorang developer. Kita harus memahami kebutuhan dan situasi dari project yang sedang kita kerjakan sebelum memutuskan untuk menggunakan konsep <em>Asynchronous</em> atau <em>Synchronous</em>. Dalam beberapa kasus, kita mungkin perlu menggunakan kedua konsep ini bersama-sama untuk mencapai performa yang optimal.</p><p>Dalam mengembangkan aplikasi, pemilihan antara <em>asynchronous</em> dan <em>synchronous programming</em> sangat penting untuk mencapai tujuan aplikasi yang diinginkan. Meskipun kedua metode memiliki kelebihan dan kekurangan masing-masing, seorang developer harus dapat memilih metode yang tepat untuk memaksimalkan efisiensi, kecepatan, dan kinerja aplikasi. Teruslah belajar dan mengembangkan keterampilan programming Anda untuk menciptakan aplikasi yang semakin baik dan efektif. 🙌 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jipzCYTOS4HSpSAY_ceLKQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bbd62136e3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>