<?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"><channel><title><![CDATA[allaroundjavascript.com]]></title><description><![CDATA[This will be a collection of everything I learn and come across regarding Javascript language Ecosystem]]></description><link>https://blog.allaroundjavascript.com</link><generator>RSS for Node</generator><lastBuildDate>Sun, 12 Apr 2026 00:36:02 GMT</lastBuildDate><atom:link href="https://blog.allaroundjavascript.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Prevent Unnecessary Re-Renders of Components When Using useContext with React]]></title><description><![CDATA[When managing global state in React applications, useContext is a powerful and convenient tool. However, it comes with a common pitfall: unnecessary re-renders of components subscribing to the context. In this article,I'll explore why this happens, e...]]></description><link>https://blog.allaroundjavascript.com/prevent-unnecessary-re-renders-of-components-when-using-usecontext-with-react</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/prevent-unnecessary-re-renders-of-components-when-using-usecontext-with-react</guid><category><![CDATA[React]]></category><category><![CDATA[hooks]]></category><category><![CDATA[useContext]]></category><category><![CDATA[useReducer]]></category><category><![CDATA[State Management ]]></category><category><![CDATA[scalability]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Sun, 12 Jan 2025 17:56:18 GMT</pubDate><content:encoded><![CDATA[<p>When managing global state in React applications, <code>useContext</code> is a powerful and convenient tool. However, it comes with a common pitfall: <strong>unnecessary re-renders</strong> of components subscribing to the context. In this article,I'll explore why this happens, evaluate common solutions, and ultimately present a scalable approach using <code>useReducer</code> to solve this problem effectively.</p>
<p>I do prefer with showing an example that you can find in this <a target="_blank" href="https://codesandbox.io/p/sandbox/blue-pine-vy5wmm?file=%2Fsrc%2FApp.js%3A16%2C1">codesandbox</a></p>
<p>For example, in the code sandbox linked above, in the above situation all does work, and paragraph change cause console only when the button that listen to click is indeed clicked</p>
<p>But in App.js if you comment out <code>&lt;AppContainerWithContext /&gt;</code> and load <code>&lt;AppContainer /&gt;</code>, there are two states managed in the container, one called <code>titleText</code> and the other called <code>paragraphText</code>. <code>titleText</code> is passed as a prop to component called <code>TitleText</code> and <code>paragraphText</code> is passed to a component called <code>ParagraphText</code>. Both components are wrapped in <code>React.memo()</code>. There are two buttons called in the <code>AppContainer</code> and each has a function that changes the text back and forth based on the value of separate boolean states.</p>
<p>This happens when a state changes in context, every app (component) accessing data from that context re-renders, even if it's not utilizing the state data that changed (because it's all ultimately passed through the value object). React.Memo does not work on values accessed from context the same way it does for properties.</p>
<h3 id="heading-the-problem-why-does-usecontext-trigger-unnecessary-re-renders"><strong>The Problem: Why Does useContext Trigger Unnecessary Re-Renders?</strong></h3>
<p>React's <code>useContext</code> hook allows components to access shared state from a context provider. However, every time the context value changes, <strong>all components consuming the context re-render</strong>, even if the part of the context they rely on hasn't changed. This can lead to significant performance issues in large applications.</p>
<h4 id="heading-example-of-the-issue"><strong>Example of the Issue</strong>:</h4>
<p>Consider the following context and components:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> AppContext = createContext();

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AppProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">"Title A"</span>);
  <span class="hljs-keyword">const</span> [paragraph, setParagraph] = useState(<span class="hljs-string">"Paragraph A"</span>);

  <span class="hljs-keyword">const</span> value = { title, setTitle, paragraph, setParagraph };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">AppContext.Provider</span>&gt;</span></span>;
}

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useAppContext</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> useContext(AppContext);
}
</code></pre>
<p>Now, suppose you have two components, as in teh codesandbox before, <code>TitleText</code> and <code>ParagraphText</code>, each consuming a specific part of the context:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> TitleText = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { title } = useAppContext();
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
};

<span class="hljs-keyword">const</span> ParagraphText = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> { paragraph } = useAppContext();
  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{paragraph}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};
</code></pre>
<p>When <code>setTitle</code> is called, both <code>TitleText</code> and <code>ParagraphText</code> will re-render because the entire context value object changes, even though only the <code>title</code> has been updated.</p>
<h3 id="heading-common-solutions-and-their-downsides"><strong>Common Solutions and Their Downsides</strong></h3>
<p>One solution is indeed as illustrated with the initial code in the sandbox.</p>
<p><strong>1. Using React.memo</strong></p>
<p>Wrapping components with <code>React.memo</code> can prevent unnecessary re-renders if the component’s props haven’t changed:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> React.memo(TitleText);
</code></pre>
<p>But this approach present 2 main downsides.</p>
<p><strong>Downsides</strong>:</p>
<ul>
<li><p><strong>Dependency Management</strong>: Ensuring props or context values passed to components are stable (e.g., wrapped with <code>useCallback</code> or <code>useMemo</code>) can quickly become cumbersome.</p>
</li>
<li><p><strong>Inefficient for Large State</strong>: For complex applications, it doesn’t scale well because every component still subscribes to the entire context.</p>
</li>
</ul>
<p>Another approach is create a Context for each “main” state that is shared among component that need those state changes and based on those state change need to re-render.</p>
<p>This is called “Splitting Contexts” like:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> AllContextProvider = <span class="hljs-function"><span class="hljs-params">props</span> =&gt;</span> {
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">UserProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">ThemeProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">NotifProvider</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">TimelineProvider</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">CertProvider</span>&gt;</span>
              <span class="hljs-tag">&lt;<span class="hljs-name">MenusProvider</span>&gt;</span>
              {props.children}
              <span class="hljs-tag">&lt;/<span class="hljs-name">MenusProvider</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">CertProvider</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">TimelineProvider</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">NotifProvider</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ThemeProvider</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">UserProvider</span>&gt;</span></span>
  );
};
</code></pre>
<p>and the using as:</p>
<p>…</p>
<p>const TitleContext = createContext();</p>
<p>const ParagraphContext = createContext();</p>
<p>…</p>
<p>But this approach though is completely fine present some issue:</p>
<h4 id="heading-2-splitting-contexts"><strong>2. Splitting Contexts</strong></h4>
<p><strong>Downsides</strong>:</p>
<ul>
<li><p>Leads to "Provider Hell" where components are wrapped in multiple providers.</p>
</li>
<li><p>Harder to manage and scale with more state variables.</p>
</li>
</ul>
<h3 id="heading-a-scalable-solution-refactoring-to-usereducer"><strong>A Scalable Solution: Refactoring to useReducer</strong></h3>
<p>So a better approach is to refactoring from the initial <code>createContext</code> setup using <code>useState</code> to a <code>useReducer</code>-based implementation provides a scalable and efficient solution I have wrote in this <a target="_blank" href="https://codesandbox.io/p/sandbox/blue-pine-vy5wmm?file=%2Fsrc%2Fcontexts%2FAppContext.js%3A50%2C1">codesandbox</a>.</p>
<p>This was considering the initial use of useState</p>
<h4 id="heading-initial-implementation-with-usestate"><strong>Initial Implementation with useState</strong></h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext, useContext, useState } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-keyword">const</span> AppContext = createContext();

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AppProvider</span>(<span class="hljs-params">{ children }</span>) </span>{ <span class="hljs-keyword">const</span> [title, setTitle] = useState(<span class="hljs-string">"Title A"</span>); <span class="hljs-keyword">const</span> [paragraph, setParagraph] = useState(<span class="hljs-string">"Paragraph A"</span>);

<span class="hljs-keyword">const</span> value = { title, setTitle, paragraph, setParagraph };

<span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">AppContext.Provider</span>&gt;</span></span>; }

<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useAppContext</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-keyword">return</span> useContext(AppContext); }
</code></pre>
<p>While functional, this implementation suffers from re-render issues because <code>setTitle</code> and <code>setParagraph</code> cause the entire <code>value</code> object to change, leading to re-renders of all consuming components.</p>
<h4 id="heading-refactored-implementation-with-usereducer"><strong>Refactored Implementation with useReducer</strong></h4>
<p>Using <code>useReducer</code> allows us to centralize state management and define explicit actions for state updates, reducing unnecessary re-renders. Here’s the refactored version:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { createContext, useContext, useReducer, useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;

<span class="hljs-comment">// Initial state</span>
<span class="hljs-keyword">const</span> initialState = {
  <span class="hljs-attr">title</span>: <span class="hljs-string">"Title A"</span>,
  <span class="hljs-attr">paragraph</span>: <span class="hljs-string">"Paragraph A"</span>,
};

<span class="hljs-comment">// Reducer function to handle state updates</span>
<span class="hljs-keyword">const</span> reducer = <span class="hljs-function">(<span class="hljs-params">state, action</span>) =&gt;</span> {
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">"SET_TITLE"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">title</span>: action.payload };
    <span class="hljs-keyword">case</span> <span class="hljs-string">"SET_PARAGRAPH"</span>:
      <span class="hljs-keyword">return</span> { ...state, <span class="hljs-attr">paragraph</span>: action.payload };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
};

<span class="hljs-comment">// Create the context</span>
<span class="hljs-keyword">const</span> AppContext = createContext();

<span class="hljs-comment">// Custom hook for consuming context with a selector</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useAppContext</span>(<span class="hljs-params">selector</span>) </span>{
  <span class="hljs-keyword">const</span> { state } = useContext(AppContext);
  <span class="hljs-keyword">return</span> selector ? selector(state) : state;
}

<span class="hljs-comment">// Context provider</span>
<span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">AppContextProvider</span>(<span class="hljs-params">{ children }</span>) </span>{
  <span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);

  <span class="hljs-keyword">const</span> setTitle = useCallback(<span class="hljs-function">(<span class="hljs-params">title</span>) =&gt;</span> {
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"SET_TITLE"</span>, <span class="hljs-attr">payload</span>: title });
  }, []);

  <span class="hljs-keyword">const</span> setParagraph = useCallback(<span class="hljs-function">(<span class="hljs-params">paragraph</span>) =&gt;</span> {
    dispatch({ <span class="hljs-attr">type</span>: <span class="hljs-string">"SET_PARAGRAPH"</span>, <span class="hljs-attr">payload</span>: paragraph });
  }, []);

  <span class="hljs-keyword">const</span> value = {
    state,
    setTitle,
    setParagraph,
  };

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AppContext.Provider</span> <span class="hljs-attr">value</span>=<span class="hljs-string">{value}</span>&gt;</span>{children}<span class="hljs-tag">&lt;/<span class="hljs-name">AppContext.Provider</span>&gt;</span></span>;
}
</code></pre>
<h3 id="heading-selective-subscriptions-in-components"><strong>Selective Subscriptions in Components</strong></h3>
<p>With <code>useReducer</code>, we can now implement selective subscriptions to ensure only the relevant parts of the state trigger re-renders:</p>
<h4 id="heading-titletext-component"><strong>TitleText Component</strong></h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useAppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../contexts/AppContext"</span>;

<span class="hljs-keyword">const</span> TitleText = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"TitleText Triggered"</span>);

  <span class="hljs-comment">// Subscribe to the title part of the state</span>
  <span class="hljs-keyword">const</span> title = useAppContext(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.title);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> React.memo(TitleText);
</code></pre>
<h4 id="heading-paragraphtext-component"><strong>ParagraphText Component</strong></h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">"react"</span>;
<span class="hljs-keyword">import</span> { useAppContext } <span class="hljs-keyword">from</span> <span class="hljs-string">"../contexts/AppContext"</span>;

