<?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 Ori Baram on Medium]]></title>
        <description><![CDATA[Stories by Ori Baram on Medium]]></description>
        <link>https://medium.com/@obrm770?source=rss-25ddb3a99175------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FZrrbBox5d1isGJ7BbLyaQ.jpeg</url>
            <title>Stories by Ori Baram on Medium</title>
            <link>https://medium.com/@obrm770?source=rss-25ddb3a99175------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 17:31:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@obrm770/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[Best Practices and Design Patterns in React.js for High-Quality Applications]]></title>
            <link>https://medium.com/@obrm770/best-practices-and-design-patterns-in-react-js-for-high-quality-applications-6b203be747fb?source=rss-25ddb3a99175------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b203be747fb</guid>
            <category><![CDATA[code-organization]]></category>
            <category><![CDATA[code-scalability]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Ori Baram]]></dc:creator>
            <pubDate>Thu, 30 Mar 2023 09:41:54 GMT</pubDate>
            <atom:updated>2023-04-23T13:04:40.964Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Hey there, if you love using React.js like we do, you know it’s an awesome library for creating user interfaces. It’s simple, flexible, and super speedy. But as your app gets bigger, managing components, state, and logic becomes more of a challenge. To keep things running smoothly and make your code easy to understand, it’s important to follow best practices and design patterns.</strong></h3><h4>In this guide, we’ll show you some of the most useful practices and patterns for working with React.js. We’ll cover things like how to structure your folders, separate concerns, and design components. These tips will make your life as a developer a whole lot easier. They will help you build applications that are easy to maintain, scale, and perform well. We’ll show you lots of real-life code examples to make things super clear and give you practical advice on how to put these best practices to work in your own projects. Plus there is a bonus at the end — a <strong>GitHub </strong>repo with all the code mentioned in this article!</h4><h4>So, let’s get started and make our React apps even better!</h4><h3>1. Best Practices for Building Scalable React Applications</h3><p>If you are building a React application and want to make sure it stays organized and scalable, then you need to follow some best practices! In this section, we’ll cover four essential best practices that will help you build maintainable, scalable, and efficient React applications. These practices include organizing your project files in a feature-based folder structure, keeping your components focused and small, using appropriate naming conventions, and separating the responsibilities of Pages and presentational components. By following these practices, you can create applications that are easier to navigate, understand, and maintain.</p><h3>1.1. Folder Structure</h3><p>Having an organized folder structure is super important if you want to keep your project hierarchy clear and make it easy to navigate. Check out this example of a feature-based folder structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/0*WSXa03WtOiCJw7Ng" /></figure><p>Instead of organizing components by file types, we group them by features. This makes it a lot simpler to find and manage related files, like a component’s JavaScript and CSS files.</p><h3>1.2. Keep Components Small and Focused</h3><p>When you’re building an application, it’s super important to create components that are easy to understand, maintain, and test. That’s why it’s a good idea to keep your components focused and small. If a component is starting to get too big, don’t sweat it — just break it down into smaller, more manageable components!</p><p>For instance, let’s say you have a UserProfile component that’s starting to feel overwhelming. You could break it down into smaller components like ProfilePicture, UserName, and UserBio. This will make each component simpler to handle and reuse.</p><p>Check out this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*_2Ap-5qb1Ej7eGH-" /></figure><h3>1.3. Naming Conventions</h3><p>When you give your components, props, and state variables names that make sense, it helps other people (and future you!) understand your code more easily. Plus, it makes your code easier to maintain in the long run. Here are some tips to help you name things like a pro:</p><ul><li>For components, use PascalCase (like UserProfile.js)</li><li>For variables and functions, use camelCase (like getUserData())</li><li>And for constants, use UPPERCASE_SNAKE_CASE (like API_URL)</li></ul><p>Note that this is very subjective and it up to you to decide by which naming convention you want to follow. The most important thing is to be consistent with your naming style.</p><h3>1.4. Pages (container components) and Presentational Components</h3><p>In React, there are two types of components: Pages (container components) and presentational components. Pages handle tasks like fetching data from external sources (like APIs), managing state and logic, and passing data down to the presentational components using props. Meanwhile, presentational components are responsible for rendering UI elements and displaying data passed down from their parent components. By separating these responsibilities, we can create more modular and reusable components.</p><p><strong>Example — TodoApp Page:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/0*G5uk9bW7t8yRESPf" /></figure><p><strong>TodoList Component:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*mz_egBeoZyavJ7Ue" /></figure><p>Okay, so when it comes to React components, we can divide them into two types: Pages (or container components) and presentational components. Pages handle stuff like getting data from APIs and managing state and logic, while presentational components show the data that they get from their props and define how things look. By doing this, we can keep our code more organized, easier to understand, and simpler to test.</p><h3>1.5. Keep it DRY with Array Mapping</h3><p>Using an array of items and mapping over them can be a nifty trick to avoid code repetition in your React components. Imagine you’re building a navigation bar with multiple links, each with its own title, path, and icon. Rather than writing out the same structure and code for each link, you can create an array of objects that hold all the necessary data and dynamically render them with a map function.</p><p>Check out this sample code that demonstrates how you can easily create an array of links and map over them to render a navigation bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/0*ksUdDrnf4GR0NNr0" /></figure><p>In the example above, we demonstrated how creating an array of items and mapping over them can help you avoid code repetition in your React components. This technique is not only useful for rendering navigation bars, but also for rendering forms with multiple input fields.</p><p>By creating an array of objects that contain the necessary data for each input field, you can map over them to render the input fields dynamically. This can greatly simplify your code and make it more maintainable, especially when dealing with forms that have many input fields.</p><p>Here’s an example of this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*YcxR8R00csSfajRO" /></figure><p>This cool example shows how to use an array of input objects to create dynamic input fields in React. Each input object includes the label, type, and name for each input field. By using the map() function, you can easily loop over the array and render each input field dynamically with the data from each input object.</p><p>Using arrays and mapping over them is a great way to create dynamic content in your React components without repeating the same code over and over. This technique makes your components more scalable, reusable and easier to maintain.</p><h3>2. Separation of Concerns</h3><p>Separation of concerns is super important in software development. It’s all about making sure each part of your app has one job to do. When it comes to React.js, separating the logic from the view can help make your code more maintainable, reusable, and scalable. So let’s take a closer look at some examples and techniques to help us achieve this separation and make our React apps even better.</p><h3>2.1. Custom Hooks</h3><p>Custom hooks let you take stateful logic out of your components and use it across multiple components. Custom hooks are just JavaScript functions with a special naming convention — they have to start with “use” (like, useForm). These hooks can use other built-in or custom hooks, and they can export an object or an array with all the properties and methods you want to use in your components. Want to see some real-life examples of how custom hooks can make your React.js code even better? Let’s dive in!</p><h3>Example: Custom Hook for Form Input Handling</h3><p>Imagine you’ve got a form with loads of input fields. Handling the state and input for each field can get pretty tricky and repetitive. But fear not — we can make things easier with a custom hook called useForm. This hook lets you extract the state and logic for all those fields and keep things neat and tidy.</p><p>First up, we use useState to create a values object that holds all our form input values. Then, we make a handleChange method that updates the values object whenever an input changes. Finally, we add a resetForm method that sets everything back to square one.</p><p>By popping values, handleChange, and resetForm in an array, we can use these properties and methods in all our components and make our form component way easier to maintain and reuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*e9Ua4LUUXRcEXsvb" /></figure><p>Now, we can use the useForm custom hook in our form component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*pep0bmtYwiWHQWnL" /></figure><p>The useForm custom hook is the way to go if you want to handle form inputs in any React.js app with ease. Whether it’s a login form or a registration form, you name it.</p><h3>Another example: Custom Hook for Fetching Data</h3><p>Another thing we can do with custom hooks is fetch data from an API. It’s pretty common actually. All we need is to make a custom hook called useFetch that takes care of the state and side effects related to fetching data. Easy-peasy!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/0*XFrSbOWzGYR0tB5w" /></figure><p>Now, we can use the useFetch custom hook in any component that requires data from an API:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/0*QBD59VltVvPDqyXy" /></figure><p>Thanks to the useFetch custom hook, we can easily handle the state and logic for fetching data from the view in our UserList component. This makes our code way easier to maintain and reuse. With useFetch, we can keep all the state and side effects related to fetching data in one tidy spot, then use the resulting data in multiple components. This separation of concerns means we can easily change our data fetching logic without messing with the components that depend on it. All in all, it makes our code more maintainable and scalable.</p><h3>2.2. Services</h3><p>If you want to make your React apps more modular, using services is a great way to go. Basically, services are functions or classes that handle business logic like calling APIs, playing around with data, or other helpful tasks. You can import these services and use them in your components or custom hooks. It’s an easy way to separate logic from the view and keep things organized.</p><h3>Example: API Service</h3><p>Let’s say we need to work with a RESTful API to do some CRUD operations on user data. To make things simpler, we can create a service that takes care of all of that. It’s a handy way to communicate with the API and get our tasks done efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*4ghotTge_-3fM-sH" /></figure><p>Now, we can use the API service in our components or custom hooks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/0*nPh4D8qTlUsB3aZd" /></figure><p>Thanks to the API service, we can keep all the API interaction logic separate from the view in our UserList component. That way, we can easily maintain and reuse our code without any fuss. It’s a great way to make sure everything stays organized and easy to manage.</p><h3>Example: Utility Service</h3><p>Let’s say we need to do some useful stuff like format dates, calculate sums, or make unique IDs. We can create a handy utility service that’ll take care of all that. It’s like our own little helper that we can call on whenever we need to get some useful work done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*IKsTFWMcnqxY6pKM" /></figure><p>Cool! We can easily use our utility service in our components or custom hooks to make our code more efficient and reusable. It’s a great way to keep things organized and make sure everything runs smoothly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qCj0Bo0StEGx3Xcg" /></figure><p>By using the utility service, we’ve kept the utility logic separate from the view, making our TransactionList component easier to manage and reuse.</p><h4><strong>When to use a Custom Hook and when to use a Service Function</strong></h4><p>When deciding whether to use a custom hook or a service function, it’s important to consider the specific use case and requirements of your application. <strong>Custom hooks</strong> are more appropriate when you need to <strong>manage state or context</strong>, or when you want to <strong>reuse functionality across multiple components</strong>. On the other hand, service functions are better suited for reusable <strong>logic that does not depend on state or context</strong>.</p><p>In practice, you may find that some functionality fits better as a custom hook, while other functionality works better as a service function. For example, here are some more examples of when you might choose to use each approach:</p><h4><strong>Custom Hooks:</strong></h4><ul><li><strong>Managing complex state:</strong> If you need to manage complex state across multiple components, a custom hook can be a great way to encapsulate that logic and make it reusable. For example, if you need to manage a user’s preferences and match them with your product, a custom hook like useUserSettings could help track the state of the user&#39;s preferences and provide functionality for checking the match with your product. The custom hook utilizes useState to track the state of the user&#39;s preferences and the match with your product, and provides a function to check the match based on the user&#39;s preferences and your product&#39;s categories.</li><li><strong>Context-dependent functionality:</strong> A custom hook can help access the context from your application and provide reusable functionality. For example, if you need to perform user authentication and manage the user’s state across multiple components, a custom hook like useLoggedUser could help you access the user&#39;s state and provide functionality for updating the state. The custom hook can utilize the LoggedUserContext to access the user&#39;s state and provides functions for setting a new user, setting an existing user, updating the user&#39;s state, etc.</li></ul><h4>Service Functions:</h4><ul><li><strong>Task-specific functionality:</strong> If you need to perform a specific task that doesn’t depend on context or state, a service function can be a more appropriate approach. For example, if you need to validate data like an email address or a password, or formatting data such as currency values or dates, or sorting data such as a list of products or search results, service functions could provide these functionalities without requiring state or context.</li><li><strong>Standalone functionality:</strong> If you need to provide functionality that can be used across multiple applications or platforms, a service function can be a good way to encapsulate that logic and make it reusable. For example, if you need to provide a function for image processing, or file storage, or email sending, or payment processing, service functions could provide these functionalities in a way that can be used across multiple applications or platforms.</li></ul><h3>3. Component Design Patterns</h3><p>When you’re building React apps, it’s important to make components that are easy to work with, reusable, and don’t give you a headache when you’re trying to update them. That’s where <strong>design patterns</strong> come in. In this section, we’re going to check out some design patterns that can help you make flexible and reusable components. These patterns will help you divide big components into smaller, more manageable pieces, making them easier to understand, test, and maintain.</p><h3>3.1. Higher-Order Components (HOCs)</h3><p><strong>Higher-Order Components (HOCs)</strong> are pretty neat! They’re functions that take a component and return a new component with more features or behaviors. Basically, they let you reuse component logic and handle things like authentication or data fetching.</p><p>For example, you can use an HOC to check if a user is authenticated and then wrap a component that needs authentication with it. If the user is authenticated, the wrapped component will show up. But if not, they’ll be sent to the login page. Here’s an example to give you an idea of what it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*XGwM3oVwxWIJmE7l" /></figure><p>Alright, so in this example we got this function called requireAuth, which gets a component as input and returns a new one that checks if the user is logged in. If not, it takes the user to the login page. Otherwise, the wrapped component is rendered with the extra props from the HOC.</p><p>Now, we can also use HOCs to wrap a component that needs some data fetching. Basically, the HOC will fetch the data and pass it down to the component as props.</p><p>Check it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/0*Afa_ADY3F8QIRl0I" /></figure><p>So in this example, the withDataFetching function takes a component and gets data from a URL to pass it down as props. If there’s an error, it goes into the error prop, and if the data’s still loading, the isLoading prop is set to true.</p><p>There are plenty of other rad <strong>HOCs </strong>you can use with React too! One of them is <strong>memo</strong>. Instead of causing unnecessary re-renders even if a component’s props remain the same, thereby slowing down your React app, <strong>memo </strong>allows you to optimize your component so that it only re-renders if the props it receives have changed, making your app more efficient and improving performance. This can be a real game-changer for optimizing performance in your React app.</p><p>But there are also some other <strong>HOCs </strong>that are commonly used in popular React libraries. For example, there’s <strong>connect </strong>from the react-redux library, which connects a component to the <strong>Redux store</strong>, so it can access the store’s state and dispatch functions. This means you can easily create components that react to changes in the Redux store. Another one is <strong>withFirebase </strong>from the<strong> react-redux-firebase</strong> library, which provides a <strong>Firebase </strong>instance to a component, so it can interact with the Firebase backend.</p><p>HOCs are pretty cool because they let you reuse component logic and deal with problems that affect the whole app. It’s like killing two birds with one stone! HOCs make it so your components are nice and tidy, they’re easy to take care of, they’re focused and easy to maintain.</p><h3>3.2. Render Props</h3><p><strong>Render props</strong> are a fancy term in React that lets you share code between components by passing a function as a prop to a child component, and it can be more flexible than HOCs in some cases.</p><p>This function, when called, returns a React element (usually JSX). The idea behind render props is to let the parent component take care of rendering some part of the component. So, the child component can focus on providing the necessary functionality, while the parent component determines how the rendered content should look like.</p><p>Let’s see an example of how render props work in real life:</p><p>Imagine you’re building an online store app, and you need to display a list of products in different parts of your app. You want to fetch the products and display them in different ways, such as a grid view or a list view. Here’s how you can achieve this using the render props pattern:</p><p>First, create a ProductFetcher component that fetches the product data and accepts a render prop (a function):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*Uojz7V5jGqdCEUvN" /></figure><p>In this example, the ProductFetcher component is responsible for fetching the products and managing the loading state. It accepts a render prop, which is a function, and calls it with the products as an argument.</p><p>Now, let’s create two separate components for displaying the products in grid and list views:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/0*RteHE1ZHUH4bJGX3" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/0*fx9tfoH1crOITH33" /></figure><p>Finally, use the ProductFetcher component and pass the appropriate render function to display the products in different formats:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*G_1kI7OBRBIkmwzh" /></figure><p>So, in this example, we have the ProductFetcher component that fetches and manages the product data. The ProductGrid and ProductList components are responsible for displaying the products in different formats. With the help of the render prop, the ProductFetcher component fetches the product data, and the parent component (in this case, App) determines how the products should be displayed.</p><p>By using the <strong>render props</strong> pattern, we get some sweet benefits, like:</p><ol><li><strong>Separation of concerns:</strong> The ProductFetcher component is only responsible for fetching and managing the loading state of products. It doesn’t have to worry about how the products are displayed.</li><li><strong>Reusability:</strong> The ProductFetcher component can be used throughout the app to fetch and display products in different formats without much hassle.</li><li><strong>Flexibility:</strong> The parent component can decide how the products should be displayed, giving us the freedom to customize the UI without tinkering with the fetching logic.</li></ol><h3>3.3. Compound Components</h3><p><strong>Compound components</strong> are a cool design trick that helps you create better and more flexible components. You can group together related components and control their behavior from a parent component, which can make your code much more organized and user-friendly.</p><p>One popular example of this is an accordion component, which usually has lots of panels that expand and collapse when you click them. With compound components, you can build a reusable accordion component that’s both easy to customize and easy to use.</p><p>Let’s check out an example of how to make an Accordion component using compound components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/0*AB1LUZ1X3jiAhkRD" /></figure><p>In this example, we got this Accordion component, where we render a list of children and loop through them with React.Children.map to decide when to display them. We use React.cloneElement to give AccordionHeader and AccordionContent some extra props to control how they behave.</p><p>Here’s how all of these component would look in a component called MyAccordion:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/0*09ArDPpEBH7bBXkT" /></figure><p>You must agree with me that this component is way more comprehensive, easy to reason about and clean.</p><p>And if that’s not enough for you, we also got a Tabs component that shows different content when you click on different tabs. Just like with the Accordion, we can use compound components to make it easier to build and use. Want to see an example of how it’s done?</p><p>Check it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/0*SKg2L9TPT7m6vY0n" /></figure><p>In this example we got a Tabs component that displays a list of tabs with different content. We use React.cloneElement to give the Tab and TabContent components some extra props for controlling their behavior.</p><p>And here’s how it will look combined all together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/0*9ZI0oSo-cCkIiFIq" /></figure><p><strong>Compound components</strong> are really cool and can make your components super flexible and expressive. Instead of just having a bunch of separate components, you can group them together in a parent component to make things way more intuitive and user-friendly. Stuff like Accordions, Tabs, and Dropdowns can get pretty complicated in a web app, but with compound components, you can simplify everything and make it easy-peasy for your users to navigate.</p><h3>3.4. Optimize Rendering with React.memo</h3><p><strong>React.memo</strong>, that we already mentioned, is like a secret weapon for optimizing functional components. It makes sure that the component only re-renders when the props change, which can be a huge performance boost, especially when you’re dealing with complex or expensive-to-compute props. Basically, it helps you avoid unnecessary renders and keeps your app running smoothly.</p><p>Check out this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/0*-MbCIsvxQe3psi8d" /></figure><p>In this example, the UserProfileName component will only re-render when its name prop changes, avoiding unnecessary updates and improving performance.</p><h3>3.5. Use React.lazy for Code Splitting and Lazy Loading</h3><p><strong>React.lazy </strong>is a really neat tool that can help speed up your app and make it more efficient. It’s a built-in feature that allows you to split up your components and load them only when you actually need them. This is great if you have a really big app with tons of different components that aren’t all needed right away. With React.lazy, you can pick and choose which components to load, and exactly when to load them. This means that your app can start up faster, use less memory, and generally be much more efficient. Plus, it’s super easy to use — all you need to do is wrap your component in a special function, and React will take care of the rest.</p><p>Let’s say you’re building an e-commerce app with React. You have a product listing page that displays all the products in your inventory. Each product has an image, name, price, and description.</p><p>You also have a product details page that displays more information about a single product, such as reviews, ratings, and related products.</p><p>If you load all the code for the product details page on the product listing page, it could slow down the initial load time and cause your app to feel sluggish. That’s where React.lazy comes in.</p><p>Here’s how you can use React.lazy to lazily load the ProductDetails page only when the user clicks on a product:</p><p>First, you create a separate file for the ProductDetails component:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/0*mciB4UFVxYIfe2tN" /></figure><p>Next, you wrap the ProductDetails component in a call to React.lazy:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/0*8XFVElXkcWk5Ujam" /></figure><p>This tells React to lazily load the ProductDetails component only when it’s needed.</p><p>Finally, you use the ProductDetails component in your product listing page, and wrap it in a Suspense component to handle the loading state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*v0QOItJu7Lb6C4MY" /></figure><p>When the user clicks on a product, the handleProductClick function sets the selectedProduct state to the clicked product. If selectedProduct is not null, the ProductDetails component is rendered inside a Suspense component.</p><p>The Suspense component displays a loading state until the ProductDetails component is loaded.</p><p>That’s it! With React.lazy, you can lazily load components when you need them, making your app faster and more efficient.</p><h3>3.6. Use Context and React.createContext for Global State Management</h3><p>The <strong>Context API</strong> is a great way to share state across multiple components without having to pass props down through the component tree. This can greatly simplify your state management and make your code more maintainable.</p><p>Take a look at this sample:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/0*aehr3eMFxHFIrQJi" /></figure><p>So, we have a ThemeContext and a ThemeProvider component that we wrap around the app. It’s great because all components can use the useTheme hook to access and update the theme without passing it around like a hot potato.</p><p>Here’s an example for this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/0*MEJyHPuhH_mBr-Pd" /></figure><h3>3.7. Reducers for Managing Complex State</h3><p><strong>Reducers </strong>are like a super handy tool that can help you manage complex state in a predictable and testable way. They’re a functional programming pattern that works great with useReducer hook or libraries like Redux. Basically, you pass them the current state and an action, and they return the new state.</p><h3>Example: Todo App</h3><p>So, here’s what you do first: make a function that’s gonna be the reducer and the actions you want:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/0*KVKJVlP4Yq1_ooi4" /></figure><p>Then, you can use the todoReducer with the useReducer hook. It’s as simple as that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/0*LdmyzzxwyZNc_zC5" /></figure><h3>3.8. Use Keys When Rendering Lists</h3><p>When you’re rendering a list of stuff in React, make sure to give each item a unique key. This helps React work its magic and make things faster and smoother. Here’s how you do it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/0*zNlD_zmcdUsfM72D" /></figure><p>In this example, we give each item in the todos array a unique key, which helps React render things faster and avoid messing up the DOM, optimizing rendering and avoid unnecessary DOM updates.</p><p>By sticking to these best practices, you’ll be able to create React apps that are way easier to manage, scale, and keep running smoothly. By breaking things down into smaller, more focused components, optimizing rendering, and only loading the things you actually need, and handling state efficiently, you’ll be well on your way to creating a top-notch React app. So make sure to keep these tips in mind as you tackle your own React projects to ensure they’ll last for the long haul.</p><h3>Conclusion</h3><p>To wrap it up, all the cool design patterns and best practices we’ve talked about are super important for making awesome <strong>React.js</strong> apps. If you want to write clean, easy-to-read code that’s simple to maintain and scale up, then you gotta <strong>organize your folders right</strong>, split up your components into <strong>custom hooks</strong>, <strong>services</strong>, and <strong>presentational parts</strong>, use the <strong>appropriate names</strong> for things, and work with <strong>HOCs</strong>, <strong>render props, compound components, </strong>and <strong>reducers</strong>. And don’t forget the basics like keeping your<strong> components small</strong>, optimizing your rendering with <strong>React.memo</strong>, code splitting with <strong>React.lazy</strong>, using the <strong>Context API</strong>, and using <strong>keys </strong>when you’re doing list rendering. Following all these tips and tricks is the way to a robust and efficient application that both you, fellow developers and your users will love!</p><p><strong>All the code mentioned in this article can be found in </strong><a href="https://github.com/obrm/react-best-practices-design-pattens"><strong>this repository</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b203be747fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a Full-Stack React & Node.js Project: A Comprehensive Cheat Sheet]]></title>
            <link>https://medium.com/@obrm770/setting-up-a-full-stack-react-node-js-project-a-comprehensive-cheat-sheet-ee326576c21a?source=rss-25ddb3a99175------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee326576c21a</guid>
            <category><![CDATA[full-stack]]></category>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[project-setup]]></category>
            <dc:creator><![CDATA[Ori Baram]]></dc:creator>
            <pubDate>Sun, 19 Mar 2023 13:48:49 GMT</pubDate>
            <atom:updated>2023-03-23T13:37:01.780Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>Setting up a Full Stack React &amp; Node.js Project: A Comprehensive Cheat Sheet</h3><p>Embarking on a new full stack React &amp; Node.js project can be both exciting and daunting. To ensure a smooth and efficient setup process, I have compiled a step-by-step cheat sheet that will guide you from creating your project folder to fine-tuning your frontend and back-end configurations.</p><p>In this article, you will learn how to create a project folder, set up your server for development with the help of essential dependencies such as concurrently, and initialize a Git repository. We will also cover setting up your frontend using Create React App or Vite, configuring a proxy for seamless communication between your frontend and back-end, and organizing your files using best practices. Furthermore, it is important to note that the <strong><em>appendices</em> </strong>at the end of this article contain useful and crucial information. Please be sure to review them carefully.</p><p>By following the instructions in this cheat sheet, you will be able to dive into your full stack project with confidence, laying a strong foundation for your application development journey. So, let us get started and happy coding!</p><h3>Setting Up the Server</h3><ol><li>Create a folder for your project using lowercase letters and hyphen-separated words.</li></ol><blockquote><strong><em>Naming conventions </em></strong><em>can vary depending on personal preference and team standards. However, there are some general best practices that you can follow to ensure your project’s folder names are clear and consistent. Here<br>are a few suggestions:</em></blockquote><blockquote><strong><em>1. Use lowercase letters</em></strong><em> — it’s a common practice to use</em><strong><em> only lowercase letters</em></strong><em> when naming folders in web development. This is because </em><strong><em>Unix-based</em></strong><em> systems are </em><strong><em>case-sensitive</em></strong><em>, so using lowercase letters ensures that your files and directories will be accessible across different platforms. See also the </em><strong><em>appendix </em></strong><em>at the end of this document.</em></blockquote><blockquote><strong><em>2. Use hyphens or underscores</em></strong><em> — when you need to separate words in your folder name, it’s a good idea to use either hyphens (-) or underscores (_). Both are commonly used, but </em><strong><em>hyphens are generally preferred</em></strong><em> since they are more readable and easier to type.</em></blockquote><blockquote><strong><em>3. Use descriptive names</em></strong><em> — your folder name should be descriptive and concise, so anyone who reads it can quickly understand what it contains. Avoid using abbreviations or acronyms that may not be clear to everyone.</em></blockquote><blockquote><em>Based on these best practices, a good naming convention for a project folder could be something like ‘my-project’ or ‘my_app’. Again, the important thing is to choose a convention that is clear and consistent for you and your team.</em></blockquote><p>2. Open the folder in VS Code.</p><p>3. Create a .gitignore file with the following content:</p><pre># Dependencies<br>node_modules<br><br># Build/Production<br>/client/build<br><br># Environment variables<br>*.env*<br>!.env.example<br><br># Logs<br>/logs<br>*.log<br><br># Editor specific<br>.vscode<br>.idea<br>*.suo<br>*.ntvs*<br>*.njsproj<br>*.sln<br><br># Temporary files<br>*.sw?<br>*.cache<br>.DS_Store<br><br># Generated / Auto-generated files<br>/dist<br>/dist-ssr<br>.eslintcache<br><br># Configuration<br>.prettierrc</pre><p>4. In the terminal, run npm init. Set the description, entry point to server.js, author to your name, and license to MIT.</p><blockquote>Both licenses, ISC &amp; MIT, allow users to use, copy, modify, and distribute the software, including for commercial purposes, without any requirement to share their changes.<br>The <strong>MIT </strong>license includes a <strong>disclaimer of liability</strong>, while the ISC license does not.</blockquote><p>5. Install concurrently as a development dependency, by running npm i -D concurrently.</p><p>6. Install express and dotenv by running npm i express dotenv.</p><p>7. Create a config folder and a config.env file inside it.</p><p>8. Add the following content to config.env:</p><pre>NODE_ENV=development<br>PORT=5000</pre><p>9. To use ES modules instead of CommonJS, add &quot;type&quot;: &quot;module&quot;, to your package.json file after &quot;main&quot;: &quot;server.js&quot;,.</p><p>10. Create a server.js file with the following content (for ES modules):</p><pre>import express from &#39;express&#39;;<br>import dotenv from &#39;dotenv&#39;;<br><br>dotenv.config({ path: &#39;./config/config.env&#39; });<br><br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;Server running&#39;));<br><br>const PORT = process.env.PORT || 5000;<br><br>app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));</pre><p>If you are using Common JS Modules, use this:</p><pre>const express = require(&#39;express&#39;);<br>const dotenv = require(&#39;dotenv&#39;);<br><br>dotenv.config({ path: &#39;./config/config.env&#39; });<br><br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;Server running&#39;));<br><br>const PORT = process.env.PORT || 5001;<br><br>app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));</pre><p>11. Update the scripts section in package.json (remove the test script):</p><p><em>If you are intending to use CRA (create-react-app), use this:</em></p><pre>&quot;start&quot;: &quot;node server.js&quot;,<br>&quot;server&quot;: &quot;node --watch server.js&quot;,<br>&quot;client&quot;: &quot;npm start --prefix client&quot;,<br>&quot;dev&quot;: &quot;concurrently \&quot;npm run server\&quot; \&quot;npm run client\&quot;&quot;</pre><p><em>If you are intending to use Vite, use this:</em></p><pre>&quot;start&quot;: &quot;node server.js&quot;,<br>&quot;server&quot;: &quot;node --watch server.js&quot;,<br>&quot;client&quot;: &quot;npm run dev --prefix client&quot;,<br>&quot;dev&quot;: &quot;concurrently \&quot;npm run server\&quot; \&quot;npm run client\&quot;&quot;</pre><p>12. In the terminal, run npm run server and verify that you don&#39;t have any errors.</p><p>14. Open <a href="http://localhost:5000/">http://localhost:5000</a> in your browser to check if the server is running correctly and verify you see there “Server running”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*07crjsFn7lJsbFserr98jg.png" /><figcaption>Verifying the server is running in the browser</figcaption></figure><h3>Setting Up the Frontend</h3><ol><li>Run npx create-react-app client or run yarn create vite and name your project “client”, to create a new Vite-based React app in the &quot;client&quot; folder.</li></ol><p><em>If you didn’t install yarn on your machine before, in the terminal, run this command:</em></p><p><em>For macOS or Linux, you can use the following command:</em></p><pre>npm install -g yarn</pre><p><em>For Windows, you can use the following command:</em></p><pre>npm install --global yarn</pre><p>3. If you created a Vite-based React app, change to the client folder by using cd client in the terminal, and run yarn in order to install the node modules.</p><p>4. To install additional packages for your React app, don’t forget to first change to the client directory using cd client.</p><p>5. Delete the .gitignore and README.md files in the client folder.</p><p>6. Remove the git repository from the client folder. Change to the client folder using cd client and run -rf .git on <strong>macOS </strong>or <strong>Linux</strong>.<br>On <strong>Windows</strong>, Open File Explorer and go to the client folder. Click the “View” tab on the top menu. Check the “Hidden items” checkbox in the “Show” section.<br>Once you’ve enabled the visibility of hidden items, delete the .git folder in the client folder.<br>Back in the terminal, return to the root directory with cd ...</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*Lsjv8CflUefR3uug_cF4qw.png" /><figcaption>Enabling the visibility of hidden items on Windows 11</figcaption></figure><p>7. Add a proxy to the package.json file in the client folder for easier API requests, so if you type an address in this way: (&#39;/api/users&#39;), it will be directed to http://localhost<a href="http://127.0.0.1:5000/">:5000</a>/api/users:</p><p><em>In a CRA (create-react-app) based project, add this line:</em></p><pre>&quot;proxy&quot;: &quot;http://localhost:5000&quot;,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*wjXMidmicGE-mqS-5JZN-w.png" /></figure><p><em>In a Vite based project, add to the vite.config.js file in the client folder:</em></p><pre>import { defineConfig } from &quot;vite&quot;;<br>import react from &quot;@vitejs/plugin-react&quot;;</pre><pre>// <a href="https://vitejs.dev/config/">https://vitejs.dev/config/</a><br>export default defineConfig({<br>  plugins: [react()],<br>  server: {<br>    proxy: {<br>       &quot;/api/&quot;: &quot;http://localhost:5000/&quot;,<br>    },<br>  },  <br>});</pre><p>8. Change back to root folder using cd .. and run npm run dev to start both the back-end and frontend servers simultaneously.</p><p><strong>Now you’re all set to start working on your Full Stack application!</strong></p><h3>Summary</h3><p>In this cheat sheet, we outline the steps to set up a full stack project, ensuring a smooth and efficient setup process. The article covers creating a project folder, setting up the server using essential dependencies, initializing a Git repository, configuring the frontend with Create React App or Vite, setting up a proxy for seamless frontend and back-end communication, and organizing files using best practices.</p><p>By following these instructions, you’ll be well-prepared to dive into your full stack project with confidence, laying a strong foundation for your application development journey.</p><h3>Happy coding!</h3><h3>Appendix I: A GitHub repository</h3><p>Here’s a <a href="https://github.com/obrm/connect-front-to-back-vite">link</a> to a GitHub repository containing a boilerplate code for a full stack application based on this article using Vite. In this <a href="https://github.com/obrm/connect-front-to-back-cra">link</a>, you will find a GitHub repository for a full stack application based on this article using CRA.</p><h3>Appendix II: Testing Your Application</h3><p>To ensure that your full Stack application is functioning correctly, we will add a sample data array to the server.js file and create a GET endpoint for retrieving this data. We will also update the client-side App.js file to fetch and display the data.</p><ol><li>Add the people array to the server.js file and create a GET endpoint for retrieving this array:</li></ol><pre>import express from &#39;express&#39;;<br>import dotenv from &#39;dotenv&#39;;<br><br>dotenv.config({ path: &#39;./config/config.env&#39; });<br><br>const app = express();<br><br>app.get(&#39;/&#39;, (req, res) =&gt; res.send(&#39;Server running&#39;));<br><br>const people = [<br>  { id: 1, name: &#39;John Doe&#39; },<br>  { id: 2, name: &#39;Jane Smith&#39; },<br>  { id: 3, name: &#39;Michael Brown&#39; },<br>  { id: 4, name: &#39;Emily Johnson&#39; },<br>  { id: 5, name: &#39;David Jones&#39; },<br>  { id: 6, name: &#39;Sarah Davis&#39; },<br>  { id: 7, name: &#39;Kevin Wilson&#39; },<br>  { id: 8, name: &#39;Laura Taylor&#39; },<br>  { id: 9, name: &#39;Richard Williams&#39; },<br>  { id: 10, name: &#39;Emma White&#39; },<br>];<br><br>app.get(&#39;/api/people&#39;, (req, res) =&gt; {<br>  res.json(people);<br>});<br><br>const PORT = process.env.PORT || 5000;<br><br>app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`));</pre><p>2. Update the App.js file in the client folder to fetch and display the data:</p><pre>import { useState, useEffect } from &#39;react&#39;<br>import &#39;./App.css&#39;<br><br>function App() {<br>  const [people, setPeople] = useState([]);<br><br>  useEffect(() =&gt; {<br>    const fetchPeople = async () =&gt; {<br>      try {<br>        const response = await fetch(&#39;/api/people&#39;);<br>        const data = await response.json();<br>        setPeople(data);<br>      } catch (error) {<br>        console.error(&#39;Error fetching data:&#39;, error);<br>      }<br>    };<br>    fetchPeople();<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;List of People&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {people.map((person) =&gt; (<br>          &lt;li key={person.id}&gt;{person.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>3. Verify everything is working.</p><ul><li>Run npm run dev in the terminal to start both the back-end and frontend servers concurrently.</li><li>Open your web browser and navigate to <a href="http://localhost:3000/">http://localhost:3000</a> (or <a href="http://localhost:5173/">http://localhost:5173</a> if you are using Vite) to view the List of People.</li><li>Check that the list of people from the people array in the server.js file is displayed correctly.</li></ul><p>By following these steps, you can verify that your full stack application is functioning properly and can proceed with further development.</p><h3>Appendix III: __dirname and __filename are not defined In ES modules</h3><p>In ES modules, the __dirname and __filename variables are not defined. These variables are commonly used in CommonJS modules to get the directory name and file name of the current module, and might be needed in your Node.js project later on.</p><p>While it may be inconvenient to not have access to __dirname and __filename in ES modules, it is not a major limitation. There are alternative ways to get the directory and file name of the current module in ES modules, such as using the URL constructor to parse the import.meta.url property.</p><p>The way to get around this in ES modules is by using the fileURLToPath method imported from the url module, and passing import.meta.url as an argument to get the __filename, and to get the __dirname to use the path.dirname method, like in this example:</p><pre>import path from &#39;path&#39;;<br>import { fileURLToPath } from &#39;url&#39;;<br><br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);</pre><h3>Appendix IV: File and Directory Naming Best Practices</h3><p>Unix-based systems, such as Linux and macOS, are case-sensitive. This means that if you create two files with the names “file.txt” and “File.txt” in the same directory, the system will treat them as two distinct files.</p><p>The implication of this is that you need to be careful when naming your files and directories. If you use<em> inconsistent capitalization</em>, you may end up with multiple files or directories with similar names, which can cause confusion and errors when working with them. Therefore, it’s a <em>best practice to use consistent capitalization</em> and avoid naming conflicts to ensure that your files and directories are easily accessible and manageable <em>across different platforms</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee326576c21a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript — Under the Hood]]></title>
            <link>https://medium.com/@obrm770/javascript-under-the-hood-8cec84bbfd64?source=rss-25ddb3a99175------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cec84bbfd64</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[under-the-hood]]></category>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[inner-workings]]></category>
            <category><![CDATA[javascript-engine]]></category>
            <dc:creator><![CDATA[Ori Baram]]></dc:creator>
            <pubDate>Fri, 17 Mar 2023 14:31:41 GMT</pubDate>
            <atom:updated>2023-03-19T05:41:39.222Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<h3>JavaScript Under the Hood: Mastering the Inner Workings</h3><p><strong>This article is heavily inspired, among other things, by lectures and presentations from the amazing </strong><a href="https://www.udemy.com/course/the-complete-javascript-course/"><strong>Complete JavaScript Course</strong></a><strong> by </strong><a href="https://codingheroes.io/"><strong>Jonas Schmedtmann</strong></a><strong>.</strong></p><p><em>In this article we will focus on JavaScript as it runs in the browser.</em></p><p>Every browser has a JavaScript engine. The most popular engine is Google’s V8 engine. This engine is the engine of Google Chrome and also of Node.js. Of course, all other browsers have their own JavaScript engines.</p><p>A JavaScript engine will always consist of a <em>Call Stack</em> and a <em>Memory Heap</em> and will run on <em>one thread</em> (The JavaScript engine itself runs in several threads (processes) that do different things: compressor for example, garbage collection, etc., but that is not our interest in this article). We will elaborate on them later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*B1vbuWHGHBcJis5yhURs6A.png" /><figcaption>JavaScript Engine</figcaption></figure><h3><strong>Compilation, Interpretation and Just-In-Time Compilation</strong></h3><p>Computers fundamentally understand machine code, which can be represented as assembly language. Therefore, all software must eventually be converted into a format the computer can execute directly. There are three common approaches to this conversion process:</p><ol><li><strong>compilation</strong></li><li><strong>Interpretation</strong></li><li><strong>Just-in-time compilation</strong></li></ol><p><strong>Compilation (Ahead of time Compilation)</strong></p><p>In this method, all the code is converted to machine language at once, and then written to a file in assembly, so that the computer can run the software, which can happen even a long time after the file was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*tT1cT-EXJn2xFtSknFp3ug.png" /><figcaption>Compilation</figcaption></figure><p><strong>Interpretation</strong></p><p>In this method, <a href="https://en.wikipedia.org/wiki/Interpreter_(computing)">the Interpreter</a> goes through the code in an initial pass and then executes it line by line. During the runtime, while running line by line, the code is also compiled into machine language.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*_rheroVO4qyaInqTE00Qmg.png" /><figcaption>Interpretation</figcaption></figure><p>In the past, JavaScript was primarily an interpreted language, which led to certain performance limitations. As web developers discovered, interpreting JavaScript line by line made it challenging to implement optimizations effectively. This is partly due to JavaScript’s dynamic nature, where data types can change at runtime. For example, if a variable is consistently used as a Boolean, an interpreter may still allocate more memory than necessary because it cannot make assumptions about the variable’s type.</p><p>Over time, advances in JavaScript engines, such as <em>just-in-time compilation (JIT)</em>, have been introduced to address these inefficiencies, resulting in significant performance improvements.</p><p><strong>Just-in-time compilation</strong></p><p>In this approach, the entire code is translated into machine language in a single step and is executed immediately afterward. During the conversion process, no intermediate files are created; instead, the code is directly compiled into machine language and executed without delay. This method streamlines the execution process by combining the compilation and execution steps, thereby enhancing the overall efficiency of code processing and execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*VHtjPscT2j19CwU46RzRJw.png" /></figure><p>Today, JavaScript employs <em>just-in-time (JIT) compilation</em>, which combines the benefits of both interpretation and traditional compilation. This real-time compilation process is faster than interpretation because it eliminates the overhead associated with interpreting code line by line. JIT compilation also offers advantages over ahead-of-time compilation, as it can perform optimizations based on runtime information that would not be available during a traditional compilation process. As a result, code executed using JIT compilation is often faster and more efficient than code executed through either interpretation or ahead-of-time compilation alone.</p><h3><strong>Just-in-time compilation in JavaScript</strong></h3><p>Now we will talk about how just-in-time compilation is performed in real time in JavaScript.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcW1Wt2uT44s5cGffdvEJg.png" /><figcaption>Steps involved in JIT compilation for JavaScript</figcaption></figure><p><strong>Parsing</strong></p><p>In the first step of processing JavaScript code, parsing is performed, which involves reading the code and creating an Abstract Syntax Tree (AST). During this process, the code is broken down into meaningful components according to JavaScript’s syntax, such as significant keywords like const, function, or new. These components are then organized into a structured tree. This stage also includes checking the code for any syntax errors. The resulting AST serves as the basis for converting the JavaScript source code into machine code, which can be executed by the JavaScript engine in subsequent stages.</p><p>Say we have a simple primitive variable like this x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*YUlM-wQDCXUA0TfE7o3SFQ.png" /></figure><p>So this is what the AST looks like for this single line of code. Besides the simple things, such as the name, the value and the type, there is a lot more data, which is not our concern. Understanding the exact structure of the AST is not crucial, and there’s no need to delve into its details. This information is provided merely for general knowledge purposes.</p><p><strong><em>Important note: </em></strong><em>Despite both being referred to as ‘trees,’ the AST and the DOM Tree are entirely separate concepts and should not be confused due to the shared terminology. The AST Is a representation of all the code inside the JavaScript engine.</em></p><p><strong>Compilation and Execution</strong></p><p>The subsequent stage is the compilation phase, where the generated AST is converted into machine code. Following this, the machine code is executed immediately, as modern JavaScript engines employ JIT Compilation, as previously mentioned. We will soon discuss the execution stage occurring within the call stack. However, the story doesn’t end there. Modern JavaScript engines, such as the V8 engine, employ sophisticated optimization strategies. Initially, they generate an inefficient version of the machine code to enable prompt execution, and then, in the background, the code undergoes optimization processes. After each optimization, the code is recompiled in the optimized version, with the previous code being replaced without disrupting or halting the execution. This process is what makes modern engines so fast.</p><p>These processes of compression, compilation, and optimization occur within specialized threads (processes) inside the engine, which are inaccessible to us. This thread operates independently from the main thread where the call stack runs and our code executes.</p><p>While different engines may implement this process in various ways, the fundamentals remain the same for modern runtime compilation.</p><h3><strong>The JavaScript runtime environment</strong></h3><p>Next, we’ll discuss the JavaScript runtime environment in the browser, which is crucial to understand.</p><p>Picture the runtime environment as a container encompassing everything needed to run JavaScript within the browser. At the core of the runtime environment lies the JavaScript engine, which we explored in the previous section. Without an engine, there is no runtime, and without a runtime, JavaScript cannot function.</p><p>However, the engine alone is insufficient. For it to operate correctly within the browser, access to Web APIs is necessary. Web APIs encompass everything related to the DOM, timers, and numerous other APIs that we can access in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*MWil2MUrPgrE2L9N2WDNdw.png" /><figcaption>JavaScript runtime in the browser</figcaption></figure><p>For instance, console.log, which we frequently use, is not a part of the language itself but an implementation of an API that JavaScript utilizes. Web APIs are interfaces that offer functionality to the engine in the browser environment but are not part of the JavaScript language itself. JavaScript accesses these APIs through the global Window object in the browser.</p><p>As mentioned earlier, Web APIs are not part of the engine, but they are components of the runtime environment. The runtime environment, as discussed, is a container that holds everything JavaScript needs to function in the browser, in the context of this article. The JavaScript runtime also comprises the Callback Queue, a data structure containing all the callback functions that are ready to execute. For example, when attaching an Event Listener to a DOM element like a button, it responds to a click event. We will see this in action later.</p><p>The function passed to the Event Listener is a Callback Function. When the event occurs, such as a button click, the callback function is invoked. What happens is that the callback function is first moved to the Callbacks Queue, and once the Call Stack is empty, the Callback Function transitions to the Call Stack for execution.</p><p>This occurs through the so-called Event Loop, which takes Callback Functions from the Callback Queue and places them onto the Call Stack for execution. In this manner, the JavaScript runtime implements the Nonblocking Concurrency Model, a non-blocking parallel model. Although JavaScript runs on a single thread, it employs multiple processes using other components in the runtime environment. We’ll discuss this further later and explain why it makes the entire JavaScript runtime non-blocking.</p><p>We have discussed how JavaScript operates in the browser, but it is important to remember that JavaScript can also exist and run outside of browsers, such as in Node.js.</p><p>The Node.js runtime environment is quite similar to the browser’s runtime environment. However, since there is no browser, Web APIs are not present, as there is no browser to provide them. Instead, we have C++ Bindings and a Thread Pool. These details are not our primary concern. The essential point to remember is that different JavaScript runtimes exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KbqM840dmfHwwF1qIfJGrA.png" /><figcaption>Node.js runtime environment</figcaption></figure><h3>The <strong>Execution Context</strong></h3><p>So, how is JavaScript code executed? We will now delve deeper into the topic, starting with the Execution Context. While the Execution Context is an abstract concept, it can be defined as <em>an environment where segments of JavaScript code are executed</em>. It serves as a container that holds all the necessary information for executing specific code, such as local variables or arguments passed to functions. There will always be only one Execution Context in operation, and the default Execution Context is the Global Execution Context, where the top-level code is executed.</p><p>Once the top-level code execution is complete, functions begin to execute. For each function call, a new Execution Context is created, containing all the information required to run that particular function. The same principle applies to methods, as they are merely functions attached to keys within objects.</p><p>After all functions have finished executing, the engine awaits the arrival of Callback Functions to run them, such as those linked to Click Events. As a reminder, it is the Event Loop that supplies these Callback Functions from the Callback Queue when the Call Stack is emptied.</p><p><strong>The components of the Execution Context</strong></p><p>The first thing we have in the Execution Context is the Variables Environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*2YADBHbXbj4ncySbiAiWiQ.png" /></figure><p>In this environment, all variables and function declarations are stored. Additionally, a special ‘arguments’ object is present. As the name suggests, this object contains all the arguments passed to the function currently in the Execution Context, provided the Execution Context belongs to a function. As mentioned earlier, each function has its own Execution Context, so all variables declared by the function will be located in the function’s variable environment. Furthermore, a function can access variables outside of itself due to the Scope Chain. In short, the Scope Chain contains references to all external variables accessible by the function. Lastly, each Execution Context also receives a special variable called the ‘this’ Keyword.</p><p>In summary, the Execution Context comprises the variable environment, the Scope Chain, and the ‘this’ Keyword. These components are created during the Creation Phase, which occurs just before the execution.</p><p>It’s worth mentioning that Arrow Functions do not possess their own <a href="https://blog.logrocket.com/anomalies-in-javascript-arrow-functions/#:~:text=Arrow%20functions%20do%20not%20have%20an%20arguments%20binding">‘arguments’ object</a> or <a href="https://www.w3schools.com/js/js_arrow_function.asp#:~:text=In%20short,%20with%20arrow%20functions%20there%20are%20no%20binding%20of%20this.">‘this’ Keyword</a>. Rather, they make use of the ‘arguments’ object and ‘this’ keyword from their nearest parent function or, alternatively, refer to the Global Scope.</p><p><strong>The Execution Context in practice</strong></p><p>Let’s look at an example to understand the topic better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*sQQhq3wopQFH0gg5nYBimQ.png" /></figure><p>Initially, a Global Execution Context is created for the Top Level code, which is any code not contained within a function. So, at first, only this code is executed. This makes sense because functions only run when they are called or triggered. In this example, the ‘<strong><em>first</em></strong>’ variable is in the Top Level Code, so it’s executed in the Global Execution Context. It’s known that the value of ‘<strong><em>first</em></strong>’ is 5, ‘<strong><em>second</em></strong>’ and ‘<strong><em>third</em></strong>’ are functions, and the value of ‘<strong><em>fourth</em></strong>’ is still unknown.</p><p>In line 14, to get the value of ‘<strong><em>fourth</em></strong>’, the ‘<strong><em>second</em></strong>’ function is activated and its Execution Context is created. Here, the value of ‘<strong><em>a</em></strong>’ is known to be 1, but the value of ‘<strong><em>b</em></strong>’ is still unknown, as it must be obtained from the ‘<strong><em>third</em></strong>’ function. So, the ‘<strong><em>third</em></strong>’ function runs, and its Execution Context is created with the value of ‘<strong><em>c</em></strong>’ being 3 and its ‘arguments’ object containing 1 and 2, which were passed when the function was executed. Now, ‘<strong><em>third</em></strong>’ returns 6 (1 + 2 + 3), we return to the Execution Context of ‘<strong><em>second</em></strong>’, and the value of ‘<strong><em>b</em></strong>’ is now 6. Finally, ‘<strong><em>second</em></strong>’ returns 7 (6 + 1), and the value of ‘<strong><em>fourth</em></strong>’ is determined as 7 in the Global Execution Context.</p><p>In this small and seemingly simple example, we observed a rather complex process. This raises the question of how the JavaScript engine knows when to execute functions, and which Execution Context should be the current one, especially in more intricate code examples. This is where the <strong>Call Stack</strong> comes into play.</p><h3><strong>The Call Stack</strong></h3><p>As previously mentioned, the JavaScript runtime includes the JavaScript engine, which itself comprises the Memory Heap and the Call Stack. So, what exactly is the Call Stack?</p><p>The Call Stack is where Execution Contexts are stacked on top of one another to keep track of the program’s execution. At any given moment, the topmost Execution Context is the one being executed, following the Last-In-First-Out (LIFO) method.</p><p>Referring back to the previous example, the Global Execution Context initially occupies the Call Stack. When the ‘<strong><em>second</em></strong>’ function is called, it moves to the top of the Call Stack, followed by the ‘<strong><em>third</em></strong>’ function when it is called. Once the ‘<strong><em>third</em></strong>’ function finishes and returns a value, it is removed from the Call Stack. Similarly, when the ‘<strong><em>second</em></strong>’ function concludes, it is also removed, leaving the Global Execution Context with all the values it was waiting for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*if_0db0ZcCHVRAPCPDczlA.png" /></figure><p>It’s crucial to understand that while any Execution Context is running and positioned at the top of the Call Stack, all other Execution Contexts are suspended and waiting for the current one to complete. This occurs because JavaScript operates on a single thread, requiring operations to be performed sequentially rather than in parallel. The Call Stack is an essential component of the JavaScript engine itself and not a separate part of the runtime environment.</p><p>In this way, the Call Stack maintains the execution order of Execution Contexts, ensuring that the sequence of execution is always preserved.</p><h3><strong>How Asynchronous JavaScript works behind the scenes</strong></h3><p>Let’s briefly review the JavaScript runtime again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*MWil2MUrPgrE2L9N2WDNdw.png" /><figcaption>JavaScript runtime</figcaption></figure><p>As previously mentioned, the JavaScript runtime environment serves as a container that encompasses all the various components required for executing JavaScript code. At the core of any JavaScript runtime lies the <strong>JavaScript engine</strong>, which is responsible for code execution and object storage in memory, and operates on a single thread. Code execution and object storage occur in the<strong> Call Stack</strong> and the <strong>Memory Heap</strong>. Notably, JavaScript is single-threaded, allowing it to perform only one task at a time, in contrast to languages like Java that can execute multiple code pieces simultaneously.</p><p>Next, we have the <strong>Web APIs environment</strong>, which provides APIs to the engine that aren’t part of the JavaScript language itself. These include timers, the DOM, the fetch API, the Geolocation API, and so on. Additionally, there’s the <strong>Callback Queue</strong>, a data structure containing all the Callback Functions ready to be executed and attached to upcoming events. When the Call Stack is empty, the Event Loop transfers callbacks from the Callback Queue to the Call Stack for execution.</p><p>The <strong>Event Loop</strong> is crucial for enabling asynchronous behavior in JavaScript, allowing for the <strong>Non-Blocking Concurrency Model</strong>. The term “Concurrency Model” refers to how a language handles multiple tasks occurring simultaneously.</p><p>So, how does JavaScript’s Non-Blocking Concurrency Model truly function, and why is the Event Loop so vital? We’ll concentrate on the essential components of the runtime environment for this topic, including <strong>the Call Stack, Event Loop, Web APIs, </strong>and <strong>Callback Queue</strong>. Although the JavaScript engine operates on a single thread, asynchronous code can still be executed non-blockingly. We’ll soon explore how the JavaScript concurrency model operates behind the scenes, using all the parts of the JavaScript runtime we’ve already discussed, by examining a real code sample. We’ve seen how the Call Stack functions, and now we’ll focus on the code in <strong>the Web APIs </strong>and <strong>Callback Queue</strong>.</p><p>Consider the following image element, ‘<strong><em>el</em></strong>’. In the second line, we define the ‘<strong><em>src</em></strong>’ of this image as ‘<strong><em>dog.jpg</em></strong>’, and the image begins to load asynchronously in the background (image loading occurs asynchronously in JavaScript).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*UaNBuZiT4qRwxWzZq1hfaA.png" /></figure><p>What exactly is this enigmatic “<strong>background</strong>”? As we’re aware, everything associated with the DOM isn’t truly part of JavaScript but belongs to Web APIs. Consequently, asynchronous tasks related to the DOM will operate in the Web APIs environment, <strong>not within the JavaScript engine itself!</strong> In fact, this holds true for timers, AJAX calls, and all other asynchronous tasks as well.</p><p>Thus, these asynchronous tasks will execute in the browser’s Web APIs environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*7rbJ1LUhwBSUrBL9z-tiFQ.png" /></figure><p>Should the image load within the Call Stack, it would result in obstructing the execution of the remaining code. Consequently, image loading in JavaScript is asynchronous and does not occur in the Call Stack or the Main Thread of Execution but rather in the separate Web APIs environment, as previously mentioned.</p><p>Now, if we desire to perform an action after the image completes loading, we must listen for the loading event. This is precisely what we do in the following line of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*UaNBuZiT4qRwxWzZq1hfaA.png" /></figure><p>Here, we attach an eventListener to the load event of the image and pass it a callback function, as usual. In practice, this involves registering the callback function in the Web APIs environment, precisely where the image is being loaded, and this callback function will remain there until the loading event concludes.</p><p>In the subsequent line, we execute an AJAX call using the fetch API, and the asynchronous fetch operation also occurs in the Web APIs environment to avoid blocking the aforementioned Call Stack. Finally, we employ the ‘then’ method on the Promise returned by the fetch function, which registers a Callback Function in the Web APIs environment, allowing us to respond to the future resolved value of the Promise. This Callback Function is associated with a Promise that retrieves data from the API, a detail that will be significant later on.</p><p>Thus, we have an image loading in the background and data being fetched from the API, all taking place within the Web APIs environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*RyM4IBKZ4ReazytS3YlA5w.png" /></figure><p>Now we’ve arrived at a particularly intriguing point. Imagine the image has completed loading, and the Load event occurs for that same image. What follows is the callback for this event being sent to the Callback Queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/1*TgK7W2VWsQJBcQawgDOSAg.png" /></figure><p>Essentially, the Callback Queue is an ordered list of all the Callback Functions waiting in line for execution. You can think of the Callback Queue as a to-do list containing all tasks to be carried out, with the Call Stack being the one to perform those tasks in the end.</p><p>In our example, there are no other callbacks in the Callback Queue, but there could be. If there were other callbacks in the queue, then the new callback would be placed at the end and wait patiently for its turn to run.</p><p>This has significant implications that are crucial to note. Consider a situation where you set setTimeOut to five seconds. After five seconds, the callback in setTimeOut will not immediately go to the Call Stack but to the Callback Queue. If there are already other callbacks in the Callback Queue waiting to be executed, and it takes one second to execute all of them, <strong>the setTimeOut callback will run only after six seconds, not five!</strong> These six seconds consist of the five seconds elapsed for the timer, plus the additional second it took to execute all the other queued callbacks. <strong>This means that the time set for setTimeOut functions is not a guarantee.</strong> The only certainty is that setTimeOuts will not run before the specified time, but they may run after it. This all depends on the state of the Callback Queue and the Call Stack (which also needs to be clear to receive callbacks).</p><p>Another important point to mention is that the Callback Queue also holds callbacks resulting from DOM events, such as mouse clicks, key presses, or others. It’s worth noting that many DOM events, like Click Events, are not asynchronous, but they still utilize the Callback Queue to trigger their callbacks. Therefore, if a button with an added Event Listener is clicked, the same process will occur as with the asynchronous loading event.</p><h3>The <strong>Event Loop</strong></h3><p>Now, let’s observe the Event Loop in action. The Event Loop examines the Call Stack to determine if it is empty, excluding the ever-present Global Execution Context, of course. If the Call Stack is indeed empty, indicating that no code is currently being executed, the Event Loop will take the first callback from the Callback Queue and place it onto the Call Stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*8our79Tm7woi-PKvpe5VzA.png" /></figure><p>This process is called an Event Loop Tick. Each time the Event Loop retrieves a Callback Function from the Callback Queue and places it on the Call Stack, we say an Event Loop Tick has occurred. The Event Loop plays a crucial role in coordinating the Call Stack with the Callbacks in the Callback Queue. Essentially, the Event Loop decides when each Callback Function will be executed, orchestrating the entire JavaScript runtime environment.</p><p>It’s important to note that JavaScript itself doesn’t have a sense of time since all asynchronous actions occur outside its engine. The rest of the runtime manages the asynchronous behavior, with the Event Loop determining when and where the JavaScript engine will execute the code it receives.</p><p>To summarize the process, the image began loading asynchronously in the Web APIs environment, not in the Call Stack. We then used addEventListener to attach a callback function to the image load event. The callback function represents the deferred asynchronous code, which we only want to execute after the image has loaded, allowing the rest of the code to continue running. addEventListener registered the callback in the Web APIs environment, where it waited for the loading event. Once the event occurred, the Web APIs environment moved the callback to the Callback Queue. The callback then waited in the Callback Queue for the Event Loop to transfer it to the Call Stack. This transfer occurred when the callback was first in line and the Call Stack was empty. The entire process ensures that the image loads in the background in a non-blocking manner.</p><p>In conclusion, the Web APIs environment, Callback Queue, and Event Loop work together to enable asynchronous code execution in a non-blocking way, even with only one thread in the JavaScript engine.</p><h3><strong>The Microtasks Queue</strong></h3><p>Alright, we still need to address the function waiting for the AJAX call in the background.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*B-BC_Km_dsjQOAesLPIcPQ.png" /></figure><p>This is where Promises come into play. With Promises, the process works slightly differently. Suppose the data has finally arrived. The callbacks associated with Promises, such as the one we registered with the ‘then’ method of the Promise, don’t go to the Callback Queue. Instead, Promise-related Callback Functions have their own dedicated queue, called the <strong>Microtasks Queue</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*InJaPUleArqm94q1G-7CMA.png" /></figure><p>The Microtasks Queue has a unique feature: it takes priority over the Callback Queue. The Event Loop will first check for any callbacks in the Microtasks Queue, and if there are any, it will execute them before running additional callbacks from the Callback Queue. Promise-related Callback Functions are referred to as Microtasks, hence the name Microtasks Queue. While there are other types of Microtasks, they are not relevant at the moment. In our example, we currently have a Microtask in the Microtasks Queue, and the Call Stack is empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*H9OQsheDuDx9EA0s9baduA.png" /></figure><p>The Event Loop will now take the Microtask and place it on the Call Stack, just like it did with the Callback Function from the Callback Queue, regardless of whether the Callback Queue is empty or not. This behavior would be the same even if multiple callbacks were in the Callback Queue, because Microtasks always take precedence. In practical terms, this means that Microtasks can effectively skip ahead of regular callbacks in the queue.</p><p>If another Microtask arrives, it will also be executed before any Callback Function in the Callback Queue. This situation implies that the Microtasks Queue can potentially starve the Callback Queue, as continuously adding more Microtasks may prevent Callback Functions in the Callback Queue from ever being executed. While this scenario is unlikely to occur, it is still important to be aware of this possibility. The execution of asynchronous code with both normal callbacks and microtasks originating from promises is quite similar, with the only difference being that they enter distinct queues and the Event Loop prioritizes microtasks over normal callbacks.</p><p>In conclusion, we explored the inner workings of asynchronous JavaScript, the runtime environment, the Call Stack, Web APIs, the Callback Queue, the Event Loop, and the Microtasks Queue.</p><p>JavaScript’s Non-Blocking Concurrency Model, despite operating on a single thread, has been made possible by the intricate interplay between these components. We have demonstrated how the Event Loop manages and coordinates asynchronous code execution by transferring callbacks from the Callback Queue and Microtasks Queue to the Call Stack, with microtasks taking precedence over regular callbacks. This intricate system enables JavaScript to efficiently handle multiple tasks simultaneously, ensuring a smooth and responsive user experience.</p><h3>Conclusion</h3><p>In conclusion, in this article we got an overview of the inner workings of JavaScript, delving into the mechanics of its engine, compilation techniques, and runtime environment. We have explored the evolution from interpretation to just-in-time (JIT) compilation, which has revolutionized JavaScript’s performance by optimizing code execution based on runtime information. Furthermore, we have examined the intricacies of the JavaScript runtime environment, such as the Execution Context and the Call Stack, and their critical roles in managing code execution. The article has also shed light on the non-blocking concurrency model, detailing the Event Loop, the Web APIs environment and the Microtasks Queue as essential components in managing asynchronous JavaScript. By understanding these fundamental aspects and these core concepts of JavaScript, we can better grasp the power of asynchronous JavaScript and optimize our code to enhance performance and efficiency.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cec84bbfd64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>