<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Avraham Hamu on Medium]]></title>
        <description><![CDATA[Stories by Avraham Hamu on Medium]]></description>
        <link>https://medium.com/@avrahamhamu?source=rss-afcba5bab133------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LqOy6WfqZnl9_rIDb6LAbw.jpeg</url>
            <title>Stories by Avraham Hamu on Medium</title>
            <link>https://medium.com/@avrahamhamu?source=rss-afcba5bab133------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 05:56:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@avrahamhamu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Work Around Next.js]]></title>
            <link>https://medium.com/att-israel/how-to-work-around-next-js-a9480677f9be?source=rss-afcba5bab133------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9480677f9be</guid>
            <category><![CDATA[styled-components]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Avraham Hamu]]></dc:creator>
            <pubDate>Tue, 24 Dec 2024 13:55:14 GMT</pubDate>
            <atom:updated>2024-12-24T14:39:41.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Work Around Next.js Limitation of Importing CSS Outside the Main File Using Styled-Components?</h3><blockquote><strong>Global CSS cannot be imported from files other than your Custom &lt;App&gt;. Please move all global CSS imports to pages/_app.js.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ViKSP687oH-kwqS_" /><figcaption>Photo by <a href="https://unsplash.com/@dillonwinspear?utm_source=medium&amp;utm_medium=referral">Dillon Winspear</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’ve encountered the error “<strong>Global CSS cannot be imported from files other than your Custom &lt;App&gt;. Please move all global CSS imports to pages/_app.js</strong>”, while using Next.js and feel frustrated, follow the instructions until the end.</p><p>For this article, I’ll use a real-life example with the library <em>react-international-phone</em>, but the principle is the same for any third-party library.</p><p>In a recent project, I wanted to add the library <a href="https://react-international-phone.vercel.app/">react-international-phone</a> library as part of an internal npm module. The main application is developed with Next.js, and all submodules are packaged into different npm modules.</p><p>This approach guarantees a good separation of concerns, as each module is developed by a different team.</p><p>I use <a href="https://styled-components.com/">styled-components</a> 💅🏻 in my project, which makes things more complicated to handle. If you work without styled-components it could be simpler for you.</p><h3>The Problem</h3><p>I then started to add this new library into the module where I work on. It was pretty straight forward, as explained in the documentation:</p><pre>import { useState } from &#39;react&#39;;<br>import { PhoneInput } from &#39;react-international-phone&#39;;<br>import &#39;react-international-phone/style.css&#39;;<br><br>const InputPhoneNumber = (): ReactElement =&gt; {<br>  const [phone, setPhone] = useState(&#39;&#39;);<br><br>  return (<br>    &lt;PhoneInputWrapperSC&gt;<br>      &lt;PhoneInput<br>        defaultCountry=&quot;ua&quot;<br>        value={phone}<br>        onChange={(phone) =&gt; setPhone(phone)}<br>      /&gt;<br>    &lt;/PhoneInputWrapperSC&gt;<br>  );<br>};<br><br>export const PhoneInputWrapperSC = styled.div`<br>  display: flex;<br>  justify-content: space-between;<br>  align-items: center;<br>  width: &#39;100%&#39;;<br>`;</pre><p>It is specifically mentioned in the documentation :</p><p><strong><em>“Don’t forget to import default styles when using UI components”</em></strong></p><pre>import &#39;react-international-phone/style.css&#39;;</pre><p>Guess where do you have to import this global css?</p><p>Yes, in the main App.tsx file 🧐. This a Next.js restriction and there is no other way to <a href="https://nextjs.org/learn-pages-router/basics/assets-metadata-css/global-styles">add global css</a>.</p><blockquote>In Next.js, you can add <a href="https://nextjs.org/docs/basic-features/built-in-css-support#adding-a-global-stylesheet">global CSS</a> files by importing them from <a href="https://nextjs.org/docs/advanced-features/custom-app">pages/_app.js</a>. You <strong>can’t</strong> import global CSS anywhere else.</blockquote><p>My previous snippet can’t work correctly, since it’s not the main Next.js app file. Adding “import ‘react-international-phone/style.css’;” directly into the main Next.js app file is also not a possible solution, as I don’t have permission to modify this file ⛔️.</p><h3>The Solution</h3><pre>// file name: InputPhoneNumber.tsx<br>import React from &#39;react&#39;;<br>import { PhoneInput} from &#39;react-international-phone&#39;;<br>import { GlobalStylesSC } from &#39;./GlobalCss&#39;;<br>import { PhoneInputWrapperSC } from &#39;./InputPhoneNumber.styles&#39;;<br><br>export const InputPhoneNumber = (props): ReactElement =&gt; {<br>const [phone, setPhone] = useState(&#39;&#39;);<br>  return (<br>    &lt;PhoneInputWrapperSC&gt;<br>      &lt;GlobalStylesSC /&gt; &lt;&lt;&lt;&lt;***** ADD THE STYLED COMPONENT HERE<br>      &lt;PhoneInput<br>        defaultCountry=&quot;ua&quot;<br>        value={phone}<br>        onChange={(phone) =&gt; setPhone(phone)}<br>      /&gt;<br>    &lt;/PhoneInputWrapperSC&gt;<br>  );<br>};</pre><p>As you can see, I’ve added a styled-components <em>&lt;GlobalStylesSC/&gt;</em> in my code to include the global styles file. In the next section, we’ll explore step-by-step how I did this.</p><h3>How to make it work</h3><ul><li>First, I created the <em>GlobalStylesSC </em>component<em>, </em>which serves as a placeholder. The third-party global css file is injected inside this component.</li></ul><pre>// file name: GlobalCss.tsx<br>import { createGlobalStyle } from &#39;styled-components&#39;;<br><br>const externalLibStyles = `react-international-phone-css-place-holder`;<br><br>export const GlobalStylesSC = createGlobalStyle`<br>  ${externalLibStyles}<br>`;</pre><ul><li>The second step is to create a script capable of searching for the third-party global css file that we want and copying it into our placeholder component. The reason I use a script instead of doing it manually is to maintain the ability to upgrade my third-party library. If I had manually copied the global css into my placeholder component, I would need to do it again whenever upgrading my third-party library. By automating this stage with a script, it becomes transparent for the user.</li><li>The script search in node_modules the for file ‘<em>react-international-phone/dist/index.css</em>’ (our global css file)</li><li>It then copies this file into the placeholder ‘<em>react-international-phone-css-place-holder’ </em>from our Global css styled component.</li></ul><pre>// file name: replaceCssPlaceHolder.js<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br><br>const TARGET_FILE_TO_EDIT = &#39;./src/components/InputPhoneNumber/GlobalCss.tsx&#39;;<br><br>const findNodeModulesDir = (startDir) =&gt; {<br>  let currentDir = startDir;<br>  /* eslint-disable no-constant-condition */<br>  while (true) {<br>    const packageDir = path.join(currentDir, &#39;node_modules&#39;, &#39;react-international-phone&#39;);<br>    if (fs.existsSync(packageDir)) {<br>      return path.dirname(packageDir);<br>    }<br>    // Check if reached the root directory<br>    if (path.dirname(currentDir) === currentDir) {<br>      return null; // Package not found<br>    }<br>    currentDir = path.dirname(currentDir); // Move up the directory tree<br>  }<br>};<br><br>// Find the node_modules directory containing the &#39;react-international-phone&#39; package<br>const nodeModulesDir = findNodeModulesDir(__dirname);<br><br>if (!nodeModulesDir) {<br>  console.error(&#39;Unable to locate node_modules directory containing the package.&#39;);<br>  process.exit(1);<br>}<br><br>// Construct the path to the CSS file relative to the node_modules directory<br>const cssFilePath = path.join(nodeModulesDir, &#39;react-international-phone/dist&#39;, &#39;index.css&#39;);<br><br>if (!fs.existsSync(cssFilePath)) {<br>  console.error(&#39;CSS file not found.&#39;);<br>  process.exit(1);<br>}<br><br>// Read the content of the CSS file<br>const cssContent = fs.readFileSync(cssFilePath, &#39;utf8&#39;);<br><br>// Read the content of GlobalCss.tsx<br>let globalCssContent = fs.readFileSync(TARGET_FILE_TO_EDIT, &#39;utf8&#39;);<br><br>// Replace the placeholder with the CSS content<br>globalCssContent = globalCssContent.replace(<br>  /react-international-phone-css-place-holder/g,<br>  cssContent<br>);<br><br>// Write the updated content back to GlobalCss.tsx<br>fs.writeFileSync(TARGET_FILE_TO_EDIT, globalCssContent);<br><br>console.log(&#39;CSS placeholder replaced successfully.&#39;);</pre><ul><li>I run this script during the build stage from my package.json file. I simply added a line into the scripts section in package.json</li></ul><pre>// file name: package.json<br>&quot;build:css&quot;: &quot;node ./scripts/replaceCssPlaceHolder&quot;,</pre><p>The result works perfectly, the file GlobalCss.tsx looks like this:</p><pre>import { createGlobalStyle } from &#39;styled-components&#39;;<br><br>const externalLibStyles = `.react-international-phone-country-selector{position:relative}.react-international-phone-country-selector-button{display:flex;height:var(--react-international-phone-height, 36px);box-sizing:border-box;align-items:center;justify-content:center;padding:0;border:1px solid var(--react-international-phone-country-selector-border-color, var(--react-international-phone-border-color, gainsboro));margin:0;appearance:button;-webkit-appearance:button;background-color:var(--react-international-phone-country-selector-background-color, var(--react-international-phone-background-color, white));cursor:pointer;text-transform:none;user-select:none}.react-international-phone-country-selector-button:hover{background-color:var(--react-international-phone-country-selector-background-color-hover, whitesmoke)}.react-international-phone-country-selector-button--hide-dropdown{cursor:auto}.react-international-phone-country-selector-button--hide-dropdown:hover{background-color:transparent}.react-international-phone-country-selector-button__button-content{display:flex;align-items:center;justify-content:center}.react-international-phone-country-selector-button__flag-emoji{margin:0 4px}.react-international-phone-country-selector-button__flag-emoji--disabled{opacity:.75}.react-international-phone-country-selector-button__dropdown-arrow{border-top:var(--react-international-phone-country-selector-arrow-size, 4px) solid var(--react-international-phone-country-selector-arrow-color, #777);border-right:var(--react-international-phone-country-selector-arrow-size, 4px) solid transparent;border-left:var(--react-international-phone-country-selector-arrow-size, 4px) solid transparent;margin-right:4px;transition:all .1s ease-out}.react-international-phone-country-selector-button__dropdown-arrow--active{transform:rotateX(180deg)}.react-international-phone-country-selector-button__dropdown-arrow--disabled{border-top-color:var(--react-international-phone-disabled-country-selector-arrow-color, #999)}.react-international-phone-country-selector-button--disabled{background-color:var(--react-international-phone-disabled-country-selector-background-color, var(--react-international-phone-disabled-background-color, whitesmoke));cursor:auto}.react-international-phone-country-selector-button--disabled:hover{background-color:var(--react-international-phone-disabled-country-selector-background-color, var(--react-international-phone-disabled-background-color, whitesmoke))}.react-international-phone-flag-emoji{width:var(--react-international-phone-flag-width, 24px);height:var(--react-international-phone-flag-height, 24px);box-sizing:border-box}.react-international-phone-country-selector-dropdown{position:absolute;z-index:1;top:var(--react-international-phone-dropdown-top, 44px);left:var(--react-international-phone-dropdown-left, 0);display:flex;width:300px;max-height:200px;flex-direction:column;padding:4px 0;margin:0;background-color:var(--react-international-phone-dropdown-item-background-color, var(--react-international-phone-background-color, white));box-shadow:var(--react-international-phone-dropdown-shadow, 2px 2px 16px rgba(0, 0, 0, .25));color:var(--react-international-phone-dropdown-item-text-color, var(--react-international-phone-text-color, #222));list-style:none;overflow-y:scroll}.react-international-phone-country-selector-dropdown__preferred-list-divider{height:1px;border:none;margin:var(--react-international-phone-dropdown-preferred-list-divider-margin, 0);background:var(--react-international-phone-dropdown-preferred-list-divider-color, var(--react-international-phone-border-color, gainsboro))}.react-international-phone-country-selector-dropdown__list-item{display:flex;min-height:var(--react-international-phone-dropdown-item-height, 28px);box-sizing:border-box;align-items:center;padding:2px 8px}.react-international-phone-country-selector-dropdown__list-item-flag-emoji{margin-right:8px}.react-international-phone-country-selector-dropdown__list-item-country-name{overflow:hidden;margin-right:8px;font-size:var(--react-international-phone-dropdown-item-font-size, 14px);text-overflow:ellipsis;white-space:nowrap}.react-international-phone-country-selector-dropdown__list-item-dial-code{color:var(--react-international-phone-dropdown-item-dial-code-color, gray);font-size:var(--react-international-phone-dropdown-item-font-size, 14px)}.react-international-phone-country-selector-dropdown__list-item:hover{background-color:var(--react-international-phone-selected-dropdown-item-background-color, var(--react-international-phone-selected-dropdown-item-background-color, whitesmoke));cursor:pointer}.react-international-phone-country-selector-dropdown__list-item--selected,.react-international-phone-country-selector-dropdown__list-item--focused{background-color:var(--react-international-phone-selected-dropdown-item-background-color, whitesmoke);color:var(--react-international-phone-selected-dropdown-item-text-color, var(--react-international-phone-text-color, #222))}.react-international-phone-country-selector-dropdown__list-item--selected .react-international-phone-country-selector-dropdown__list-item-dial-code,.react-international-phone-country-selector-dropdown__list-item--focused .react-international-phone-country-selector-dropdown__list-item-dial-code{color:var(--react-international-phone-selected-dropdown-item-dial-code-color, var(--react-international-phone-dropdown-item-dial-code-color, gray))}.react-international-phone-country-selector-dropdown__list-item--focused{background-color:var(--react-international-phone-selected-dropdown-item-background-color, var(--react-international-phone-selected-dropdown-item-background-color, whitesmoke))}.react-international-phone-dial-code-preview{display:flex;align-items:center;justify-content:center;padding:0 8px;border:1px solid var(--react-international-phone-dial-code-preview-border-color, var(--react-international-phone-border-color, gainsboro));margin-right:-1px;background-color:var(--react-international-phone-dial-code-preview-background-color, var(--react-international-phone-background-color, white));color:var(--react-international-phone-dial-code-preview-text-color, var(--react-international-phone-text-color, #222));font-size:var(--react-international-phone-dial-code-preview-font-size, var(--react-international-phone-font-size, 13px))}.react-international-phone-dial-code-preview--disabled{background-color:var(--react-international-phone-dial-code-preview-disabled-background-color, var(--react-international-phone-disabled-background-color, whitesmoke));color:var(--react-international-phone-dial-code-preview-disabled-text-color, var(--react-international-phone-disabled-text-color, #666))}.react-international-phone-input-container{display:flex}.react-international-phone-input-container .react-international-phone-country-selector-button{border-radius:var(--react-international-phone-border-radius, 4px);margin-right:-1px;border-bottom-right-radius:0;border-top-right-radius:0}.react-international-phone-input-container .react-international-phone-input{overflow:visible;height:var(--react-international-phone-height, 36px);box-sizing:border-box;padding:0 8px;border:1px solid var(--react-international-phone-border-color, gainsboro);border-radius:var(--react-international-phone-border-radius, 4px);margin:0;background-color:var(--react-international-phone-background-color, white);border-bottom-left-radius:0;border-top-left-radius:0;color:var(--react-international-phone-text-color, #222);font-family:inherit;font-size:var(--react-international-phone-font-size, 13px)}.react-international-phone-input-container .react-international-phone-input:focus{outline:none}.react-international-phone-input-container .react-international-phone-input--disabled{background-color:var(--react-international-phone-disabled-background-color, whitesmoke);color:var(--react-international-phone-disabled-text-color, #666)}<br>`;<br><br>export const GlobalStylesSC = createGlobalStyle`<br>  ${externalLibStyles}<br>`;</pre><p>As you can see, I have accomplished the following tasks:</p><ul><li>I transformed a global css file into a limited scope Styled-Component, without modifying the Next.js main &lt;App&gt; file</li><li>This solution allows users to update their third-party libraries without worrying about the impact of changes across the application.</li><li>By using AI to create the <em>replaceCssPlaceHolder.js </em>file, you don’t need to work hard on making a recursive search into node_modules. Let ChatGPT doi it for you — it’s faster and more efficient!😇</li></ul><p>This workaround demonstrates how I can leverage my experience as a senior developer to solve problems while enjoying the powerful of ChatGpt for writing the recursive search script. I maintained the principle of separation of concerns (SoC) and ensured that my changes did not impact other modules of the application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9480677f9be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/att-israel/how-to-work-around-next-js-a9480677f9be">How to Work Around Next.js</a> was originally published in <a href="https://medium.com/att-israel">AT&amp;T Israel Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to easily define and configure your own ESLint rules without the hassle]]></title>
            <link>https://medium.com/@avrahamhamu/how-to-easily-define-and-configure-your-own-eslint-rules-without-the-hassle-a15d1fb0134f?source=rss-afcba5bab133------2</link>
            <guid isPermaLink="false">https://medium.com/p/a15d1fb0134f</guid>
            <category><![CDATA[typescript-const-enum]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[custom-eslint-rules]]></category>
            <category><![CDATA[eslint-config]]></category>
            <dc:creator><![CDATA[Avraham Hamu]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 20:35:56 GMT</pubDate>
            <atom:updated>2024-10-19T20:35:56.678Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Although there are many guides online, none of them are truly comprehensive, and the official ESLint documentation can be quite confusing. After spending hours fine-tuning the setup myself, I’m here to share what I’ve learned — because <strong>knowledge is power. Knowledge shared is power multiplied.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ekIL2GXBMz8lrqJG" /><figcaption>Photo by <a href="https://unsplash.com/@2mduffel?utm_source=medium&amp;utm_medium=referral">Mark Duffel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Context</h3><p>Recently, I found myself in a situation where I needed to add a simple custom ESLint rule to my project. The goal was to enforce the use of const enum instead of just enum in TypeScript (this is just an example).</p><p>I’ve been using ESLint for a while, but I’d never encountered a situation like this before. Usually, I just search for what I need and find an existing predefined rule (after all, it’s pretty rare in our profession to be pioneers 😊).</p><p>However, this time, I couldn’t find anything ready-made, and all the guides I read were incomplete. I felt a bit lost 🧭.</p><h3>Configuring your setup</h3><p>We will now focus on the setup itself, rather than the specific goal of the custom rule. First, ensure that you have the necessary dependencies added to your project.</p><ol><li>Since I am using TypeScript, I recommend adding the following two dependencies:</li></ol><pre>&quot;@typescript-eslint/eslint-plugin&quot;: &quot;^7.18.0&quot;,<br>&quot;@typescript-eslint/parser&quot;: &quot;^7.18.0&quot;,</pre><p>2. Next, add the following empty files to your project. These files will serve as the foundation for your custom ESLint rule and configuration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*3xX356wxsVRPT1kIxxaQSw.png" /></figure><p>3. Complete the files with the following content</p><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;eslint-plugin-mycustom-eslint-rules&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;<br>}<br><br>// index.js<br>module.exports = {<br>  rules: {<br>    &#39;prefer-const-enum&#39;: require(&#39;./prefer-const-enum&#39;),<br>  },<br>};<br><br>// prefer-const-enum.js<br>module.exports = {<br>  create(context) {<br>    return {<br>      TSEnumDeclaration(node) {<br>        if (!node.const) {<br>          context.report({<br>            node,<br>            message: &#39;Use const enum instead of enum&#39;,<br>          });<br>        }<br>      },<br>    };<br>  },<br>};</pre><p>➡️ The steps you must follow are found in the package.json file, specifically in the &quot;name&quot;: &quot;eslint-plugin-mycustom-eslint-rules&quot; entry. The <strong>prefix </strong><strong>&quot;eslint-plugin-&quot; is mandatory</strong>, and you can choose any name you like for the [mycustom-eslint-rules] part.</p><p>➡️ In index.js, you will create a rule name that corresponds to the path of the file containing the rule implementation.</p><p>➡️ The file prefer-const-enum.js is just an example of a rule. Its content was generated by ChatGPT, and you can add any implementation you desire.</p><p>4. Run the following command from command line:</p><pre>npm i -D file:eslint/custom-rules</pre><p>It will add this line into your main package.json</p><pre>&quot;eslint-plugin-mycustom-eslint-rules&quot;: &quot;file:eslint/custom-rules&quot;,</pre><h3>Using the new rule</h3><p>In the previous chapter, you defined a new rule and are almost done wiring it into your setup. Now, we will complete the final step.</p><p>Open your ESLint setup file. In my case, I use a JavaScript file named .eslintrc.js. Add the following entries to incorporate your custom rule:</p><pre>module.exports = {<br>  // Other ESLint configurations...<br>  plugins: [&#39;mycustom-eslint-rules&#39;],<br>  rules: {<br>    &#39;mycustom-eslint-rules/prefer-const-enum&#39;: 2,<br>  },<br>};</pre><p>This configuration ensures that your new rule is activated and will enforce the specified behavior throughout your project.</p><h3>Finally it works 🎉</h3><p>This is the kind of error that you will receive on running <em>“npm run eslint”</em></p><pre> 1:8  error  Use const enum instead of enum  mycustom-eslint-rules/prefer-const-enum</pre><h3>Conclusion</h3><p>The main pitfall was in the name defined in /eslint/custom-rules/package.json, where the prefix must be eslint-plugin-. Additionally, the way you activate the custom rules involves loading them as an npm module without the need to create a fully-fledged npm artifact.</p><p>I hope this guide saves you some time. Remember, while AI helped me generate the rule itself, there’s still a long way to go in terms of providing complete setup solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a15d1fb0134f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Navigate xCode Upgrade Challenges from 14 to 15 in React Native Apps]]></title>
            <link>https://medium.com/@avrahamhamu/how-to-navigate-xcode-upgrade-challenges-from-14-to-15-in-react-native-apps-d0fed4132d82?source=rss-afcba5bab133------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0fed4132d82</guid>
            <category><![CDATA[podfile]]></category>
            <category><![CDATA[iphone-15]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[macos-sonoma]]></category>
            <category><![CDATA[xcode15]]></category>
            <dc:creator><![CDATA[Avraham Hamu]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 13:02:20 GMT</pubDate>
            <atom:updated>2024-01-04T13:02:20.669Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Typedef redefinition with different types (‘uint8_t’ (aka ‘unsigned char’) vs ‘enum clockid_t’)</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*66VRnYYBqmjebTDQ" /><figcaption>Photo by <a href="https://unsplash.com/@arnosenoner?utm_source=medium&amp;utm_medium=referral">Arno Senoner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently upgraded my macOS from version 13 (Ventura) to 14 (Sonoma), which involved updating xCode from 14 to 15.</p><p>Unfortunately, there’s no backward compatibility. Prior to the upgrade, my React Native application built and ran successfully. However, with the transition to xCode 15, I found myself grappling with various changes. 😮</p><p>The first crucial step after installing xCode 15 is to also install the Simulator for iPhone 15. Failure to do so renders your previous simulators inaccessible (whether this is a bug or a feature remains unclear). After setting up the Simulator for iPhone 15, I attempted to build my application, encountering my first error — a familiar routine.</p><blockquote><strong>../ios/Pods/Pods.xcodeproj: The iOS Simulator deployment target ‘IPHONEOS_DEPLOYMENT_TARGET’ is set to 11.0, but the range of supported deployment target versions is 12.0 to 17.2.99</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pu1aTfFu9tSdWiPZXCLYQ.png" /><figcaption>screenshot from xCode 15</figcaption></figure><p>This error was easily resolved by updating a line in the <em>Podfile</em>. Here’s the snippet for reference:</p><pre>... your stuff...<br><br>  def handle_targets_config(installer)<br>    installer.pods_project.targets.each do |target|<br>      target.build_configurations.each do |config|<br>          # ==&gt; change in the below line 11.0 by 12.0 &lt;==<br>          config.build_settings[&#39;IPHONEOS_DEPLOYMENT_TARGET&#39;] = &#39;11.0&#39;<br>      end<br>    end<br>  end<br><br>  post_install do |installer|<br>    react_native_post_install(installer)<br>    handle_targets_config(installer)<br>  end<br>end</pre><p>With this adjustment made, I proceeded to rebuild my project, only to be confronted with an old error I thought I had addressed in the past. 👎🏻</p><pre>Showing All Messages<br>../ios/Pods/Headers/Private/RCT-Folly/folly/portability/Time.h:52:17: <br>Typedef redefinition with different types (&#39;uint8_t&#39; (aka &#39;unsigned char&#39;) vs &#39;enum clockid_t&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBjubvhcoEKBT5_l2nNUGQ.png" /><figcaption>screenshot from xCode 15</figcaption></figure><p>This issue had been successfully fixed by modifying a line in the “<em>Time.h</em>” file. However, the xCode upgrade seemed to resurrect it. Let’s delve into the details.</p><p>Previously, I had resolved this error by adjusting a line in the “<em>Time.h</em>” file located at “<em>../ios/Pods/Headers/Private/RCT-Folly/folly/portability/Time.h</em>”</p><pre>#pragma once<br><br>#include &lt;stdint.h&gt;<br>#include &lt;time.h&gt;<br><br>#include &lt;folly/portability/Config.h&gt;<br><br>// OSX is a pain. The XCode 8 SDK always declares clock_gettime<br>// even if the target OS version doesn&#39;t support it, so you get<br>// an error at runtime because it can&#39;t resolve the symbol. We<br>// solve that by pretending we have it here in the header and<br>// then enable our implementation on the source side so that<br>// gets linked in instead.<br>#if __MACH__ &amp;&amp;                                                       \<br>        ((!defined(TARGET_OS_OSX) || TARGET_OS_OSX) &amp;&amp;                \<br>         (MAC_OS_X_VERSION_MIN_REQUIRED &lt; MAC_OS_X_VERSION_10_12)) || \<br>    (TARGET_OS_IPHONE &amp;&amp; (__IPHONE_OS_VERSION_MIN_REQUIRED &lt; __IPHONE_10_0))<br><br>#ifdef FOLLY_HAVE_CLOCK_GETTIME<br>#undef FOLLY_HAVE_CLOCK_GETTIME<br>#endif<br><br>#define FOLLY_HAVE_CLOCK_GETTIME 1<br>#define FOLLY_FORCE_CLOCK_GETTIME_DEFINITION 1<br><br>#endif</pre><p>The modification involved changing the line “<em>TARGET_OS_IPHONE &amp;&amp; (__IPHONE_OS_VERSION_MIN_REQUIRED &lt; __IPHONE_11_0)</em>” to match the conditions suggested in the file comments.</p><pre>...your stuff...<br>  def handle_targets_config(installer)<br>    installer.pods_project.targets.each do |target|<br>      target.build_configurations.each do |config|<br>          config.build_settings[&#39;IPHONEOS_DEPLOYMENT_TARGET&#39;] = &#39;11.0&#39;<br>      end<br>    end<br>  end<br><br>  post_install do |installer|<br>    react_native_post_install(installer)<br>    handle_targets_config(installer)<br>    # We need to make one crude patch to RCT-Folly - set `__IPHONE_10_0` to our iOS target + 1<br>    # https://github.com/facebook/flipper/issues/834 - 84 comments and still going...<br>    # == &gt; Here was my hack<br>    `sed -i -e  $&#39;s/__IPHONE_10_0/__IPHONE_12_0/&#39; Pods/RCT-Folly/folly/portability/Time.h`<br>  end<br>end<br></pre><p>Since my <em>IPHONEOS_DEPLOYMENT_TARGET</em> was set to <em>11.0</em>, I replaced:</p><pre>__IPHONE_OS_VERSION_MIN_REQUIRED &lt; __IPHONE_10_0<br>by <br>__IPHONE_OS_VERSION_MIN_REQUIRED &lt; __IPHONE_12_0</pre><p>This allowed the project to compile successfully. However, the recent modification in the <em>Podfile</em>:</p><pre>config.build_settings[&#39;IPHONEOS_DEPLOYMENT_TARGET&#39;] = &#39;11.0&#39;<br>by<br>config.build_settings[&#39;IPHONEOS_DEPLOYMENT_TARGET&#39;] = &#39;12.0&#39;</pre><p>rendered the “<em>Time.h</em>” condition false, leading to project failure.</p><p>Here lies one of the challenges introduced by xCode 15 — the file’s relocation from “<em>Pods/RCT-Folly/folly/portability/Time.h</em>” to “<em>Pods/Headers/Private/RCT-Folly/folly/portability/Time.h</em>” with additional permission access complications.</p><p>To navigate these changes, I found a workaround using a temporary file.</p><p>Here’s the final version of my <em>Podfile</em>:</p><pre>... your stuff...<br>  def handle_targets_config(installer)<br>    installer.pods_project.targets.each do |target|<br>      target.build_configurations.each do |config|<br>          config.build_settings[&#39;IPHONEOS_DEPLOYMENT_TARGET&#39;] = &#39;12.0&#39;        <br>      end<br>    end<br>  end<br><br>  post_install do |installer|<br>    react_native_post_install(installer)<br>    handle_targets_config(installer)<br>    # We need to make one crude patch to RCT-Folly - set `__IPHONE_10_0` to our iOS target + 1<br>    # ==&gt; hack to modify the header file<br>    `sed -e $&#39;s/__IPHONE_10_0/__IPHONE_13_0/&#39; \<br>        Pods/Headers/Private/RCT-Folly/folly/portability/Time.h &gt; temp_file \<br>        &amp;&amp; mv temp_file Pods/Headers/Private/RCT-Folly/folly/portability/Time.h`<br>  end<br>end</pre><p>The only downside to this approach is that the terminal will prompt you to confirm the replacement of the file with the new content.</p><p>One more time, Apple’s peculiar changes force developers to invest time in navigating through these upgrades. Fortunately, my previous experience with a similar error during the xCode 14 upgrade proved beneficial in tackling the challenges posed by xCode 15. Despite the occasional headaches, the ability to troubleshoot and find workarounds is an essential skill for developers facing the ever-evolving landscape of development tools.</p><p>If you found this post helpful or insightful, don’t forget to give it a clap !👏</p><p>Your support is greatly appreciated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0fed4132d82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Memoization Cheatsheet]]></title>
            <link>https://medium.com/better-programming/react-native-memoization-cheatsheet-769ee2841aa2?source=rss-afcba5bab133------2</link>
            <guid isPermaLink="false">https://medium.com/p/769ee2841aa2</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Avraham Hamu]]></dc:creator>
            <pubDate>Wed, 22 Mar 2023 19:37:28 GMT</pubDate>
            <atom:updated>2023-04-04T15:21:09.919Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qeseXtf6VpsNuwx9" /><figcaption>Photo by <a href="https://unsplash.com/@kelsymichael?utm_source=medium&amp;utm_medium=referral">Kelsy Gagnebin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What Is Memoization?</h3><p>Memoization is a programming technique that speeds up performance by caching the results of expensive function calls. When a function is memoized, it returns a precomputed value immediately if it has seen the same inputs before.</p><p>This article focuses on how to use memoization effectively rather than explaining how the technique works. It provides several examples to illustrate the proper use of memoization.</p><p>Whether or not to use memoization should be based on a careful performance analysis using appropriate tools.</p><p>If you are unfamiliar with React memoization, we recommend you read <a href="https://www.joshwcomeau.com/react/usememo-and-usecallback/">this article</a> before proceeding.</p><h3>1. Gold Rule</h3><p>When it comes to optimization, there is always a tradeoff between speed and other factors such as code complexity, maintainability, and readability. Therefore, it is important not to optimize prematurely and instead measure the cost of unnecessary re-renders before trying to optimize them.</p><p>To measure the cost of a function and determine whether it needs to be memoized, it is best to use appropriate tools such as <a href="https://github.com/facebook/react/tree/main/packages/react-devtools">React Native devtools</a> if you are working with RN.</p><p>By measuring the cost of a function using devtools, you can identify bottlenecks in your code and make informed decisions about where to optimize for performance.</p><p>Remember, optimization should always be guided by actual performance data, not by assumptions or guesswork. So, don’t rush to pre-optimize without first measuring the cost of unnecessary re-renders using appropriate tools like <a href="https://developer.chrome.com/docs/devtools/performance">devtools</a>.</p><h3>2. Some Concepts — Quick Reminder</h3><h4>When should you use memoization?</h4><blockquote>React is heavily optimized out of the box, and so in general, re-renders aren’t a big deal.</blockquote><blockquote>Don’t use memoization if you can’t quantify the performance gains.</blockquote><h4>What is the difference between <strong>useCallback</strong>, <strong>useMemo</strong> and <strong>memo</strong>?</h4><p>useCallback is syntactic sugar; it returns its function uncalled so that you can call it later. It makes our lives a bit nicer when memoing callback functions.</p><pre>// This:<br>React.useCallback(function helloWorld(){}, []);<br>// ...Is functionally equivalent to this:<br>React.useMemo(() =&gt; function helloWorld(){}, []);</pre><p>useMemo calls its function and returns the result.</p><p>When React.memo() wraps a component, React memoizes the rendered output of the wrapped component, then skips unnecessary renderings.</p><h3>2. <strong>The Cheatsheet Table</strong></h3><p>The table below shows various scenarios involving parent and child components, which we use to test the re-rendering process.</p><figure><img alt="table with four columns (#, parent component, child component memorization, child’s re-render avoided), 18 rows (most important rows: parent component = useCallback(()=&gt;…,), child component memoization=React.memo, Child’s re-render avoided=bug; parent component = useCallback(()=&gt;…,[arg]), child component memoization=nothing, Child’s re-render avoided=hurt performance; parent component = useCallback(()=&gt;…,[]), child component memoization=nothing, Child’s re-render avoided=hurt performance" src="https://cdn-images-1.medium.com/max/855/1*S27xBrrnIyuuZ1UH-10jJg.jpeg" /><figcaption>For cases 7, 8 and 9, see explanations in section 3.2 below</figcaption></figure><h3>3. The Proof by Examples</h3><p>To allow you to experiment with the code and see the effects of memoization in action, all the examples can be opened in a separate window using <a href="https://stackblitz.com/">StackBlitz</a>’s inline editor.</p><p>The child component in each example will blink every time it is re-rendered, providing a clear visual indication of how memoization affects performance.</p><p>To get more information about which component is being re-rendered, it is important to open the log section while experimenting with the examples.</p><p><strong>Disclaimer</strong>: these examples are optimized for desktops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wf5fz5n3RcQmzkZomwuaSg.png" /></figure><h4>3.1 React.memo [aka pure component by the past]</h4><blockquote>React.memo will only re-render when it receives new data, or when its internal state changes.</blockquote><p>1. The default behavior in React is for child components to be re-rendered whenever their parent components are re-rendered.</p><p><em>In the following example, click the grey button to increment a counter and see the child re-render:</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender%2Fff38b61699afea18cb627a70cd6dce31&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/919fa574ec94f5bfb7a0ef47a9ad5632/href">https://medium.com/media/919fa574ec94f5bfb7a0ef47a9ad5632/href</a></iframe><p>2. Memoizing the child component can prevent it from being re-rendered unnecessarily when its parent component is re-rendered.</p><p><em>Click the grey button to increment a counter and see the log child re-render:</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-ca3tam%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-ca3tam%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-ca3tam%2Fd928b3bb085010fc91b1cb5510b4fd1c&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3a6e70d02b6deb53ed434e28397b4a8/href">https://medium.com/media/b3a6e70d02b6deb53ed434e28397b4a8/href</a></iframe><p>3.1. Memoization only prevents re-renders when the component is passed the same props. Any changes to the props passed to the memoized child component will trigger a re-render, even if it has been memoized.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-vscd2y%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-vscd2y%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-vscd2y%2F4971ede438c2b38638b257a1b512df95&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/22a6536a05b1a1ba71d172f89fbe557a/href">https://medium.com/media/22a6536a05b1a1ba71d172f89fbe557a/href</a></iframe><p>3.2. React.memo can prevent a child component from being re-rendered when its parent component updates, but only if the parent update doesn’t affect the child’s props.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-mnydwv%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-mnydwv%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-mnydwv%2Ff09a9e9cf92255b0b7676abc1711d0bc&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5dc51e731eec2ea630b61dce213ee7f8/href">https://medium.com/media/5dc51e731eec2ea630b61dce213ee7f8/href</a></iframe><p>4.1. Passing an anonymous function to a memoized child component will cause it to be re-rendered, even if it has been memoized.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-ukgcbb%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-ukgcbb%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-ukgcbb%2F7e3b1d96eabdb36e683017e1e95ab4fa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ecbe5bc7b04245dd607f954ea9a7b5c/href">https://medium.com/media/3ecbe5bc7b04245dd607f954ea9a7b5c/href</a></iframe><p>4.2. Even when using a const function (not an inline function), passing it to a memoized child component will still cause it to be re-rendered.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-wnpex6%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-wnpex6%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-wnpex6%2F380d9f1dd2bab96427215ec81d49547b&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcef37533992559b19f88fbaf10732c1/href">https://medium.com/media/fcef37533992559b19f88fbaf10732c1/href</a></iframe><p>5.1. Non-primitive props will always trigger a re-render of a memoized child component. React.memo uses a shallow comparison and considers a new reference a new value.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-m6ldff%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-m6ldff%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-m6ldff%2F61c2e8d9d37f3a11a9293af894201ab8&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/73ed659c38a92ab383d9a169b9e333bd/href">https://medium.com/media/73ed659c38a92ab383d9a169b9e333bd/href</a></iframe><p>5.2. In cases where non-primitive props must be passed to a memoized child component in React, a deep comparison technique can help optimize memoization. It’s important to consider the performance impact of different comparison methods (isEqual), such as using JSON.stringify or lodash.isEqual.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-yfv9jv%3Fembed%3D1%26file%3DChild.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-yfv9jv%3Ffile%3DChild.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-yfv9jv%2F72a0516cd88a2eaf7cc3220db1cf8cde&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f55f2190e8823d126c7bec19782bcf6b/href">https://medium.com/media/f55f2190e8823d126c7bec19782bcf6b/href</a></iframe><h4>3.2 React.useCallback</h4><p>When applying memoization to a component that accepts a callback, it is essential to exercise caution. This is because the parent component may provide different instances of the callback function on every render.</p><p>Here are several ways incorrectly using the useCallback hook can decrease application performance:</p><ul><li>The first issue is that calling the useCallback() hook every time MyComponent renders can reduce render performance.</li><li>On each component re-render, the useCallback() hook returns the same function object, while the inline function is recreated each time (useCallback() only skips it). This optimization can sometimes cost more than not having the optimization, especially if the function is small or the component is simple.</li></ul><p>6.1. It is recommended to use the useCallback hook in conjunction with a child memoized component only.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-x7gnvu%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-x7gnvu%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-x7gnvu%2F3592148ab6d7bd1178bd5a1537adfd15&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/92c2b8cd88ef621fe3364069b41ffe0e/href">https://medium.com/media/92c2b8cd88ef621fe3364069b41ffe0e/href</a></iframe><p>6.2. Deep comparison allows you to inspect the child component’s second argument, which could have triggered a useless re-render.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-q3rkw4%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-q3rkw4%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-q3rkw4%2Fdbea3f74a2fada4a67369f167c747a01&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e982752c465f4bb8211645cecb0225b6/href">https://medium.com/media/e982752c465f4bb8211645cecb0225b6/href</a></iframe><p>7. Using useCallback without array dependencies leads to a bug in the logic (the counter is not correctly incremented).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-bsq33q%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-bsq33q%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-bsq33q%2F94d4c81d751d4d0228993916ea222748&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b226f64e7c9828b3e818fbb94a5e8ed/href">https://medium.com/media/8b226f64e7c9828b3e818fbb94a5e8ed/href</a></iframe><p>8. Using the useCallback hook without also using the useMemo hook can harm performance and be pointless, as useCallback returns the same function object but recreates the inline function on each render.</p><p>Additionally, React performs additional work during each render, which can slow down your app.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-dicffg%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-dicffg%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-dicffg%2Fd862d10b691d5e2927fca2d257a23b39&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/addc290dff0b760ad968328ab004cf43/href">https://medium.com/media/addc290dff0b760ad968328ab004cf43/href</a></iframe><p>9. Same as previous, but with an empty arg array. There’s no demo.</p><p>10. This case is interesting when saving large, heavy functions only</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-psc2hp%3Fembed%3D1%26file%3DParent.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-psc2hp%3Ffile%3DParent.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-psc2hp%2F323de0d96842f19a83360e43b6472a35&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/580630ea5117e204a059b979eaf5620b/href">https://medium.com/media/580630ea5117e204a059b979eaf5620b/href</a></iframe><h3>3.3. React.useMemo</h3><blockquote><em>useMemo</em> is essentially like a lil cache, and the dependencies are the cache invalidation strategy.</blockquote><p>11. Hook useMemo example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-vuikjn%3Fembed%3D1%26file%3DChild.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Freact-ts-1-rerender-vuikjn%3Ffile%3DChild.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Freact-ts-1-rerender-vuikjn%2Fb6d11ad29226eb388c6ad3a3fbb1ed5e&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b25419830692e397ee758a05c4ac71a4/href">https://medium.com/media/b25419830692e397ee758a05c4ac71a4/href</a></iframe><h3>Conclusion</h3><p>If you’ve made it this far, you have tested all the cases with the editor.</p><p>The hooks useMemo and useCallback are often misused, which can have the opposite effect intended by the developer.</p><p>You can eliminate about 90% of the useMemo and useCallback hooks in your app right now, and the app should still function well; it may even perform slightly faster. This is not to say that useMemo or useCallback are entirely useless, but their application should be limited to specific and concrete cases. Frequently, we wrap items in these hooks unnecessarily.</p><p>It is crucial to understand that useMemo and useCallback are only beneficial during the re-render phase. During the initial render, they are ineffective and can harm performance by causing React to perform additional work. This means your app may be slightly slower during the initial render, and if you have numerous instances of these hooks throughout your app, the slowdown may even be noticeable.</p><p>Based on the information provided, there is only one scenario where memoizing props on a component is practical: when all of the props and the component itself are memoized. Otherwise, memoizing props only wastes memory and makes your code unnecessarily complex.</p><p>You may safely remove all useMemo and useCallback hooks from the code if:</p><ul><li>They are passed directly or through a chain of dependencies to DOM elements as attributes.</li><li>They are passed as props, directly or through a chain of dependencies, to a component that is not memoized.</li><li>They are passed as props, directly or through a chain of dependencies, to a component with at least one non-memoized prop.</li></ul><h3>References</h3><ul><li><a href="https://dmitripavlutin.com/use-react-memo-wisely/">Use React.memo() wisely</a></li><li><a href="https://www.joshwcomeau.com/react/usememo-and-usecallback/">Understanding useMemo and useCallback</a></li><li><a href="https://www.developerway.com/posts/how-to-use-memo-use-callback">How to useMemo and useCallback: you can remove most of them</a></li></ul><p>Great article to think out of the (memo):</p><p><a href="https://overreacted.io/before-you-memo/">Before You memo() - overreacted</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=769ee2841aa2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/react-native-memoization-cheatsheet-769ee2841aa2">React Native Memoization Cheatsheet</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to shrink (tree-shake) lodash in bundle file for React Native?]]></title>
            <link>https://medium.com/att-israel/how-to-shrink-tree-shake-lodash-in-bundle-file-for-react-native-90813a995dfa?source=rss-afcba5bab133------2</link>
            <guid isPermaLink="false">https://medium.com/p/90813a995dfa</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[lodash]]></category>
            <category><![CDATA[bundle]]></category>
            <category><![CDATA[tree-shaking]]></category>
            <dc:creator><![CDATA[Avraham Hamu]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 14:06:08 GMT</pubDate>
            <atom:updated>2021-12-14T14:06:08.652Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i1WKmMX_Wq-0zGPU" /><figcaption>Photo by <a href="https://unsplash.com/@samuelgirven?utm_source=medium&amp;utm_medium=referral">Samuel Girven</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>1. Let’s start from the beginning…</h3><p>By default, React Native files are compiled into one bundle file. In time, the size of this file will increase with the new libs that you add 🏋🏻. <br>But did you know that the bundle size also directly impacts the bootstrap application time?</p><p>The issue is not only that each upgrade version will take longer to download (who really cares about this?)…but also that performance issues always lessen a good user experience.</p><p>To solve this, the first stage is to reduce bundle size… to remove what we **<strong><em>never</em></strong>** use.</p><h3>2. What is Tree Shaking?</h3><p>Tree Shaking is a <strong>concept in development of eliminating dead code or unused code</strong>. Imagine your application as a tree🌴. By implementing tree shaking practices, the performance of your React Native applications will be improved and the bundle size reduced.</p><p>The idea is to remove modules from packages that aren’t being used by your application. The concept behind the term is that each package has its individual exports which have files that they depend on, fanning out in tree structure. If I only need one of those exports, I can <em>shake up</em> the tree to remove the branches that aren’t necessary. This is also called dead code elimination.</p><h3>3. Let’s measure out bundle size before reducing it</h3><p>Simply run the following command it will do all the magic</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d822f41a90c7f82214e7cf372bca426/href">https://medium.com/media/8d822f41a90c7f82214e7cf372bca426/href</a></iframe><p>The result will automatically appears in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxQJ1830YkEhNs5Wt5DkkA.png" /><figcaption>from the total bundle size, node_modules is 2.95MB !! … and lodash 117KB</figcaption></figure><h3>4. But before we go forward…let’s make things clear</h3><p>My React Native project uses the Typescript template from the official documentation with the following tsconfig.json configuration <em>[I use RN 0.64.2 with version 6.6.5 of Typescript template]</em></p><p><a href="https://github.com/react-native-community/react-native-template-typescript/blob/6.6.5/template/tsconfig.json">https://github.com/react-native-community/react-native-template-typescript/blob/6.6.5/template/tsconfig.json</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe3dc0db3fbd2d479fc32bd648e249cd/href">https://medium.com/media/fe3dc0db3fbd2d479fc32bd648e249cd/href</a></iframe><p>It is ❗<strong><em>important</em></strong>❗ to note here that I left the field <strong>“module”: “commonjs” </strong>as is, because switching to <strong>“module”: “esnext” </strong>will increase the final bundle size. I will write another story about that later, just make sure your are aligned with the correct Typescript configuration.</p><h3>5. Having said that 😉</h3><h4>☝️ 3 ways to import functions from lodash</h4><ul><li>Import the whole library</li></ul><pre>import _ from &#39;lodash&#39;;</pre><ul><li>Import specific methods inside of curly brackets</li></ul><pre>import { map, tail, times, uniq } from &#39;lodash&#39;;</pre><ul><li>Import specific methods one by one</li></ul><pre>import map from &#39;lodash/map&#39;;<br>import tail from &#39;lodash/tail&#39;;<br>import times from &#39;lodash/times&#39;;<br>import uniq from &#39;lodash/uniq&#39;;</pre><p>So, instead of grabbing the entire lodash package, I only grab the relevant packages, only the ones that I <strong><em>really</em></strong> need in my application.</p><p>→ but …forcing my team to split from one line import to multiples lines imports, would have make them hate me, especially as I added an es-lint to enforce this import strategy (details in a separate chapter).</p><p>Theoretically, the tree shaking is done automatically by webpack…except that we don’t use webpack, we build a mobile application - there are a lot of good articles on how to perform tree shaking for a React web application.</p><p>After googling for hours on how to activate this automatic tree shaking with metro-bundler… I found out…that this feature is not supported by metro-bundler.</p><p><a href="https://github.com/facebook/metro/issues/227">https://github.com/facebook/metro/issues/227</a></p><blockquote>React Native packaging tools do not support Metro Tree Shaking</blockquote><blockquote>Metro currently does not support tree shaking based on module import/export.</blockquote><blockquote>We are not actively working on tree shaking at Facebook and are exploring other more promising ways to keep our app size small.</blockquote><p>Just to feel the difference, by changing all the project lodash from</p><pre>import { map, tail, times, uniq } from &#39;lodash&#39;;</pre><p>to</p><pre>import map from &#39;lodash/map&#39;;<br>import tail from &#39;lodash/tail&#39;;<br>import times from &#39;lodash/times&#39;;<br>import uniq from &#39;lodash/uniq&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cfmxY-kgX5uwgqDv1mczRA.png" /><figcaption>the new bundle size is now: 2.88MB and lodash only 46 KB</figcaption></figure><h3>6. So until now, it looks that we achieved our goal, but…</h3><p>I still use the lodash split notation, and you remember that it is a little bit constraining.</p><p>I also discovered that there are many babel plugins that could do the job for me, meaning, I will continue to write</p><pre>import { map, tail, times, uniq } from &#39;lodash&#39;;</pre><p>and the plugin will split the line into multi lines during the transpile phase to JavaScript.</p><p>And indeed, I tested many of them.</p><h3>The plugins that I tried</h3><ul><li><a href="https://github.com/lodash/babel-plugin-lodash">babel-plugin-lodash</a> (<a href="https://github.com/lodash/babel-plugin-lodash"><em>You must use ES2015 imports to load Lodash</em></a>)</li><li><a href="https://github.com/umijs/babel-plugin-import">babel-plugin-import</a> (<em>works only with</em> <em>tsconfig.json option “module”: “ES2015/ESNext”</em>)</li><li>ts-transformer-lodash-import (<em>Only ES module imports are supported</em>)</li><li><a href="https://github.com/Brooooooklyn/ts-import-plugin">ts-plugin-import</a> (<a href="https://github.com/Brooooooklyn/ts-import-plugin"><em>with tsconfig.json option “module”: “ESNext”</em></a><em> </em>)</li></ul><p>They all have the same drawback, they will only work while configuring</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d59b24bac8be21104744e1feafcdbd3/href">https://medium.com/media/4d59b24bac8be21104744e1feafcdbd3/href</a></iframe><p>and by doing this , the bundle will be much heavier, and we lose the effect that we wanted to gain by applying the tree shaking.</p><h3>7. No choice…making the magic by myself</h3><p>I tried to make a simple mapping file, to enjoy the benefit of tree shaking on one hand, and on the other hand to not force people to split a lodash import into multiples lines.</p><p>It looks like this:</p><ul><li>create new file lodashES.ts</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/102c800ed8aca24aa9b116dee10d87ea/href">https://medium.com/media/102c800ed8aca24aa9b116dee10d87ea/href</a></iframe><ul><li>adding alias into tsconfig.json</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/892e420b8c02dc2a75721606e38eb9b2/href">https://medium.com/media/892e420b8c02dc2a75721606e38eb9b2/href</a></iframe><ul><li>adding alias into babel.config.json</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca4e2c533cbba74c6f0a2fdfc72c5a10/href">https://medium.com/media/ca4e2c533cbba74c6f0a2fdfc72c5a10/href</a></iframe><ul><li>and change the syntax in your components files, to use the new lodash alias</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b311f1654c7f0166551599fce4d1fd/href">https://medium.com/media/53b311f1654c7f0166551599fce4d1fd/href</a></iframe><pre>run again bundle size analyzer:</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d822f41a90c7f82214e7cf372bca426/href">https://medium.com/media/8d822f41a90c7f82214e7cf372bca426/href</a></iframe><p>and we get the desired size reduction we wanted in step 5.</p><ul><li>before mapping lodash : lodash size in bundle file = 117KB</li><li>after mapping lodash : lodash size in bundle file = 42KB</li></ul><p>If you use the “chain” function in your code, you won’t be able to perform tree shaking lodash, and you will need to replace it. (I was able to manage this limitation easily by using vanilla JS functions).</p><p>In order to protect, this optimization and to be sure that no one will make a direct import from lodash, I added an eslint rule:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dce33499a98ee572800df9ff2138d2e/href">https://medium.com/media/7dce33499a98ee572800df9ff2138d2e/href</a></iframe><h4>Conclusion</h4><p>During this investigation, I mainly learned to pay attention to the size of the lib. that we add to our project. This optimization only decreased the total bundle size by 2.3% which is a very minor reduction. But, in the long term, if we stick to this pattern, we will have no degradation in application performance, and we will always look to use small libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff1b35763f78796bb18b97918a85d13/href">https://medium.com/media/6ff1b35763f78796bb18b97918a85d13/href</a></iframe><p>Special thanks 🙏 to Oshri Barzilay who helped me to mature this concept, and was the father’s of the map file idea</p><p>References:</p><ul><li><a href="https://www.blazemeter.com/blog/the-correct-way-to-import-lodash-libraries-a-benchmark">The Correct Way to Import Lodash Libraries - A Benchmark | BlazeMeter</a></li><li><a href="https://medium.com/@martin_hotell/tree-shake-lodash-with-webpack-jest-and-typescript-2734fa13b5cd">Tree shake Lodash with Webpack, Jest and Typescript</a></li><li><a href="https://segmentfault.com/a/1190000039834087/en">⚡️ React Native startup speed optimization-JS article [The most complete network, worthy of collection]</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90813a995dfa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/att-israel/how-to-shrink-tree-shake-lodash-in-bundle-file-for-react-native-90813a995dfa">How to shrink (tree-shake) lodash in bundle file for React Native?</a> was originally published in <a href="https://medium.com/att-israel">AT&amp;T Israel Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>