<span class="hljs-keyword">const</span> ParagraphText = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"ParagraphText Triggered"</span>);

  <span class="hljs-comment">// Subscribe to the paragraph part of the state</span>
  <span class="hljs-keyword">const</span> paragraph = useAppContext(<span class="hljs-function">(<span class="hljs-params">state</span>) =&gt;</span> state.paragraph);

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{paragraph}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> React.memo(ParagraphText);
</code></pre>
<p>This ensures <code>TitleText</code> re-renders only when the <code>title</code> changes, and <code>ParagraphText</code> re-renders only when the <code>paragraph</code> changes</p>
<h3 id="heading-why-this-works"><strong>Why This Works</strong></h3>
<ol>
<li><p><strong>Centralized State Management</strong>:</p>
<ul>
<li>The reducer handles all state updates in one place.</li>
</ul>
</li>
<li><p><strong>Selective Subscriptions</strong>:</p>
<ul>
<li>Components only subscribe to the parts of the state they need, avoiding unnecessary re-renders.</li>
</ul>
</li>
<li><p><strong>Scalability</strong>:</p>
<ul>
<li>Adding new state variables or actions is straightforward.</li>
</ul>
</li>
<li><p><strong>Performance Optimization</strong>:</p>
<ul>
<li>This pattern minimizes re-renders while maintaining simplicity and readability.</li>
</ul>
</li>
</ol>
<h3 id="heading-lessons-from-redux-and-meta"><strong>Lessons from Redux and Meta</strong></h3>
<p>This approach aligns with patterns established by Redux, which uses reducers and subscribable stores for efficient state management. React’s <code>useReducer</code> brings these concepts into its core API, offering a lightweight and performant solution without needing external libraries.</p>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>When using <code>useContext</code>, unnecessary re-renders can be a significant challenge. While <code>React.memo</code> and splitting contexts offer partial solutions, adopting <code>useReducer</code> with selective subscriptions provides a scalable, maintainable, and efficient approach. This pattern combines the best of React’s core features with lessons learned from libraries like Met's Flux and Redux, making it ideal for managing global state in modern applications.</p>
]]></content:encoded></item><item><title><![CDATA[Battle of the Architectures: Dynamic UI with RTK Query vs. Next.js Simplicity]]></title><description><![CDATA[1. Introduction
When building a modern web application, developers are spoiled for choice with tools and frameworks. On one side, we have RTK Query and React Router, providing flexibility and control over data fetching and routing. On the other, Next...]]></description><link>https://blog.allaroundjavascript.com/battle-of-the-architectures-dynamic-ui-with-rtk-query-vs-nextjs-simplicity</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/battle-of-the-architectures-dynamic-ui-with-rtk-query-vs-nextjs-simplicity</guid><category><![CDATA[React]]></category><category><![CDATA[react-query]]></category><category><![CDATA[rtk query]]></category><category><![CDATA[react router]]></category><category><![CDATA[Next.js]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Sat, 11 Jan 2025 13:15:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1736601180166/377c41eb-6c19-4952-9cab-420f63f66d15.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>1. Introduction</p>
<p>When building a modern web application, developers are spoiled for choice with tools and frameworks. On one side, we have <strong>RTK Query</strong> and <strong>React Router</strong>, providing flexibility and control over data fetching and routing. On the other, <strong>Next.js</strong>, a full-stack framework, offers out-of-the-box solutions for routing, server-side rendering (SSR), and static site generation (SSG). In this article, we’ll compare these two architectures and help you decide which one suits your project best.</p>
<p>TldR Table <strong>Comparison:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Feature</strong></td><td><strong>RTK Query + React Router</strong></td><td><strong>Next.js</strong></td></tr>
</thead>
<tbody>
<tr>
<td>Routing</td><td>Manual with React Router</td><td>File-based routing</td></tr>
<tr>
<td>Data Fetching</td><td>RTK Query for client-side fetching</td><td>Integrated SSG, SSR, and CSR</td></tr>
<tr>
<td>Rendering</td><td>CSR (Client-Side Rendering)</td><td>CSR, SSR, SSG, ISR</td></tr>
<tr>
<td>SEO Optimization</td><td>Requires tools like React Helmet or SSR setup</td><td>Built-in SEO-friendly rendering</td></tr>
<tr>
<td>Setup Complexity</td><td>High (manual integration)</td><td>Low (built-in features)</td></tr>
</tbody>
</table>
</div><p>In the ever-evolving world of web development, developers have a plethora of tools and frameworks to choose from when building modern applications. Two popular approaches stand out when working with <strong>React</strong>:</p>
<ol>
<li><p><strong>RTK Query + React Router</strong>: A combination of the Redux Toolkit's RTK Query for efficient data fetching and React Router for client-side routing. This architecture provides flexibility and control, making it ideal for applications where customization is key. However, it requires manual integration for features like SEO optimization or server-side rendering.</p>
</li>
<li><p><strong>Next.js</strong>: A React-based full-stack framework that simplifies development with features like file-based routing, server-side rendering (SSR), static site generation (SSG), and incremental static regeneration (ISR). It's a go-to solution for applications requiring high performance, built-in SEO optimizations, and ease of use.</p>
</li>
</ol>
<p>In this article, we’ll compare these two architectures, exploring their strengths, weaknesses, and when to use each. To ground the discussion, we'll use a blog application as an example.</p>
<h3 id="heading-rtk-query-react-router-a-dynamic-approach"><strong>RTK Query + React Router: A Dynamic Approach</strong></h3>
<p>When using <strong>RTK Query</strong> and <strong>React Router</strong>, you manage routing and data fetching independently. Here's how you might implement a blog post page:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// BlogPost.js</span>
<span class="hljs-keyword">import</span> { useParams } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;
<span class="hljs-keyword">import</span> { useGetBlogPostQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">'./services/blogApi'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> { id } = useParams();
  <span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: post, isLoading, error } = useGetBlogPostQuery(id);

  <span class="hljs-keyword">if</span> (isLoading) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;
  <span class="hljs-keyword">if</span> (error) <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Error loading blog post.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span>;

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> BlogPost;
</code></pre>
<p>To make this work:</p>
<ul>
<li><strong>React Router</strong> handles routing:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { BrowserRouter <span class="hljs-keyword">as</span> Router, Route, Routes } <span class="hljs-keyword">from</span> <span class="hljs-string">'react-router-dom'</span>;
<span class="hljs-keyword">import</span> BlogPost <span class="hljs-keyword">from</span> <span class="hljs-string">'./BlogPost'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">App</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Router</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Routes</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/blog/:id"</span> <span class="hljs-attr">element</span>=<span class="hljs-string">{</span>&lt;<span class="hljs-attr">BlogPost</span> /&gt;</span>} /&gt;
      <span class="hljs-tag">&lt;/<span class="hljs-name">Routes</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">Router</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> App;
</code></pre>
<p><strong>RTK Query</strong> fetches data dynamically:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { createApi, fetchBaseQuery } <span class="hljs-keyword">from</span> <span class="hljs-string">'@reduxjs/toolkit/query/react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> blogApi = createApi({
  <span class="hljs-attr">reducerPath</span>: <span class="hljs-string">'blogApi'</span>,
  <span class="hljs-attr">baseQuery</span>: fetchBaseQuery({ <span class="hljs-attr">baseUrl</span>: <span class="hljs-string">'/api'</span> }),
  <span class="hljs-attr">endpoints</span>: <span class="hljs-function">(<span class="hljs-params">builder</span>) =&gt;</span> ({
    <span class="hljs-attr">getBlogPost</span>: builder.query({
      <span class="hljs-attr">query</span>: <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> <span class="hljs-string">`/posts/<span class="hljs-subst">${id}</span>`</span>,
    }),
  }),
});

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> { useGetBlogPostQuery } = blogApi;
</code></pre>
<p>This approach allows for high flexibility but requires additional configuration to optimize SEO, performance, and server-side rendering.</p>
<h3 id="heading-nextjs-a-simplified-full-stack-framework"><strong>Next.js: A Simplified, Full-Stack Framework</strong></h3>
<p>Next.js streamlines the creation of dynamic pages with its file-based routing and built-in data-fetching methods. Here’s how the same blog post page might look:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/blog/[id].js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticPaths</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">'https://api.example.com/posts'</span>);
  <span class="hljs-keyword">const</span> posts = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-keyword">const</span> paths = posts.map(<span class="hljs-function">(<span class="hljs-params">post</span>) =&gt;</span> ({
    <span class="hljs-attr">params</span>: { <span class="hljs-attr">id</span>: post.id.toString() },
  }));

  <span class="hljs-keyword">return</span> { paths, <span class="hljs-attr">fallback</span>: <span class="hljs-literal">false</span> };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params">{ params }</span>) </span>{
  <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://api.example.com/posts/<span class="hljs-subst">${params.id}</span>`</span>);
  <span class="hljs-keyword">const</span> post = <span class="hljs-keyword">await</span> res.json();

  <span class="hljs-keyword">return</span> {
    <span class="hljs-attr">props</span>: { post },
  };
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">BlogPost</span>(<span class="hljs-params">{ post }</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">article</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{post.title}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{post.content}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">article</span>&gt;</span></span>
  );
}
</code></pre>
<p>In this case:</p>
<ul>
<li><p><strong>Routing</strong> is handled automatically based on the file structure (<code>pages/blog/[id].js</code>).</p>
</li>
<li><p><strong>Data fetching</strong> is managed through <code>getStaticProps</code> and <code>getStaticPaths</code>, enabling static generation and prefetching for better SEO and performance.</p>
</li>
</ul>
<p>Extended Comparison Table</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>Feature</strong></td><td><strong>RTK Query + React Router</strong></td><td><strong>Next.js</strong></td></tr>
</thead>
<tbody>
<tr>
<td><strong>Routing</strong></td><td>Manual setup with <strong>React Router</strong>. Example: <code>&lt;Route path="/blog/:id" element={&lt;BlogPost /&gt;} /&gt;</code>.</td><td>File-based routing. Example: <code>pages/blog/[id].js</code>.</td></tr>
<tr>
<td><strong>Data Fetching</strong></td><td>Client-side fetching with <strong>RTK Query</strong>, triggered when the page is loaded.</td><td>Built-in options for <strong>SSG</strong> (<code>getStaticProps</code>), <strong>SSR</strong> (<code>getServerSideProps</code>), or <strong>CSR</strong>.</td></tr>
<tr>
<td><strong>Rendering</strong></td><td><strong>Client-Side Rendering (CSR)</strong> by default. Requires additional setup for SSR with tools like Express.</td><td>Supports <strong>Static Site Generation (SSG)</strong>, <strong>Server-Side Rendering (SSR)</strong>, and hybrid rendering.</td></tr>
<tr>
<td><strong>SEO</strong></td><td>Needs tools like <strong>React Helmet</strong> or SSR for better SEO.</td><td>Native SEO optimizations with server-side rendering and static generation.</td></tr>
<tr>
<td><strong>Performance</strong></td><td>Requires manual lazy loading and optimization for images and assets.</td><td>Built-in optimizations like automatic image optimization and page prefetching.</td></tr>
<tr>
<td><strong>API Integration</strong></td><td>Requires a separate backend for API endpoints (e.g., Express, Koa).</td><td>API routes built into the framework under <code>pages/api/</code>.</td></tr>
<tr>
<td><strong>Ease of Use</strong></td><td>More configuration and boilerplate code for routing, data fetching, and SSR setup.</td><td>Simplified setup with ready-to-use features.</td></tr>
<tr>
<td><strong>Flexibility</strong></td><td>Highly flexible. You can use only the libraries and features you need.</td><td>Opinionated and less flexible, but includes everything needed for a full-stack application.</td></tr>
</tbody>
</table>
</div><h3 id="heading-comparison-in-context"><strong>Comparison in Context</strong></h3>
<ul>
<li><p>With <strong>RTK Query + React Router</strong>, you have full control over the architecture but must manually address concerns like server-side rendering and SEO.</p>
</li>
<li><p>With <strong>Next.js</strong>, these features are built-in, making it easier to create a high-performance, SEO-friendly blog application with less manual effort.</p>
</li>
</ul>
<h3 id="heading-real-world-scenarios"><strong>Real-World Scenarios</strong></h3>
<h4 id="heading-when-to-use-rtk-query-react-router"><strong>When to Use RTK Query + React Router</strong></h4>
<ul>
<li><p><strong>Highly Customized Applications</strong>:</p>
<ul>
<li>If your application requires unique routing logic or a custom data-fetching strategy, this architecture gives you full control.</li>
</ul>
</li>
<li><p><strong>Single Page Applications (SPAs)</strong>:</p>
<ul>
<li>Ideal for internal tools, dashboards, or applications where SEO is not a priority.</li>
</ul>
</li>
<li><p><strong>Advanced Data Handling</strong>:</p>
<ul>
<li>Perfect for apps where complex client-side state management is needed, leveraging RTK Query for efficient data fetching and caching.</li>
</ul>
</li>
</ul>
<p><strong>Example Scenario</strong>: A real-time analytics dashboard for an e-commerce platform where SEO is irrelevant but dynamic state management and routing customization are crucial.</p>
<pre><code class="lang-javascript">&lt;Route path=<span class="hljs-string">"/analytics"</span> element={<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">AnalyticsDashboard</span> /&gt;</span></span>} /&gt;
<span class="hljs-keyword">const</span> { <span class="hljs-attr">data</span>: salesData } = useGetSalesDataQuery();
</code></pre>
<h4 id="heading-when-to-use-nextjs"><strong>When to Use Next.js</strong></h4>
<ul>
<li><p><strong>Public-Facing Websites</strong>:</p>
<ul>
<li>If your application needs to be SEO-friendly and fast-loading for users worldwide.</li>
</ul>
</li>
<li><p><strong>Content-Driven Applications</strong>:</p>
<ul>
<li>Ideal for blogs, e-commerce sites, and marketing pages where SEO and performance are key.</li>
</ul>
</li>
<li><p><strong>Full-Stack Projects</strong>:</p>
<ul>
<li>Suitable when you want to combine front-end and back-end in a single project, using API routes for backend logic.</li>
</ul>
</li>
</ul>
<p><strong>Example Scenario</strong>: A multi-author blog platform that needs to pre-render posts for SEO and load quickly with static pages.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// pages/blog/[id].js</span>
<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getStaticProps</span>(<span class="hljs-params">{ params }</span>) </span>{
  <span class="hljs-keyword">const</span> post = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`https://api.example.com/posts/<span class="hljs-subst">${params.id}</span>`</span>).then(<span class="hljs-function">(<span class="hljs-params">res</span>) =&gt;</span> res.json());
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">props</span>: { post } };
}
<span class="hljs-attr">Conclusion</span>: Choosing the right architecture depends on your project needs. For maximum flexibility and fine-grained control, RTK Query + React Router is a great choice. If you’re looking <span class="hljs-keyword">for</span> an all-<span class="hljs-keyword">in</span>-one solution <span class="hljs-keyword">with</span> modern performance and SEO optimization, Next.js stands out.
</code></pre>
<ul>
<li><p><strong>RTK Query + React Router</strong>:</p>
<ul>
<li><p>Use this architecture when you need full customization and are building dynamic, client-centric applications.</p>
</li>
<li><p>Be prepared for additional setup to handle SEO and performance optimizations.</p>
</li>
</ul>
</li>
<li><p><strong>Next.js</strong>:</p>
<ul>
<li><p>Ideal for developers seeking a streamlined solution with built-in features for SEO, performance, and server-side capabilities.</p>
</li>
<li><p>A great choice for projects where time-to-market and simplicity are priorities.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>Choosing the right architecture ultimately depends on the specific needs and goals of your project. Both <strong>RTK Query + React Router</strong> and <strong>Next.js</strong> offer distinct advantages, but they cater to different use cases.</p>
<ul>
<li><p><strong>RTK Query + React Router</strong> is ideal for projects where flexibility and control are paramount. This architecture allows developers to fine-tune every aspect of the application, from routing logic to data fetching and state management. It shines in scenarios where customization is a priority, such as building highly interactive dashboards, SPAs, or applications that require complex client-side state handling. However, it does require more effort to integrate features like server-side rendering or SEO optimizations, making it better suited for internal tools or apps where these features are not critical.</p>
</li>
<li><p>On the other hand, <strong>Next.js</strong> is a robust, all-in-one solution designed for modern web development. It simplifies the development process with built-in features like file-based routing, server-side rendering (SSR), static site generation (SSG), and image optimization. These features make it a perfect choice for public-facing applications where performance, SEO, and time-to-market are critical. From blogs and e-commerce sites to marketing pages and multi-author platforms, Next.js provides an excellent foundation for building scalable and performant web applications with minimal configuration.</p>
</li>
</ul>
<p>When deciding between the two, it’s essential to consider your project requirements:</p>
<ul>
<li><p>Do you need <strong>maximum control</strong> over the architecture, or is a <strong>ready-to-use framework</strong> more appealing?</p>
</li>
<li><p>Are <strong>SEO and performance optimizations</strong> a priority, or are you focused on creating a <strong>dynamic and interactive client-side experience</strong>?</p>
</li>
</ul>
<p>By aligning the choice of architecture with your project’s priorities and technical needs, you can ensure a smoother development process and a better end result.</p>
]]></content:encoded></item><item><title><![CDATA[Difference between extending and intersecting interfaces in TypeScript?]]></title><description><![CDATA[Have you ever found yourself thinking in a complex project asking this question, then in this article I will try to answer with examples
Let's say the following type is defined:
interface Shape {
  color: string;
}

Now, maybe we need a way to abstra...]]></description><link>https://blog.allaroundjavascript.com/difference-between-extending-and-intersecting-interfaces-in-typescript</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/difference-between-extending-and-intersecting-interfaces-in-typescript</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[interface]]></category><category><![CDATA[Types]]></category><category><![CDATA[Interfaces]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Sun, 25 Aug 2024 10:03:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724580087606/b8d5e20b-e277-4efe-95ae-cb7894e6bb5e.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Have you ever found yourself thinking in a complex project asking this question, then in this article I will try to answer with examples</p>
<p>Let's say the following type is defined:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Shape {
  color: <span class="hljs-built_in">string</span>;
}
</code></pre>
<p>Now, maybe we need a way to abstract further some properties but still keep them reusable as type, like in the following ways to add additional properties to this type:</p>
<p>We could go for an</p>
<p><strong>Extension</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Square <span class="hljs-keyword">extends</span> Shape {
  sideLength: <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>Or with using a type alias and thus an intersection</p>
<p><strong>Intersection</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> Square = Shape &amp; {
  sideLength: <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>Then what is the difference between both approaches?</p>
<p>Which one is better to use when or they basically in practice do not make any difference?</p>
<p>Let's start saying that there are differences which may or may not be relevant in a particular scenario.</p>
<p>Perhaps the most significant is the difference in how members with the same property key are handled when present in both types.</p>
<p>Consider:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> NumberToStringConverter {
  convert: <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">number</span></span>) =&gt;</span> <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">interface</span> BidirectionalStringNumberConverter <span class="hljs-keyword">extends</span> NumberToStringConverter {
  convert: <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>The <code>extends</code> above results in an error because the deriving interface declares a property with the same key as one in the derived interface but with an incompatible signature.</p>
<pre><code class="lang-typescript">error TS2430: Interface <span class="hljs-string">'BidirectionalStringNumberConverter'</span> incorrectly <span class="hljs-keyword">extends</span> <span class="hljs-keyword">interface</span> 'NumberToStringConverter'.

  Types of property 'convert' are incompatible.
      Type '(value: string) =&gt; number' is not assignable to type '(value: number) =&gt; string'.
          Types of parameters 'value' and 'value' are incompatible.
              Type 'number' is not assignable to type 'string'.
</code></pre>
<p>However, if we employ intersection types</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> NumberToStringConverter = {
  convert: <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">number</span></span>) =&gt;</span> <span class="hljs-built_in">string</span>;
}

<span class="hljs-keyword">type</span> BidirectionalStringNumberConverter = NumberToStringConverter &amp; {
  convert: <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span></span>) =&gt;</span> <span class="hljs-built_in">number</span>;
}
</code></pre>
<p>There is no error whatsoever and, furthermore, this is useful indeed as a value conforming to this particular intersection type is easily conceived of.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> converter: BidirectionalStringNumberConverter = {
    convert: <span class="hljs-function">(<span class="hljs-params">value: <span class="hljs-built_in">string</span> | <span class="hljs-built_in">number</span></span>) =&gt;</span> {
        <span class="hljs-keyword">return</span> (
          <span class="hljs-keyword">typeof</span> value === <span class="hljs-string">'string'</span>
            ? <span class="hljs-built_in">Number</span>(value)
            : <span class="hljs-built_in">String</span>(value)
          ) <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span> &amp; <span class="hljs-built_in">number</span>; <span class="hljs-comment">// type assertion is an unfortunately necessary hack.</span>
    }
}
</code></pre>
<p>Note that the implementation of the intersection, as shown above, involves some awkward types and assertions but these are purely implementation artifacts which do not contribute to the type of the converter object which is solely determined by the type <code>BidirectionalStringNumberConverter</code> used to annotate the object literal <code>converter</code>.</p>
<p>let's see this applied:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> s: <span class="hljs-built_in">string</span> = converter.convert(<span class="hljs-number">0</span>); <span class="hljs-comment">// `convert`'s call signature comes from `NumberToStringConverter`</span>

<span class="hljs-keyword">const</span> n: <span class="hljs-built_in">number</span> = converter.convert(<span class="hljs-string">'a'</span>); <span class="hljs-comment">// `convert`'s call signature comes from `BidirectionalStringNumberConverter`</span>
</code></pre>
<p><a target="_blank" href="https://www.typescriptlang.org/play/?ts=3.3.3#code/C4TwDgpgBAcgrgWwEYQE4BUD2BlYqCWAdgOYDCmhAbmsGlALxQDeAUFO1AMYXWrABcUABSUAhgBs4EQYUQpUASgYA+KAGc8RYgG4WAXxYtQkKACF8AE3yoInYPgoTcBEvGRpyVGnUYAyWHJoWM5anry0qFD+rBxcPDSCIhJSghouxEr0qrLuqLp6uiwA9EVQAIKEFlDAABb4alD1UKJQxJiYVbVajZUQEFWiDS1iktDchABmmKgI3cCY1TXQxtBNEIP44iBxhJwQ+NQWLOMaO+FoguZWNnYOhE6aroGoYd6RjDEc4+GJIynqj2IUAAPlAcvJMqpPrF2DZgHBUIRhCtMBMoH9oPQsVAAORpLQ4qAAfgCuSSoyUghCJHJUgUSkGAPSUTBz20UBK1XA0EGahod0aQyRcEm03h91oWzBtggajUolQ2xqok4AGsAHRsDgGAwnYDqVKAhhnN7q740IQABgU7M5AANzXw7XiuBJxOp8MQJQixpgELKoBNUH6oHa3PJgoDXnw0HbDHqwTJnsbHREzfE+EIcaIcTaOaUHRngM6Gpw3R6vaJ4TY4v6GkGQ3artZbPZHOJqcRwx4i7GgA">Playground</a></p>
<p>Another important difference, <code>interface</code> declarations are open ended. New members can be added anywhere because multiple <code>interface</code> declarations with same name in the same declaration space are <em>merged</em>. This is in direct contrast to type expression produced by <code>&amp;</code> which creates an anonymous expression that can be bound to an alias for reuse but not augmented via merging.</p>
<p>Here is a common use for merging behavior</p>
<p><strong>lib.d.ts</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Array&lt;T&gt; {
  <span class="hljs-comment">// map, filter, etc.</span>
}
</code></pre>
<p><strong>array-flat-map-polyfill.ts</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">interface</span> Array&lt;T&gt; {
  flatMap&lt;R&gt;(f: <span class="hljs-function">(<span class="hljs-params">x: T</span>) =&gt;</span> R[]): R[];
}

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">Array</span>.prototype.flatMap !== <span class="hljs-string">'function'</span>) {
  <span class="hljs-built_in">Array</span>.prototype.flatMap = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">f</span>) </span>{ 
    <span class="hljs-comment">// Implementation simplified for exposition. </span>
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.map(f).reduce(<span class="hljs-function">(<span class="hljs-params">xs, ys</span>) =&gt;</span> [...xs, ...ys], []);
  }
}
</code></pre>
<p>Notice how no <code>extends</code> clause is present, although specified in separate files the interfaces are both in the global scope and are merged by name into a single logical interface declaration that has both sets of members. (the same can be done for module scoped declarations with slightly different syntax)</p>
<p>By contrast, intersection types, as stored in a <code>type</code> declaration, are closed, not subject to merging.</p>
<p>There are many, many differences. You can read more about both constructs in the TypeScript Handbook. The <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/2/objects.html#1">Object Types</a> and the <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/2/types-from-types.html">Creating Types from Types</a> sections are particularly relevant.</p>
]]></content:encoded></item><item><title><![CDATA[What is Typescript 's exclamation(!) mark operator, or bag and how does it work?]]></title><description><![CDATA[TL;DR
The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".
I think this qu...]]></description><link>https://blog.allaroundjavascript.com/what-is-tss-exclamation-mark-operator-or-bag-and-how-does-it-work</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/what-is-tss-exclamation-mark-operator-or-bag-and-how-does-it-work</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[Null Safety]]></category><category><![CDATA[undefined]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Fri, 23 Aug 2024 08:40:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1724402698000/1c90caa0-227c-4b8c-8c9e-e43639b49f71.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>TL;DR</p>
<p>The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".</p>
<p>I think this quite a clear topic but eventually not for many that are just starting to learn Typescript or for who has to deal with some codebase that is well write with it.</p>
<p>Let's start from an example:</p>
<p>Consider this code</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">let</span> referenceA: <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span> | <span class="hljs-literal">undefined</span> = <span class="hljs-literal">null</span>
<span class="hljs-keyword">const</span> n = <span class="hljs-number">1</span>
<span class="hljs-keyword">if</span> (n) {
    referenceA= <span class="hljs-string">"Hello My World!"</span>    
}
<span class="hljs-built_in">console</span>.log(referenceA.toLowerCase()) <span class="hljs-comment">// Error: Object is possibly 'null'.ts(2531)</span>
</code></pre>
<p>To avoid that error we can to tell the compiler that the variable can't be Null using the Typescript "!" operator, which's called non-null assertion operator.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">let</span> referenceA: <span class="hljs-built_in">string</span> | <span class="hljs-literal">null</span> | <span class="hljs-literal">undefined</span> = <span class="hljs-literal">null</span>
    <span class="hljs-keyword">const</span> n = <span class="hljs-number">1</span>
    <span class="hljs-keyword">if</span> (n) {
        referenceA= <span class="hljs-string">"Hello My World!"</span>    
    }
    <span class="hljs-built_in">console</span>.log(referenceA!.toLowerCase())
</code></pre>
<p>So That's the non-null assertion operator. It is a way, we developers can tell the compiler "this expression cannot be <code>null</code> or <code>undefined</code> here, so don't complain about the possibility of it being <code>null</code> or <code>undefined</code>." Sometimes the type checker is unable to make that determination itself.</p>
<p>It is explained in <a target="_blank" href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-assertion-operator">the TypeScript release notes</a>:</p>
<p><code>A new ! post-fix expression operator may be used to assert that its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact. Specifically, the operation x! produces a value of the type of x with null and undefined excluded. Similar to type assertions of the forms &lt;T&gt;x and x as T, the ! non-null assertion operator is simply removed in the emitted JavaScript code.</code></p>
<p>It is "assert" in the sense that <em>the developer is asserting it</em>, not in the sense that a test is going to be performed. The last line indeed indicates that it results in no JavaScript code being emitted.</p>
<p>So to sum-up:</p>
<p>The bang operator tells the compiler to temporarily relax the "not null" constraint that it might otherwise demand. It says to the compiler: "As the developer, I know better than you that this variable cannot be null right now".</p>
<p>Some very use case, for example are considering that unlike some other languages (eg. C#), JS (and therefore TS) does not demand that variables are initialized before use.</p>
<p>Or, to look at it another way, in JS all variables declared with <code>var</code> or <code>let</code> are implicitly initialized to <code>undefined</code>. Further, class instance properties can be declared as such, so</p>
<p><code>class C { constructor() {</code></p>
<p><code>this.myVar = undefined; }</code></p>
<p><code>}</code></p>
<p>that is perfectly legal. Finally, lifecycle hooks are framework dependent; for instance Angular and React implement them differently. So the TS compiler cannot be expected to reason about them.</p>
]]></content:encoded></item><item><title><![CDATA[Typescript generic  : T vs T extends {}  Difference  and Examples]]></title><description><![CDATA[TLDR: "T extend {}" allow you your function or class' method to accept pretty much anything except null and undefined. T can be a primitive though.
On the other hand, only T, allow accepting also those value, null and undefined
I do work with Typescr...]]></description><link>https://blog.allaroundjavascript.com/typescript-generic-t-vs-t-extends-difference-and-examples</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/typescript-generic-t-vs-t-extends-difference-and-examples</guid><category><![CDATA[TypeScript]]></category><category><![CDATA[TypeScript Generics]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Mon, 17 Apr 2023 20:57:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681765416092/724d9bb9-5f3c-45d6-8fb5-713120c5b158.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>TLDR: "T extend {}" allow you your function or class' method to accept pretty much anything except null and undefined. T can be a primitive though.</p>
<p>On the other hand, only T, allow accepting also those value, <strong>null</strong> and <strong>undefined</strong></p>
<p>I do work with Typescript in a production application, though I started to learn yet</p>
<p>way before, since more than a year now, and as with anything that one learns there are</p>
<p>many aspects, at some point one starts to dig into details and advanced concept.</p>
<p>This is the case for today's subject. I have found myself writing a code:</p>
<pre><code class="lang-plaintext">export class Attributes&lt;T&gt; {
  constructor(private data: T) {}

  get&lt;K extends keyof T&gt;(key: K): T[K] {
    // this make data be an object
    return this.data[key];
  }

  set(update: T): void {
    Object.assign(this.data, update);
  }
}
</code></pre>
<p>in which the Typescript compiler under the 'this.data' object throw the following:</p>
<pre><code class="lang-plaintext">No overload matches this call.
  Overload 1 of 4, '(target: {}, source: T): {} &amp; T', gave the following error.
    Argument of type 'T' is not assignable to parameter of type '{}'.
  Overload 2 of 4, '(target: object, ...sources: any[]): any', gave the following error.
    Argument of type 'T' is not assignable to parameter of type 'object'.ts(2769)
Attributes.ts(7, 25): This type parameter might need an `extends {}` constraint.
Attributes.ts(7, 25): This type parameter might need an `extends object` constraint.
(property) Attributes&lt;T&gt;.data: T
</code></pre>
<p>At the beginning, I did not I understood, because the tutorial I was reviewing is quite advanced and updated, then after some research, I find out that things did change a bit after version 3.5 of Typescript.</p>
<p>In TypeScript 3.5 a change was made so that generic type parameters are implicitly constrained by unknown instead of the empty object type {}, this means that</p>
<pre><code class="lang-plaintext">function funcA&lt;T&gt;() { }

function funcB&lt;T extends {}&gt;() {}
</code></pre>
<p>there are some minor details about the difference between funcA() and funcB().</p>
<p>These differences from TS 3.5 are the following:</p>
<p>If you don't explicitly constrain a generic type parameter via extends XXX, then it will implicitly be constrained by unknown, the "top type" to which all types are assignable. So in practice that means the T in funcA&lt;T&gt;() could be any type you want.</p>
<p>On the other hand, the empty object type {}, is a type to which nearly all types are assignable, except for null and undefined, when you have enabled the --<em>strictNullChecks</em> compiler option (which you should). Even primitive types like string and number are assignable to {}.<br />So to make it more clear Compare:</p>
<pre><code class="lang-plaintext">function funcA&lt;T&gt;() { }

funcA&lt;undefined&gt;(); // okay

funcA&lt;null&gt;(); // okay

funcA&lt;string&gt;(); // okay

funcA&lt;{ a: string }&gt;(); // okay
</code></pre>
<p>Meanwhile</p>
<pre><code class="lang-plaintext">function funcB&lt;T extends {}&gt;() { }

funcB&lt;undefined&gt;(); // error

funcB&lt;null&gt;(); // error

funcB&lt;string&gt;(); // okay

funcB&lt;{ a: string }&gt;(); // okay
</code></pre>
<p>So if one needs to avoid null and undefined passed as value then T extends {} is the one to use.</p>
<p>It might be a little confusing that {}, a so-called "object" type, would accept primitives like string and number. It helps to think of such curly-brace-surrounded types like {} and {a: string} as well as all interface types not necessarily as "true" object types, but as types of values where you can index into them as if they were objects without getting runtime errors. Primitives except for null and undefined are "object-like" in that you can treat them as if they were wrapped with their object equivalents:</p>
<p><code>const s: string = "";s.toUpperCase(); // okay</code></p>
<p>And therefore even primitives like string are assignable to curly-brace-surrounded types as long as the members of those types match:</p>
<p><code>const x: { length: number } = s; // okay</code></p>
<p>If you really need to express a type that only accepts "true", i.e., non-primitive objects, you can use the object:</p>
<p><code>const y: object &amp; { length: number } = s; // error</code></p>
<p><code>const z: object &amp; { length: number } = { length: 10 }; // okay</code></p>
<p>I will follow with more example and some codesandbox.</p>
]]></content:encoded></item><item><title><![CDATA[What does npm install with --force and --legacy-peer-deps do exactly?]]></title><description><![CDATA[_________________________________________________________________________________________
TL;DR:
You may have this issue if you're upgrading from NPM v6 / Node v12.
NPM v7+ installs peerDependencies by default; this is not the case with previous vers...]]></description><link>https://blog.allaroundjavascript.com/what-does-npm-install-with-force-and-legacy-peer-deps-do-exactly</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/what-does-npm-install-with-force-and-legacy-peer-deps-do-exactly</guid><category><![CDATA[Node.js]]></category><category><![CDATA[Continuous Integration]]></category><category><![CDATA[dependencies]]></category><category><![CDATA[npm error]]></category><category><![CDATA[debugging]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Sat, 01 Apr 2023 16:06:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680364453686/cbdba0ee-ae89-4272-9fff-e977fd01aa0f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>_________________________________________________________________________________________</p>
<p><strong>TL;DR:</strong></p>
<p>You may have this issue if you're upgrading from NPM v6 / Node v12.</p>
<p>NPM v7+ installs peerDependencies by default; this is not the case with previous versions of NPM.</p>
<p>NPM modules must name specific versions of their peerDependencies</p>
<p>If you already have a peerDependency installed, but not with a version named by the module, then NPM v7+ will throw an error.</p>
<p>Adding <strong>--legacy-peer-deps</strong> ignores this new requirement, at the risk of introducing breaking changes, that can be eventually fixed with the run of <strong>npm audit fix</strong>.</p>
<p>_______________________________________________________________________________________</p>
<h2 id="heading-whats-a-potential-use-case"><strong>What's a potential use case?</strong></h2>
<p><strong>Why there could be a benefit or even a need to use this command</strong></p>
<p>As a developer there are case in where you have to work on projects starting from framework or libraries that you haven’t made or developed yourself, unfortunately some of them especially in the npm world are sometimes left not update or in order to work with their dependencies last versions.</p>
<p>This situation can arise both in meanwhile doing personal projects or even projects that have a production version.</p>
<p>Especially in the node world this can lead many times in loose many hours in order to try to indeed startup those project or even integrate a library or more then one that where indeed left behind in order to work with new version of other which API are behind changed and are not anymore compatible with dependencies.</p>
<p>I am quite sure you may have faced such similar situation and didn’t understood the strange situation.</p>
<p>Basically I am will simpfy with a more graphical approch with a React Native approach, a case I had last years when running an old tutorial:</p>
<p>Project Alpha(e.g React Native application ), that it can’t compile and throw many errors.</p>
<p>Basically what could have happened is:</p>
<p>dependecy 1 that is compatible (it’s API are compatible with Project Alpha) depends of other:</p>
<p>a, b, c</p>
<p>Let’s say b, c( but can be many more, and more level deeper) are not been update, this can be the case of for example function signature, or class constructors have changed.</p>
<p>So on this situation you should KNOW and update those single dependencies manually.</p>
<p>Unfortunately it can be that an update version of those b, c dependecies do now exist at all.</p>
<p>So here it comes in rescue this command. In particular here how it behaves:</p>
<p><strong>--legacy-peer-deps restores peerDependency installation behavior from NPM v4 thru v6</strong></p>
<p>One way of thinking of this flag is that it isn't doing something new; rather it's telling NPM not to do something new, actually it is telling NPM to DO NOT install latest version of dependencies, since NPM v7 now installs peerDependencies by default.</p>
<p><strong>In many cases, this is leading to version conflicts, which will break the installation process.</strong></p>
<p>The --legacy-peer-deps flag was introduced with v7 as a way to bypass peerDependency auto-installation; it tells NPM to ignore peer deps and proceed with the installation anyway. This is how things used to be with NPM v4 thru v6.</p>
<p>If you're unclear about the difference between regular deps and peer deps, here is a bit of context:</p>
<h3 id="heading-dependencies-vs-peerdependencies"><strong>Dependencies vs peerDependencies</strong></h3>
<p>Dependencies: Libraries or modules that an NPM module needs in order to work in production.</p>
<p>peerDependencies: A peer dependency is a specific version or set of versions of a third-party software library that a module is designed to work with. They're similar in concept to the relationship between a browser extension and a browser. (Example: react-redux has two quite logical peerDependencies: react and redux.)</p>
<p>Ad exampl, in React ecosystem due to the large number of modules that haven't specifically added React v17 (or more recently, React 18) as a peerDependency, it's now commonplace to encounter the unable to resolve dependency tree error when running npm installs within a v17 React application.</p>
<p>Or as it really saved my life, when I recompiled a React Native App that I was not update since many months.</p>
<p>This error will fire whenever a module (or any of its own dependencies) lists a previous major version of React as a peerDependency without specifically including React v17 as well.</p>
<p>(Note: Similar behavior will occur with the major-version update of any other framework or library.)</p>
<h2 id="heading-correlated-commands">Correlated commands</h2>
<h3 id="heading-how-to-check-peerdependencies-for-any-given-module"><strong>How to check peerDependencies for any given module</strong></h3>
<p>NPM itself doesn't list peer deps on the pages of a given module. However, there is a simple workaround to check for peer deps, either before or after install. Simply run:</p>
<p><strong>npm info name-of-module peerDependencies</strong></p>
<p>This command will return the name of each peerDependency along with all compatible version(s).</p>
<p>In general once taking a package.json from a project that does not have Semantic Versioning due the fact that NPM do install latest version of X library on the registry, if dependencies of such are not compatible with your local one then intergration error as mentioned above are occurring.</p>
<p>For about this I recommend to check my other article that mention a better way of doing CI in NPM ecosystem, as a basic would always be better run NPM install CI vs NPM Install.</p>
<h3 id="heading-audit-fix">Audit fix</h3>
<p>It can be as happened as you didn’t know how to use this command, you have already run npm install and have many errors message regarding dependencies, in this case do not get frustrutared and try to run the following:</p>
<p><strong><em>npm audit fix</em></strong></p>
<p>is not only "upgrading" but sometimes also downgrading in order to install the stable version that fix the issue, sometimes those issues comes in newer versions that maybe have introduced bugs or simply do not match with previous package's API etc.</p>
<p>E.g in my case for example npm install have upgrade react-script to 5.0.0 that has some issue and after have run:</p>
<p><strong>npm audit fix --force</strong></p>
<p>The force flag does : To address all issues (including breaking changes), run: npm audit fix --force</p>
<p>it installed the 3.0.1 with following message:</p>
<p>npm WARN audit Updating react-scripts to 3.0.1,which is a SemVer major change.</p>
<p>So it does the upgrade to the stable version of that package that fix the issue.</p>
]]></content:encoded></item><item><title><![CDATA[Should you spend planning a commit before writing code?]]></title><description><![CDATA[I have to be honest in the past something like 8 years ago I have spend some amount of time thinking when was the right to commit.
Then as for any topic I read around and different source, and as everything this depends of the project, like a solo on...]]></description><link>https://blog.allaroundjavascript.com/should-you-spend-planning-a-commit-before-writing-code</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/should-you-spend-planning-a-commit-before-writing-code</guid><category><![CDATA[commit]]></category><category><![CDATA[Git]]></category><category><![CDATA[Software Engineering]]></category><category><![CDATA[software architecture]]></category><category><![CDATA[version control]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Wed, 10 Aug 2022 18:11:03 GMT</pubDate><content:encoded><![CDATA[<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1660154852876/G7yg9fgAo.png" alt="PlanningCommits.png" /></p>
<p>I have to be honest in the past something like 8 years ago I have spend some amount of time thinking when was the right to commit.
Then as for any topic I read around and different source, and as everything this depends of the project, like a solo one, or with a Team.
Indeed for this different cases, I have 2 different approach, both based on the principle to see who is going to review the commits: in the first case me of a version of me in the future or  eventually another component of the Team in the future.</p>
<p>But then a connection of mine wrote me:</p>
<p>"At the moment I'm spending more time planning out a commit than actually writing code when adding a new feature. Less than two hours would be lucky, some times I'd spend a good part of the day without writing any code. This is making me unhappy, since I don't feel I'm productive enough (I'm living with my parents, and have never been employed as a programmer)"</p>
<p>If I don't do this amount of planning, I just end up writing code that will have to be undone before I commit, and this just messes up my project, because don't like wasting any code I've already written and try to recycle it as much as possible (my precious).</p>
<p>Someone said that programming isn't about how fast you can type, it's about how fast you can think. I'm not very good at thinking fast." ( Well I am the same).</p>
<p>I think I'm overly cautious making my productivity not economically viable, but even still its far too easy for me to waste a whole lot of time making a mess of my codebase."</p>
<p>This was what he told me and I though that at his stage I even didn't had much thoughts but at lower level.</p>
<p>My experience is that when coding for a living, especially as a junior in a team, typically not much design work is needed. This is because you'll be working in an existing code base. Chances are, you'll often be working on a feature that is similar to existing features, so you can look at those as an example. This is nowhere near as boring as it may sound; one can is learning plenty of things, still need to understand the examples and adapt them to suit your needs.</p>
<p>Designing something new can indeed be much harder, but it is also much rarer, especially when you're a junior developer, or let's say when you take the challenge to develop something on the side even adapting tutorials can be.</p>
<p>That is to say: in a typical junior-level development job, I don't think one run into the things this person was worried about. Or at least to a far smaller extent.</p>
<p>Planning and coding are very much iterative processes. You plan a bit, try to create some code with the planning in mind, which makes you realize that you overlooked something during planning, so you adjust the plan, code some more, rinse, repeat.</p>
<p>I like to think that this is also how artists work. It's a creative journey. Often messy, sometimes boring, sometimes exhilarating, sometimes frustrating. Sometimes you end up with something boring that just works, sometimes with something beautiful that doesn't work. And, every now and then, with something that works and is beautifully elegant.</p>
<p>""Someone said that programming isn't about how fast you can type, it's about how fast you can think. I'm not very good at thinking fast.""</p>
<p>Actually neither are most people, especially if they have to do the thinking without seeing any code. Coding helps to make things concrete. It may also obfuscate the bigger picture, so zooming in (code) and out (planning) is part of the iterative process.</p>
<p>It's also worth noting that people, after years of professional experience, develop a kind of muscle memory for specific approaches, and an instinct for applying these. Which is half the battle when making something new. You cannot be expected to have that already (nor should you expect it from yourself).</p>
<p>Unfortunately <em>the "internet" show only ready "work" as YouTubers  if they would make up stuff on the spot, type it in and are done. </em>  <strong>That is not how it goes. </strong></p>
<p>They planned and practiced too beforehand or they show you things they have done hundreds of times before, that are in their routine.</p>
<p>When you see a musician play for one minute on YouTube it is safe to assume they spent days practicing, recorded tens of takes and ultimately picked the best one. And that is not counting the years they put in to get up to their level in the first place.</p>
<p>Writing software is a skill like any other that takes time to develop. And different people specialize in different things. And, in your particular specialty, there will likely always be some people who can do things quicker.
If you are just starting with Git, I would recommend this free resource live project from manning <a target="_blank" href="https://www.manning.com/liveproject/getting-started-with-git?utm_source=CarmineT85&amp;utm_medium=affiliate&amp;utm_campaign=liveproject_hamedy_getting_11_2_21&amp;a_aid=CarmineT85&amp;a_bid=ff55eb58">Getting Started with Git</a> or / after to get even more practice for advance topic and work in a Team and feel completely confident, I would recommend this other book <a target="_blank" href="https://www.manning.com/books/git-in-practice?utm_source=CarmineT85&amp;utm_medium=affiliate&amp;utm_campaign=book_mcquaid_git_9_1_14&amp;a_aid=CarmineT85&amp;a_bid=5688bbf4">Git in practice</a>
Deciding when and where to optimize is another thing. It seems many people tend to be obsessively working to satisfy own compulsive need to eradicate any imperfections. This is fine in the environment how many great creators started their career. 
The key but not easy to put in practice is to enjoy it and learn from it while no one is asking you when it's done yet.</p>
<p>My general approach is that code that just works (and is readable) and that apply to code style if one is working in a Team, is good enough. </p>
<p>If later on, new requirements or new features means that the code is no longer good enough, you can adjust it. That adjustability is the reason the world moved away from specialized hardware and embraced software (running on generic hardware).</p>
<p>My approach with unfinished "Classes" or "Component" that for example still miss the part for retrieve API or that "useEffect" to implement something that has to run only after first render or after a variable change, is to "stash", so I can recall that method / approach or part, where I put some effort but on overall still not working or not working as should or as I expect, anytime I need or integrate with a branch or another approach.</p>
<p>Indeed I see commits are not something you plan. Commits, especially in the early stages of figuring out a problem, are little more than save-points along a journey. Instead, spend time thinking about the problem.</p>
<p>Break big problems into little problems, and then break those down into smaller problems. 
This is one of the first rule and approach are taught at university or bootcamps, or at least it should be. 
At least it was at University of Bologna during my Java course.</p>
<p>Keep decomposing and digesting problems until your mind can see a single line of code. </p>
<p>Write that line of code. Keep writing code as you think. Mess up. Change the code. Change it 15 more times(stash it if some part works as your expected), if need be. Stop and commit when you feel like losing that code would be a big setback, or during a natural break in your rhythm of thought and writing code.</p>
<p>There is no general rule or guideline. When to commit is more a feeling than some methodological practice. Basically, if you think, "it would really suck to lose this code while I figure things out," then commit what you have. Just be sure to work in your own branch so no one else has to deal with whatever state your code is in.</p>
<p>Don't worry about whether the code works, compiles, or looks pretty. Many version control systems allow you to combine many messy commits into one clean, cohesive changeset. </p>
<p>Version control is a tool just as much as a text editor. Version control just happens to be really good at backing up your work.</p>
<p>So in general  there should not really time planning a commit. </p>
<p>The approach should be to write code until you feel like you have something to lose, then commit those changes so you don't.</p>
<p>This topic is connect on the question of how many commits to do and also has to do with the great tooling and feature that git give to developers, and that is amazing tooling set.</p>
]]></content:encoded></item><item><title><![CDATA[Asynchronous calls in React : useEffect() + useState()]]></title><description><![CDATA[How we do properly handle asyncronous call such retrieve data from some APIs?
Well let's keep it simple and assume that those data once retrieve are going to be used in few places so a useState() or few of them will be enough, so in following example...]]></description><link>https://blog.allaroundjavascript.com/asynchronous-calls-in-react-useeffect-usestate</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/asynchronous-calls-in-react-useeffect-usestate</guid><category><![CDATA[APIs]]></category><category><![CDATA[React]]></category><category><![CDATA[ReactHooks]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Mon, 21 Feb 2022 22:43:20 GMT</pubDate><content:encoded><![CDATA[<p>How we do properly handle asyncronous call such retrieve data from some APIs?</p>
<p>Well let's keep it simple and assume that those data once retrieve are going to be used in few places so a useState() or few of them will be enough, so in following example is not used any Redux or other global state management.</p>
<p>So we would like to re-render our component once the asynchronous call is over.</p>
<p>Many would think about memoisation and so use useMemo() but unfortunately this would not be the best approach, actually even a bad one as even in React specifically mentions that <a target="_blank" href="https://reactjs.org/docs/hooks-reference.html#usememo">useMemo</a> should not be used to manage side effects like asynchronous API calls.</p>
<p>This is because triggering an async call is a <em>side effect,</em> so it should not be performed during the render phase - neither inside the main body of the component function, nor inside useMemo(...) which also happens during the render phase. Instead all side effects should be triggered inside useEffect.</p>
<p>We should instead you should use React's state that keeps the value of async calls returned and allow to trigger a re-render.</p>
<p>But there are some little adjustment that will even improve such approach, let's write some code and I will explain :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [result, setResult] = useState()

useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> active = <span class="hljs-literal">true</span>
  load()
  <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> { active = <span class="hljs-literal">false</span> }

  <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">load</span>(<span class="hljs-params"></span>) </span>{
    setResult(<span class="hljs-literal">undefined</span>) <span class="hljs-comment">// this is optional</span>
    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> someLongRunningApi(arg1, arg2)
    <span class="hljs-keyword">if</span> (!active) { <span class="hljs-keyword">return</span> }
    setResult(res)
  }
}, [arg1, arg2])
</code></pre>
<p>Here we call the async function inside useEffect.</p>
<p>Note that you cannot make the whole callback inside useEffect async( otherwise it will create a loop) - that's why instead we declare an async function load inside and call it without awaiting.</p>
<p>The effect will re-run once one of the args changes - this is what is needed in most cases.</p>
<p>So we can make sure to memoise args if in need to re-calculate them on render.</p>
<p>Doing setResult(undefined) is optional - and let in this way have <em>fresh</em> data at each render but one could simply need to keep the previous result on the screen until the next result is availabe. Or one might do something like setLoading(true) so the user knows what's going on.</p>
<p>Using <em>active</em> flag is important. Without it we are exposing ourself to a **race condition **waiting to happen: <strong>the second async function call may finish before the first one finishes:</strong></p>
<p>Those are what then will happens in a race condition:</p>
<p>start first call</p>
<p>start second call</p>
<p>second call finishes, setResult() happens</p>
<p>first call finishes, setResult() happens again, overwriting the correct result with a stale one</p>
<p>Our component ends up in an* inconsistent state*. We avoid that by using useEffect's cleanup function to reset the active flag:</p>
<p>set <em>active#1 = true</em>, start first call</p>
<p>arg changes, cleanup function is called, set <em>active#1 = false</em></p>
<p>set <em>active#2 = true</em>, start second call</p>
<p>second call finishes, *setResult() *happens</p>
<p>first call finishes, *setResult() *doesn't happen since <em>active#1 is false</em></p>
<p>This is one of the use case in which useEffect + useState( or in case of large application, a global state management) this useEffect is the best approach and actually the one to go for deal with side effects such APIs calls.</p>
]]></content:encoded></item><item><title><![CDATA[UseMemo vs. useEffect + useState]]></title><description><![CDATA[If you are learning hooks probably this question hasn't come across to you yet.
On the other hand I have seen even experienced developers and software engineers not aware of which hook use especially when it came with those that are quite similar and...]]></description><link>https://blog.allaroundjavascript.com/usememo-vs-useeffect-usestate</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/usememo-vs-useeffect-usestate</guid><category><![CDATA[ReactHooks]]></category><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Wed, 16 Feb 2022 18:23:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/cckf4TsHAuw/upload/v1645033237313/dwKNyj6Gn.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are learning hooks probably this question hasn't come across to you yet.</p>
<p>On the other hand I have seen even experienced developers and software engineers not aware of which hook use especially when it came with those that are quite similar and then they end up write always the same function / hooks because it seemed to them the other solutions are "useless"</p>
<p>But if you are more experience you know that for the right job you need the right tool, and thus applies also to use the right hook for the right use cases.</p>
<p>But let's start with code, that I will also recall in a sandbox for more details or for runtime examples.</p>
<p>For example let's consider a simple counter:</p>
<h2 id="heading-useeffect-amp-usestate">useEffect &amp; useState</h2>
<pre><code class="lang-javascript"><span class="hljs-comment">// we need also the useState hook in order to store the state of </span>
<span class="hljs-comment">// the counter variable(result) and increment it with the </span>
<span class="hljs-comment">// asyncronous function of the hook destructuring ( setResult )</span>

<span class="hljs-keyword">import</span> { expensiveCalculation } <span class="hljs-keyword">from</span> <span class="hljs-string">"foo"</span>; 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCalculate</span>(<span class="hljs-params">someNumber: number</span>): <span class="hljs-title">number</span> </span>{
  <span class="hljs-keyword">const</span> [result, setResult] = useState&lt;number&gt;(<span class="hljs-literal">null</span>);

  useEffect(<span class="hljs-function">() =&gt;</span> {
    setResult(expensiveCalculation(someNumber));
  }, [someNumber]);

  <span class="hljs-keyword">return</span> result;
}
</code></pre>
<h2 id="heading-usememo">useMemo</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> { expensiveCalculation } <span class="hljs-keyword">from</span> <span class="hljs-string">"foo"</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useCalculateWithMemo</span>(<span class="hljs-params">someNumber: number</span>): <span class="hljs-title">number</span> </span>{
    <span class="hljs-keyword">return</span> useMemo(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">return</span> expensiveCalculation(someNumber);
    }, [someNumber]);
};
</code></pre>
<p>Here the <a target="_blank" href="https://codesandbox.io/s/usememo-vs-useeffect-usestate-forked-fe7qm8?file=/src/index.tsx">sandox</a> to see it live.</p>
<p>They both calculate the count but if you have run the sandbox you can notice that the case with useEffect has a little text showing for few millisecond and the disappearing.</p>
<p>This is because Effect( let's call it in a kind of short way) does run just after the DOM is rendered by React, instead Memo its run immediately does in this case is way much faster.</p>
<p>Well as you may guess the answer is not, though I have seen some PR where engineers where basically using it everywhere.</p>
<h2 id="heading-some-analysis">Some analysis</h2>
<p>The useEffect and setState will cause extra renders on every change: the first render will "lag behind" with stale data and then it'll immediately queue up an additional render with the new data.</p>
<p>Lets suppose someNumber is initially 0:</p>
<p>The useMemo version immediately renders 1.</p>
<p>The useEffect version renders null, then after the component renders the effect runs, changes the state, and queues up a new render with 1. Then if we change someNumber to 2:</p>
<p>The useMemo runs :</p>
<ul>
<li>3 is rendered.</li>
</ul>
<p>The useEffect version runs,</p>
<ul>
<li>renders 1 again, then the effect triggers and the component reruns with the correct value of 3.</li>
</ul>
<blockquote>
<p>you should consider useMemo as pure optimization technique. Your program should continue to work correctly even if you replace useMemo with regular function call.</p>
</blockquote>
<h2 id="heading-recap">Recap</h2>
<h3 id="heading-1-time-when-function-called">1 . Time when function called.</h3>
<p>useEffect called after component has been rendered, so you can access DOM from it. For example, this is important if you want to access DOM elements via refs.</p>
<h3 id="heading-2-semantic-guarantees">2. Semantic guarantees.</h3>
<p>useEffect guarantees that it will not be fired if dependencies have not changed. useMemo does not give such guarantees.</p>
<p>As stated in the React documentation, you should consider useMemo as pure optimization technique. Your program should continue to work correctly even if you replace useMemo with regular function call.</p>
<p>useEffect + useState can be used to control updates. Even to break-up circular dependencies and prevent infinite update loops.</p>
<p>Also, why is not recommended to use always useMemo is that as the React API docs mention, useMemo doesn’t guarantee that the memoized function won’t be executed again if the dependencies don’t change because React may, in the future, discard cache to improve performance. So if the memoized function has side effects of some kind, it might be smarter to use a custom hook.</p>
<p>In terms of how often <strong>expensiveCalculation</strong> runs, the two have identical behavior, but the useEffect version is causing twice as much rendering which is bad for performance for other reasons.</p>
<p>Plus, the useMemo version is just cleaner and more readable, in this specific case.</p>
<p>It doesn't introduce unnecessary mutable state(this is the advantage that of course is a downside when you need to mutate state properly) and has fewer moving parts.</p>
<p>So you're better off just using useMemo here.</p>
<h1 id="heading-should-we-always-use-usememo-and-take-advantage-of-its-memoization-capability">Should we always use useMemo() and take advantage of its memoization capability?</h1>
<p>Let's try to answer, as stated in the <a target="_blank" href="https://reactjs.org/docs/hooks-reference.html#usememo">React docs</a></p>
<p>In general one should avoid to useMemo() when side effects are involved. At this point one is tempted to think that is an easy thing, but I can guarantee that in real case, is not, for example, what about retrieve some APIs, aren't they a side effect, and what use to handle them especially if they could take long and are update on regular basis, you may read <a target="_blank" href="https://blog.allaroundjavascript.com/asynchronous-calls-in-react-useeffect-usestate-ckzxabxlk013m03nv36s7ac6g">Asynchronous calls in React</a> to get a deep answer but in general, useMemo() is not at all the best option to handle them and anything that happens outside the component where it used, as indeed everything outside the Component is a side effect.</p>
<h2 id="heading-practical-examples-coming">Practical examples( coming...)</h2>
]]></content:encoded></item><item><title><![CDATA[Senior Developer share his experience on remote working that I should not have made public!]]></title><description><![CDATA[Hi Michele, first thank you for your time and to share your knowledge with us.
Since how many years you are working remotely and did the actual situation impacted the way you work or interact with colleagues? 
I would say that I have been working rem...]]></description><link>https://blog.allaroundjavascript.com/senior-developer-share-his-experience-on-remote-working-that-i-should-not-have-made-public</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/senior-developer-share-his-experience-on-remote-working-that-i-should-not-have-made-public</guid><category><![CDATA[remote]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Sun, 25 Oct 2020 10:20:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1603621131898/k4Elmug2k.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Hi Michele, first thank you for your time and to share your knowledge with us.
Since how many years you are working remotely and did the actual situation impacted the way you work or interact with colleagues? </strong></p>
<p>I would say that I have been working remotely forever. Except for the first few months after graduation, where I was going into my first (and only!) employer, since them I have worked remotely in various capacity, even 20 years ago when I was working remotely of an Italian Magazine. It the latest two years I have worked with an U.S. Company, Nimbella, and it was entirely a remote-only job.  From this point of view I has not been impacted at all by the pandemic.</p>
<p><strong>From your experience, Is Home Office same as Remote or they do are the same in the end?</strong></p>
<p>It depends. Not sure what is the difference. I fell all the differentiation about remote vs home vs smart a bit… pointless. You work the way it works for you and your employer or customer and that is all. I have for example a customer in Denmark but since some people are not good at communicating I have to sit down and use screen sharing to communicate with them. With others I can work asynchronously just sending my code in a shared repository.</p>
<p><strong>What are the tools that do you believe are mandatory to work remotely for a Software Engineer / Developer / Architect? </strong></p>
<p>Basically all the tools you normally use (and you should use!) to work are remote today! Of course you need a chat or a conferencing tool but you use those even with people are working in the same building, even in the same room and they are in front of you to avoid making noise.</p>
<p><strong>Why do you think there was necessary such a situation to push for remote working or why employer and company that basically produce intellectual services and digital, are so reluctant to remote work, still nowadays?</strong></p>
<p>For the simple reason that you have to measure results in a better way than looking at the time you spent in the office. Very frequently there are not methods in place at all. You are supposed to come in the office to work. If people do not do that, for what are you paying them? This is an additional burden on manager, that they are already supposed to do that, but frequently they do not.</p>
<p><strong>Let's be intellectual honest, Remote has not benefits, what are the Contra and how those can be mitigated? To clarify, I do refer to the fact that in the end some sort of personal contact or Human contact with colleagues is necessary, and definitely there is a lack of that, what is your experience in regarding this?</strong></p>
<p>Hmm this also depends on people. There are pe</p>
<p>ople that without some sort of pressure simply dose not do anything. And there are people, like me, that cannot stop doing something and if I have some result to achieve I keep working to reach it.</p>
<p><strong>Have you done Pair Programming remotely or introduced to a project remotely new developer?
In a particular situation is for your experience even feasible to introduce Jr developer on Board remotely?</strong></p>
<p>OMG.  I really hate pair programming. It has been such a torture to do in person. I cannot imagine how hard it can be remotely. I never did it except when we have to help someone to find a bug and … I do not recommend it to anyone. I feel is such a waste of time. Work should be always asynchronous except when you need to share results and meetings should last as little as possible. Either in presence or remote. Full stop.</p>
<p><strong>How do people work at Nimbella that you did not have found previously and how with some extends those strategies could be adopted by less digital companies, in order to let them be less reluctant and in the end become more efficient and productive?</strong></p>
<p>People in Nimbella works like any other company working on a software project that is not developed with people always coding in the same room. We discuss a bit on a chat room (slack) what to do, then everyone works and write his piece of code and commit to the main repo. Someone else checks the results and we always have a test suite. That is, mostly.</p>
<p><em>Do you think Companies that are open to hire remotely or allow more flexible time, attract more higher talents?</em></p>
<p>I believe that more or less we are to the point that if company needs to hire someone talented at all they need to hire him remotely, because today it is already possible for a talented person to set they rules in hiring and… remote work is so comfortable that I believe everyone now is asking to it. So they have to choose between those guy desperate enough (hence lacking of talent) to come in the office… or the good ones</p>
<p><strong>What are the tools or service that you do believe are a must to guarantee Project Management in a Remote way?</strong></p>
<p>I do not set rules. Basically all the tools that are fit to the job are ok. I have used many different tools and the only rule is that you need a tool. Whatever. </p>
]]></content:encoded></item><item><title><![CDATA[Smart Working via VS Code, VS Code Online and Github even if you don't have Admin credentials.]]></title><description><![CDATA[This article won't be much so related to Javascript in particular and could apply for any stack and any language.
It is about first step for work remotely, as a developer that has to work with a  Git Repository or exploring the way to work from a lap...]]></description><link>https://blog.allaroundjavascript.com/smart-working-via-vs-code-vs-code-online-and-github-even-if-you-dont-have-admin-credentials</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/smart-working-via-vs-code-vs-code-online-and-github-even-if-you-dont-have-admin-credentials</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[Visual Studio Code]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Wed, 11 Mar 2020 11:22:47 GMT</pubDate><content:encoded><![CDATA[<p>This article won&#39;t be much so related to Javascript in particular and could apply for any stack and any language.
It is about first step for work remotely, as a developer that has to work with a  Git Repository or exploring the way to work from a laptop that is not our 
 normal&#39;s one or the developer prefered one.</p>
<p>There are times indeed when one is forced to use a computer in which one has not admin privilege or even having those, there is not time to set or configure an entire Development Enviroment such an IDE, configured with all plugins, libraries etc. It could be also useful when is not advisable to run code locally because either the hardware is not enough for the task done by the code base, or because we are to a client doing other projects and we want separate things but as set a virtual Machine or a Docker container is not worth the time.</p>
<p>Nevertheless software development  never stop or sleep as can be done anytime and in any location especially nowadays with the &quot;Cloud&quot;. </p>
<p>So this post is the first of a series on remote tools and solution and how to set them.</p>
<p>Nervertheless this first, will cover basic steos on how connect a local computer with Windows 10 for which we have only a simple User but could be applied to any OS.</p>
<p>It meant that we can still install software under that user account and have enough space for do it.</p>
<p>The following of this will cover the amazing possibilities offered by   <a target='_blank' rel='noopener noreferrer'  href="https://docs.microsoft.com/en-us/visualstudio/online/overview/what-is-vsonline">Visual Studio Online</a>  and further I wil test and write about the <a target='_blank' rel='noopener noreferrer'  href="https://code.visualstudio.com/docs/remote/remote-overview"> Visual Studio Remote Development </a>.</p>
<p>Let&#39;s start, first install we have to install Visual Studio Code for  <a target='_blank' rel='noopener noreferrer'  href="https://code.visualstudio.com/Download">Windows </a> and  <a target='_blank' rel='noopener noreferrer'  href="https://git-scm.com/downloads">MINGW64</a>  that is the bash tool for Git on Windows and that use bash sintax.</p>
<p>Create an Azure account if you want use Visual Studio either locally or the Online version or later the Visual Studio Remote Development.</p>
<p>Once we have those, we need to decide with protocol to use, either SSH or HTTP(S), in order to connect, o our repositories(any).
Its said that these steps can be done in some Companies by the DevOps/ SRE Team but as a developer you maybe need to be &quot;adpating&quot; be a good learning process and also is about a specific Repository and as a special case where reach out those team won&#39;t be effient or in case they are busy.</p>
<p>I write in advance that the connection via tunneling is subject to  <a target='_blank' rel='noopener noreferrer'  href="https://stackoverflow.com/questions/50426912/git-clone-failed-to-begin-relaying-via-http">IT approval </a> and I went only for it in order to explor the possibilities in order to have a clear and reproducible steps in case needed and the tunnelling connection is allowed by IT policies.</p>
<p>In general the SSH is a better way for the developer, as once setted it up will not require to provide in the future Git Remote operation ( pull, push, ect) credentials.</p>
<p>Instead the HTTP way do not require any approval as long as one has access to internet with the user because the protocol it use is already trackable by default by the IT enterprise. Also for out goal to work to some code from anyway, will suffice.</p>
<p>First step is to clone the Github repository (but this apply to any Git remote provider, so also Gitlab e.g), usually via http is something like :</p>
<pre><code> git <span class="hljs-keyword">clone</span> https:<span class="hljs-comment">//github.com/User/YourRepo.git</span>
</code></pre><p>Then you run the command, but unfortunately you get something like :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1583921699372/MDctbQXjs.png" alt="443_connectionRefused.PNG"></p>
<p>This is highly happening because you are working behind an Enterpise proxy firewall.</p>
<p>To overcome it, and as we use HTTP protocol basically we need to tell Git how to use the same configuration that our browser use in order to let us reach outside websites.</p>
<p>You need to find your <strong>Proxy Server Name</strong>, usually this is under a file with the extention of <strong>.pac </strong> sometimes this easly to find from the broswer.</p>
<p>For example in Chrome it is under  Settings, then &quot;Open Proxy Settings&quot;( I have a German Computer and Account, but that is basically the translation), it will open a System Window where it show where the Proxy Script is.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1583922617081/FtljS_y7Y.png" alt="proxyScript.PNG"></p>
<p>I have of course removed mine for privacy reasons, but is under <strong> Script Address</strong></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1583922620921/y1rDEU4Si.png" alt="ProxScriptLocationt.PNG"></p>
<p>This file can be open with any editor, Notepad or Notepad++ , it could be a very long one, you can skip all the line and go to the probably last line where it say </p>
<pre><code><span class="hljs-attribute">PROXY</span> YourProxyAddress: Port
</code></pre><p>Take note of that address, and under your Windows Home User
( C:\Users\YourUser ), search for .gitconfig file, open it in an editor and you need to add under http tag(create it if is not there)</p>
<pre><code>[http]
       <span class="hljs-comment"># This is a comment, also add the sslverify, in order to not use any </span>
       <span class="hljs-comment"># certificate</span>
    sslverify = <span class="hljs-literal">false</span> 
    proxy = YourProxyAddress: Port
</code></pre><p>After these steps if we run again the clone command,  we will be succefull cloned our remote repository :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1583923896113/bdd47vGyb.png" alt="RepoSuccessCloned.PNG">.</p>
<p>This could have been achieved also by Git CLI withouth adding manually the proxy server address in .gitconfig, as explained  <a target='_blank' rel='noopener noreferrer'  href="https://stackoverflow.com/questions/128035/how-do-i-pull-from-a-git-repository-through-an-http-proxy/59282697#comment107242899_59282697">here</a> .</p>
<p>Or even better provide also the Git credential b CLI, as from  <a target='_blank' rel='noopener noreferrer'  href="https://stackoverflow.com/questions/18356502/github-failed-to-connect-to-github-443-windows-failed-to-connect-to-github/40478893#40478893">here</a>.</p>
<p>But in this way one could come to some issue, has happened to me because depending of the password some special caracthers for bash( as it is the Git CLI) need to be escaped such @ or !, personally I had some hard time doing that even I used the right encoding for those, moreover in this way Git store those into .gitconfig and  may be not advisable store them in a computer that you don&#39;t use regulary or you are not the Admin Rights.</p>
<p>The first approach let you then provide your credential via CLI and also in Visual Sudio code via Terminal or Pallet if using a plugin, for the specific task(pull, push etc).</p>
<p>At this point you could be setted, but only if you are satisfied with the default account for Git that will be those of your User under you login in the machine.</p>
<p>In order to customize those, you need to tell git which account to use, the run the following in the  [commands]  (https://stackoverflow.com/questions/22844806/how-to-change-my-git-username-in-terminal) :</p>
<pre><code>git config --<span class="hljs-built_in">global</span> user.email <span class="hljs-string">"you@example.com"</span>
git config --<span class="hljs-built_in">global</span> user.name <span class="hljs-string">"Your Name"</span>
git config --<span class="hljs-built_in">global</span> user.password <span class="hljs-string">"your password"</span>
</code></pre><p>At this point you are all set as well with Visual Studio Code, if the Azure account is created( but will work with any CLOUD Service), for any Git task that can be done via HTTP.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1583925654448/ppa_knKEe.png" alt="VSCworking.PNG"></p>
<p>As the post was longer as planned I will be a II Part regarding the SSH protocol and following regarding specifically VS Code Online and Visual Studio Remote development</p>
]]></content:encoded></item><item><title><![CDATA[Arrow vs function expression in React.
When use the arrow and when use expression way]]></title><description><![CDATA[There are so many answers around this topic, because is about to use new ES6 feature in a recent framework such React that has the use of  Arrow functions  still as  proposal  way. 
So I decided to investigate the topic further to clarify it to mysel...]]></description><link>https://blog.allaroundjavascript.com/arrow-vs-function-expression-in-react-when-use-the-arrow-and-when-use-expression-way</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/arrow-vs-function-expression-in-react-when-use-the-arrow-and-when-use-expression-way</guid><category><![CDATA[React]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Mon, 02 Mar 2020 14:43:57 GMT</pubDate><content:encoded><![CDATA[<p>There are so many answers around this topic, because is about to use new ES6 feature in a recent framework such React that has the use of  <a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">Arrow functions</a>  still as  <a target='_blank' rel='noopener noreferrer'  href="https://reactjs.org/docs/faq-functions.html">proposal</a>  way. </p>
<p>So I decided to investigate the topic further to clarify it to myself and to the readers bringing as much as possible updated example.</p>
<p>Let&#39;s start from the  <a target='_blank' rel='noopener noreferrer'  href="https://reactjs.org/docs/faq-functions.html">docs</a> that recommend the use of function expression in this way:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span> <span class="hljs-title">extends</span> <span class="hljs-title">Component</span> </span>{
  <span class="hljs-keyword">constructor</span>(props) {
    <span class="hljs-keyword">super</span>(props);
    <span class="hljs-keyword">this</span>.handleClick = <span class="hljs-keyword">this</span>.handleClick.bind(<span class="hljs-keyword">this</span>);
  }
  handleClick() {
    console.log(<span class="hljs-string">'Click happened'</span>);
  }
  render() {
    <span class="hljs-keyword">return</span> &lt;button onClick={<span class="hljs-keyword">this</span>.handleClick}&gt;Click Me&lt;/button&gt;;
  }
}
</code></pre><p>So with a class based Component aka a component that has to manage the state, then when we want do something with the data, this is still the way to go because it was like this from the beginning but also for choice to bind the <strong>this</strong> to the class constructor.</p>
<p>The same with arrow function is still on <strong>Stage 3 Proposal</strong>, but would be like:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Foo</span> <span class="hljs-title">extends</span> <span class="hljs-title">Component</span> </span>{
  handleClick() {
    console.log(<span class="hljs-string">'Click happened'</span>);
  }
  render() {
    <span class="hljs-keyword">return</span> &lt;button onClick={<span class="hljs-keyword">this</span>.handleClick.bind(<span class="hljs-keyword">this</span>)}&gt;Click Me&lt;/button&gt;;
  }
}
</code></pre><p>So when which one is the preferred one?</p>
<p>Well it depends, as usual.</p>
<p>First if depends if we have Functional Components that do not change the state, in this case the arrow function enable us to avoid to use <strong>bind</strong> as in arrow function the <strong> <a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">this</a> </strong> has a context lexical scope, meaning its value is the one outside of the arrow function environment, as arrow functions do not have their own <strong>this</strong>, so we are sure of its value or we want that it is exactly the outside&#39;s function one!</p>
<p>This is the advantage, on the contrary there is a disadvantage, each arrow function does create a new object instance once is called, and so in React case each time the Component is rendered.</p>
<p>Let&#39;s see in code:</p>
<pre><code>
<span class="hljs-keyword">import</span> React from <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM from <span class="hljs-string">'react-dom'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Button</span> <span class="hljs-title">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      &lt;button
        onClick={() =&gt; <span class="hljs-keyword">this</span>.setState({ backgroundColor: <span class="hljs-string">'red'</span> })}
        style={<span class="hljs-keyword">this</span>.state}&gt;
        Set background to red
      &lt;/button&gt;
    )
  }
}

ReactDOM.render(
  &lt;Button /&gt;,
  document.getElementById(<span class="hljs-string">'root'</span>)
)
</code></pre><p>In this particular case actually the arrow function way is the only way to avoid a bag regarding <strong>this</strong> that its value is dynamically set.</p>
<p>As indeed in this case </p>
<pre><code><span class="hljs-keyword">import</span> React from <span class="hljs-string">'react'</span>
<span class="hljs-keyword">import</span> ReactDOM from <span class="hljs-string">'react-dom'</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BrokenButton</span> <span class="hljs-title">extends</span> <span class="hljs-title">Component</span> </span>{
  render() {
    <span class="hljs-keyword">return</span> (
      &lt;button onClick={<span class="hljs-keyword">this</span>.handleClick} style={<span class="hljs-keyword">this</span>.state}&gt;
        Set background to red
      &lt;/button&gt;
    )
  }

  handleClick() {
    <span class="hljs-keyword">this</span>.setState({ backgroundColor: <span class="hljs-string">'red'</span> })
  }
}

ReactDOM.render(
  &lt;BrokenButton /&gt;,
  document.getElementById(<span class="hljs-string">'root'</span>)
)
</code></pre><p>The color won&#39;t change at least we had bind the this as above, because the handleClick method isn’t a method at all! JavaScript doesn’t actually have methods. It only has functions. And the value of this inside those functions has some funny rules. In this case, those rules cause this to be null.</p>
<p>The thing to watch out with use arrow function in rendering part of a React component is that every time a new object is created and so new reference is created and this is true also with arrow function.</p>
<p>So The main reason for taking the above approach in which we use in the render an arrow function is if you want to pass parameters to the handler beside the native event that get passed, meaning you want to pass a parameter upwards.</p>
<p>As mentioned, this will create a new function instance on each render.
But there is a better approach in this case.</p>
<p>A better approach would be to create component composition.
You can create a child component that wraps the relevant markup, will have it&#39;s own handler and will get both the data and handler as props from the parent.</p>
<p>The child component will then invoke the handler that it got from the parent and will pass the data as a parameter. </p>
<p>Writing regarding this subject where much useful many relevant questions and answer on Stackoverflow such, and I plan to expand the topic with more example </p>
<p>https://stackoverflow.com/questions/52031147/react-which-is-recommended-arrow-or-normal-function</p>
<p>https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react</p>
<p>https://stackoverflow.com/questions/45053622/how-to-avoid-bind-or-inline-arrow-functions-inside-render-method/45053753#45053753</p>
<p>https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable</p>
<p>Also those other articles:</p>
<p>https://frontarm.com/james-k-nelson/when-to-use-arrow-functions/</p>
<p>https://medium.com/@oleg008/arrow-functions-in-react-f782d11460b4</p>
<p>https://www.freecodecamp.org/news/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56/</p>
]]></content:encoded></item><item><title><![CDATA[Webpack 4.x : The essential loaders and plugins you need to have installed]]></title><description><![CDATA[This article is directly derived from Colt Steele video tutorial
This will be an introduction list on the essential loaders and plugins one need to have installed in order to work with styles as CSS, SASS files and files in general such for example i...]]></description><link>https://blog.allaroundjavascript.com/webpack-4x-the-essential-loaders-and-plugins-you-need-to-have-installed</link><guid isPermaLink="true">https://blog.allaroundjavascript.com/webpack-4x-the-essential-loaders-and-plugins-you-need-to-have-installed</guid><category><![CDATA[plugins]]></category><category><![CDATA[webpack]]></category><dc:creator><![CDATA[Carmine Tambascia]]></dc:creator><pubDate>Wed, 29 Jan 2020 13:05:21 GMT</pubDate><content:encoded><![CDATA[<p>This article is directly derived from Colt Steele video <a target="_blank" href="https://www.youtube.com/playlist?list=PLblA84xge2_zwxh3XJqy6UVxS60YdusY8">tutorial</a></p>
<p>This will be an introduction list on the essential loaders and plugins one need to have installed in order to work with styles as CSS, SASS files and files in general such for example images.</p>
<p>The list will not be complete and will been update in the future based on the package plugins updates / deprecation and readers feedback.</p>
<p>So then let's start.</p>
<p>As a recup let's remember what <a target="_blank" href="https://webpack.js.org/concepts/#loaders">loaders</a> are:</p>
<blockquote>
<p>Loaders allow webpack to process other types of files and convert them into valid modules that can be consumed by your application and added to the dependency graph. They are transformations that are applied to the source code of a module. They allow you to pre-process files as you import or “load” them. Thus, loaders are kind of like “tasks” in other build tools and provide a powerful way to handle front-end build steps. Loaders can transform files from a different language (like TypeScript) to JavaScript or load inline images as data URLs. Loaders even allow you to do things like import CSS files directly from your JavaScript modules!</p>
</blockquote>
<p>So now that we understand why this one should be the first loader to consider to install in your frontend application part, if you want webpack to be able to include .css file into the bundler file then you need this two loaders :</p>
<p><strong>css-loader</strong> and <strong>style-loader</strong></p>
<p>The first interprets @import and url() like import/require() and will resolve them. Basically turns .CSS into Commonjs.</p>
<p>This is how you setup it into the webpack file:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rules</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.css$/i</span>,
        use: [<span class="hljs-string">'style-loader'</span>, <span class="hljs-string">'css-loader'</span>],
      },
    ],
  },
};

So then we then will have:

 use: [<span class="hljs-string">'style-loader'</span>, <span class="hljs-string">'css-loader'</span>, ],
</code></pre>
<p>Here we need to note that webpack does start to "use" first the last-right element of the use array, so in this case the css-loader loader that let webpack include into the bundler css code as Javascript one.</p>
<p>Of course we need to import the .css file into the entry point where the loader will be looking for the .css file.</p>
<p>The style-loader instead inject CSS into the DOM.</p>
<p>The next one is essential only if you want to use .scss instead of .css files. They can be used both but for now we show the SASS one only used.</p>
<p>**sass.loader ** --&gt; Turns scss into standard css</p>
<p>that import in the entry point the sass.file or the second part vendors such bootstrap.</p>
<p>Now let's move to plugins that are from the official webpack <a target="_blank" href="https://webpack.js.org/concepts/plugins/">docs</a> , defined as such:</p>
<blockquote>
<p>Plugins are the backbone of webpack. webpack itself is built on the same plugin system that you use in your webpack configuration! They also serve the purpose of doing anything else that a loader cannot do. You can find an extensive list <a target="_blank" href="https://webpack.js.org/plugins/html-webpack-plugin/">here</a>.</p>
</blockquote>
<p>The one you probably are going to use if you want to make your life easier, is the</p>
<p><strong>HtmlWebpackPlugin</strong> --&gt; simplifies creation of HTML files to serve your webpack bundles.</p>
<p>This is especially useful for webpack bundles that include a hash in the filename which changes every compilation. You can either let the plugin generate an HTML file for you, supply your own template using lodash templates, or use your own loader.</p>
<p>This will indeed make sure that if you do use cache busting feature as in filename:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">const</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = {
 <span class="hljs-attr">mode</span>: <span class="hljs-string">"production"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].[contentHash].bundle.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  },
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rules</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.css$/i</span>,
        use: [<span class="hljs-string">'style-loader'</span>, <span class="hljs-string">'css-loader'</span>],
      },
    ],
  },
};
</code></pre>
<p>that is the ability of <strong>webpack</strong> to generate a file name of the bundler file based on an Hash function( e.g the md5 algorithm ), so a filename that change based on the file content, <strong>html-webpack-plugin</strong> will include every time the new filename as the source of the bundle cleaning old one, still keeping the feature of <strong>cache busting</strong>.</p>
<p>So this is how this plugin should be used once have installed it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">'html-webpack-plugin'</span>);
<span class="hljs-keyword">var</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">'path'</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: <span class="hljs-string">'index.js'</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">'./dist'</span>),
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].[contentHash].bundle.js"</span>,
  },
  <span class="hljs-attr">plugins</span>: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin()]
};
</code></pre>
<p>With this basic setting it will generate a <strong>dist/index.html</strong> containing the following:</p>
<pre><code class="lang-javascript">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>webpack App<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"index_bundle.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<p>At this point the plugin won't know which template use, so we need still to tell it either to use a plan template.html or a library or connect to a template system.</p>
<p>Going for the simply solution, providing a template.html file as an object:</p>
<pre><code class="lang-javascript"> plugins: [<span class="hljs-keyword">new</span> HtmlWebpackPlugin({
 <span class="hljs-attr">template</span>: <span class="hljs-string">'yourTemplatePath/template.html'</span>
})]
</code></pre>
<p>Our template will be used to fill the index.html generated by the plugin with the link to the last bundler with the Hash number concatenated as name.</p>
<p>The next plugin is one that is quite necessary for any project that involve a Development environment and a Production one( well theoretically any).</p>
<p>We will assume then to have 3 different webpack files:</p>
<p>**webpack.common.js **--&gt; containing the setting in common to both production and development</p>
<p>and of course** webpack.dev.js** and a **webpack.prod.js **</p>
<p>Like the following:</p>
<p><strong>webpack.common.js :</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">var</span> HtmlWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"html-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">entry</span>: {
    <span class="hljs-attr">main</span>: <span class="hljs-string">"./src/index.js"</span>,
  },
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rules</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.html$/</span>,
        use: [<span class="hljs-string">"html-loader"</span>]
      },
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.(svg|png|jpg|gif)$/</span>,
        use: {
          <span class="hljs-attr">loader</span>: <span class="hljs-string">"file-loader"</span>,
          <span class="hljs-attr">options</span>: {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"[name].[hash].[ext]"</span>,
            <span class="hljs-attr">outputPath</span>: <span class="hljs-string">"imgs"</span>
          }
        }
      }
    ]
  }
};
</code></pre>
<p>Meanwhile the <strong>webpack.dev.js</strong> will become simpler as we don't need the template plugin as already in <strong>web.common.js</strong>, so the** webpack.dev.js** will become:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">const</span> common = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./webpack.common"</span>);

<span class="hljs-built_in">module</span>.exports = {
  <span class="hljs-attr">mode</span>: <span class="hljs-string">"development"</span>,
  <span class="hljs-attr">output</span>: {
    <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].bundle.js"</span>,
    <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
  }, 
};
</code></pre>
<p>similarly the webpack.prod.js that will keep the hash functionality.</p>
<p>We then will include in both the prod and the dev file the common one, but how we can use it?</p>
<p>Here when it come into play the merge plugin, that once installed and required need to be used in this way in both the <strong>dev</strong> and **prod **version of webpack:</p>
<p><strong>webpakc.dev.js</strong></p>
<pre><code class="lang-javascript">
<span class="hljs-keyword">const</span> path = <span class="hljs-built_in">require</span>(<span class="hljs-string">"path"</span>);
<span class="hljs-keyword">const</span> common = <span class="hljs-built_in">require</span>(<span class="hljs-string">"./webpack.common"</span>);
<span class="hljs-keyword">const</span> merge = <span class="hljs-built_in">require</span>(<span class="hljs-string">"webpack-merge"</span>);

<span class="hljs-built_in">module</span>.exports = merge(common, {
  <span class="hljs-attr">mode</span>: <span class="hljs-string">"development"</span>,
    <span class="hljs-attr">output</span>: {
       <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].bundle.js"</span>,
       <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
    },

 });
</code></pre>
<p>Of course we will have different package.json script to run before the webpack.de.js version and then another that will use the webpack.prod.js</p>
<p>This of course require an extra work but enable more flexbility once our application process development start to involve more aspect for development and production but with a large base from both.</p>
<p>For example in development we don't need to build our bundle file everytime so the 2 process could use separate server.</p>
<p>In the webpack.dev.js we can integrate a development server, simply installing it:</p>
<pre><code class="lang-javascript">npm install webpack-dev-server
</code></pre>
<p>That will us enable to be called directly from a package.json script as such:</p>
<pre><code class="lang-javascript"><span class="hljs-string">"start"</span>: <span class="hljs-string">"webpack-dev-server config webpack.dev.js --open"</span>
</code></pre>
<p>Where the open flag let also open a local instance at the default address(localhost:8080).</p>
<p>The advantage f the web-dev-server is also that if does not exist a dist folder where the bundler should be put, it does it create in memory and update it at every change.</p>
<p>At one point we will need also to load some image and this can be manage of course via webpack without put hard coded link.</p>
<p>We will assume to have and image folder under the root/src where image will be uploaded during development.</p>
<p>Unfortunately webpack will not know where this folder is so we need some help and that when it comes in the <a target="_blank" href="https://github.com/webpack-contrib/html-loader">html-loader</a> :</p>
<pre><code class="lang-javascript">HTML Loader --&gt; Exports HTML <span class="hljs-keyword">as</span> string. HTML is minimized when the compiler demands.
</code></pre>
<p>Here how we should use after have installed:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">module</span>: {
     <span class="hljs-attr">rules</span>: [
       {
          <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.html$/</span>,
          use: [<span class="hljs-string">"html-loader"</span>]
        },
     ],
},
</code></pre>
<p>Unfortunately this plugin will push the image into the js file produced from webpack but we would get an error if not handle image inside webpack.</p>
<p>Here when it comes the <strong>File-loader</strong> loader that does create dinamically the src for image inside the bundler produced by webpack.</p>
<p>This is how to use it in your webpack.common.js</p>
<pre><code class="lang-javascript">    {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.(svg|png|jpg|gif)$/</span>,
        use: {
          <span class="hljs-attr">loader</span>: <span class="hljs-string">"file-loader"</span>,
          <span class="hljs-attr">options</span>: {
            <span class="hljs-attr">name</span>: <span class="hljs-string">"[name].[hash].[ext]"</span>,
            <span class="hljs-attr">outputPath</span>: <span class="hljs-string">"images"</span>
          }
        }
      }
</code></pre>
<p>So file-loader will manage to handler the image imported by html-loader and provide an hash name in the above way.</p>
<p>Indeed in the src/index.html we will have :</p>
<pre><code class="lang-javascript">  &lt;img src=<span class="hljs-string">"images/YourImageName.hashnumber.ext"</span>&gt;
</code></pre>
<p>Of course simply add more image extension if you need to support them.</p>
<p>Another plugin that should not be left out is the ** clean-webpack**, as from github <a target="_blank" href="https://github.com/johnagan/clean-webpack-plugin">repo</a> :</p>
<blockquote>
<p>remove/clean your build folder</p>
</blockquote>
<p>As we had split the webpack between commom, dev and prod as we don't use the HtmlwebpackPlugin in production every time we build we end up with many bundlers file, but with the above plugin it cleans the output folder and let use only the last bundler.</p>
<p>We use it this way:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> CleanWebpackPlugin = <span class="hljs-built_in">require</span>(<span class="hljs-string">"clean-webpack-plugin"</span>);

<span class="hljs-built_in">module</span>.exports = merge(common, {
    <span class="hljs-attr">mode</span>: <span class="hljs-string">"production"</span>,
    <span class="hljs-attr">output</span>: {
         <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].[contentHash].bundle.js"</span>,
         <span class="hljs-attr">path</span>: path.resolve(__dirname, <span class="hljs-string">"dist"</span>)
    },
    <span class="hljs-attr">plugins</span>: [
         <span class="hljs-keyword">new</span> CleanWebpackPlugin()
    ]
});
</code></pre>
<p>We could have the necessity to produce differents bundles based on different libraries( JQuery, React etc).</p>
<p>In this case first we need to change the entry point configuration in the webpack.common.js like:</p>
<pre><code class="lang-javascript"> entry: {
   <span class="hljs-attr">main</span>: <span class="hljs-string">"yourPathToindex.js"</span>,
   <span class="hljs-attr">vendor</span>: <span class="hljs-string">"yourPathtoReactenty.js"</span>
},
</code></pre>
<p>The last plugin we are going to list is the one that let improve our user experience.</p>
<p>Indeed having the bundle in the end of the file means that the CSS file are injected together with javascript then only once everything is loaded.</p>
<p>Unfortunately in this way the browser will flag for some milliseconds an error saying that cannot find those styles.</p>
<p>This is when it comes in hand the <strong>mini-css-extract-plugin</strong> that we will use only in production as load css require time andin development face we don't care that much regarding the flag warning.</p>
<p><strong>webpack.prod.js</strong></p>
<pre><code class="lang-javascript">  plugins: [
    <span class="hljs-keyword">new</span> MiniCssExtractPlugin({ <span class="hljs-attr">filename</span>: <span class="hljs-string">"[name].[contentHash].css"</span> }),
    <span class="hljs-keyword">new</span> CleanWebpackPlugin()
  ],
  <span class="hljs-attr">module</span>: {
    <span class="hljs-attr">rules</span>: [
      {
        <span class="hljs-attr">test</span>: <span class="hljs-regexp">/\.scss$/</span>,
        use: [
          MiniCssExtractPlugin.loader, <span class="hljs-comment">//3. Extract css into files</span>
          <span class="hljs-string">"css-loader"</span>, <span class="hljs-comment">//2. Turns css into commonjs</span>
          <span class="hljs-string">"sass-loader"</span> <span class="hljs-comment">//1. Turns sass into css</span>
        ]
      }
    ]
  }
</code></pre>
<p>What we will get will be a cssfilenameHashnumber.css that will be not minified so still not the best in term of performance.</p>
<p>In order to achieve this performance improvement we can use the <a target="_blank" href="https://github.com/NMFR/optimize-css-assets-webpack-plugin">optimize-css-assets-webpack-plugin</a>.</p>
<p>It can be used as it says in official <a target="_blank" href="https://github.com/NMFR/optimize-css-assets-webpack-plugin">repo</a> or in a better way create an apropriate object</p>
<pre><code class="lang-javascript">optimization: {
    <span class="hljs-attr">minimizer</span>: [
      <span class="hljs-keyword">new</span> OptimizeCssAssetsPlugin(),
      <span class="hljs-keyword">new</span> TerserPlugin(),
      <span class="hljs-keyword">new</span> HtmlWebpackPlugin({
        <span class="hljs-attr">template</span>: <span class="hljs-string">"./src/template.html"</span>,
        <span class="hljs-attr">minify</span>: {
          <span class="hljs-attr">removeAttributeQuotes</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">collapseWhitespace</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">removeComments</span>: <span class="hljs-literal">true</span>
        }
      })
    ]
  },
</code></pre>
<p>We need <strong>new TerserPlugin()</strong> because OptimizeCssAssetsPlugin override the minifying feature of webpack so it does not then proceed to minify all files but only CSS.</p>
<p>This was a quite extensive list based on the above tutorial but will eventually be added more plugin list and be update depending also on readers feedbacks</p>
]]></content:encoded></item></channel></rss>