<?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 Reg on Medium]]></title>
        <description><![CDATA[Stories by Reg on Medium]]></description>
        <link>https://medium.com/@reg9295?source=rss-61c86d937b88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dXblnkPn1yn4KM23z-EDcQ.jpeg</url>
            <title>Stories by Reg on Medium</title>
            <link>https://medium.com/@reg9295?source=rss-61c86d937b88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 13:43:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@reg9295/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[Complete i18n Guide To Support Multi-Language For Your React Native App]]></title>
            <link>https://levelup.gitconnected.com/complete-i18n-guide-to-support-multi-language-for-your-react-native-app-c5ea4e0fa5b3?source=rss-61c86d937b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5ea4e0fa5b3</guid>
            <category><![CDATA[i18n]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native-developers]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-tutorial]]></category>
            <dc:creator><![CDATA[Reg]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 16:29:17 GMT</pubDate>
            <atom:updated>2023-01-24T16:29:17.038Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DtEyFwghwqJDiodm" /><figcaption>Photo by <a href="https://unsplash.com/@edurnetx?utm_source=medium&amp;utm_medium=referral">Edurne Tx</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The implementation of i18n (internationalisation and localisation) in a React Native project can be quite complex and confusing, especially with all these outdated tutorials out there in the wild.</p><p>But in this article, I will guide you through the installation and configuration to make i18n work in your React Native project. Without further ado, let’s get started!</p><p><strong>Installation and Configuration</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*-buVUNAdwm6I9qzoRbQl8g.png" /></figure><p><a href="https://github.com/i18next/react-i18next">react-i18next</a> is a powerful i18n library for React and React Native that is based on <a href="https://www.i18next.com/">i18next</a>. It also has the most Github stars and download counts (see above) when compared to other i18n libraries for React Native, meaning that more people have been testing it on production, and there are more resources available for help when you get stuck.</p><p>To install react-i18next and its dependency :</p><pre>npm install react-i18next i18next --save<br><br>// alternatively, if you use yarn<br>yarn add react-i18next i18next</pre><p>Then, create the directory and files as shown below :</p><pre>src<br>├── /locales<br>│   ├── en.json<br>│   ├── zh.json // or any other locale you want<br>│   └── index.js<br>...</pre><p>en.json :</p><pre>{<br>  &quot;dummyNamespace&quot;: {<br>    &quot;medium&quot;: &quot;medium is great!&quot;<br>  }<br>}</pre><p>zh.json :</p><pre>{<br>  &quot;dummyNamespace&quot;: {<br>    &quot;medium&quot;: &quot;medium 太棒了!&quot;<br>  }<br>}</pre><p>index.js :</p><pre>import i18n from &#39;i18next&#39;;<br>import {initReactI18next} from &#39;react-i18next&#39;;<br>import en from &#39;./en.json&#39;;<br>import zh from &#39;./zh.json&#39;;<br><br>const resources = {<br>  en: {<br>    translation: en,<br>  },<br>  zh: {<br>    translation: zh,<br>  },<br>};<br><br>i18n.use(initReactI18next).init({<br>  resources,<br>  lng: &#39;zh&#39;,<br>  fallbackLng: &#39;en&#39;,<br>  compatibilityJSON: &#39;v3&#39;,<br>  interpolation: {<br>    escapeValue: false<br>  }<br>});</pre><p>The resources variable contains all the translation strings imported from the JSON files we created earlier. However, it’s worth noting that these translation strings can also be managed through a UI, such as <a href="https://locize.com/">lociz</a> — although it is not covered in this article, but if you are interested, you can check it out. lng variable sets the default language to be used in your app. fallbackLng specifies the fallback language if the value in lng is not available. interpolationLng on the other hand, specifies whether to escape values to mitigate XSS attacks.</p><p>Note that index.js is not compulsory but is recommended to avoid cluttering up your App.js.</p><p>Finally, App.js :</p><pre>import &#39;./src/locales/index&#39;;<br>import {useTranslation} from &#39;react-i18next&#39;;<br>...<br><br>function App() {<br>  const {t} = useTranslation();<br><br>  return (<br>    &lt;View&gt;<br>      &lt;Text&gt;{t(&#39;dummyNamespace.medium&#39;)}&lt;/Text&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>Then in the Android simulator, you will see it is indeed working! :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*yXMhmoB2dSQPoB4ABRtyWA.png" /></figure><p><strong>Switching Language</strong></p><p>We can optionally create a dropdown language selector component that allows users to dynamically select their desired language at runtime. I have chosen this specific dropdown picker library, but you can choose any library you prefer. To install it :</p><pre>npm install react-native-dropdown-picker</pre><p>And modify your App.js:</p><pre>import DropDownPicker from &#39;react-native-dropdown-picker&#39;;<br>...<br><br>function App() {<br>  const {t, i18n} = useTranslation(); // destructure i18n here<br>  const [open, setOpen] = useState(false);<br>  const [value, setValue] = useState(&#39;en&#39;);<br>  const [items, setItems] = useState([<br>    {label: &#39;English&#39;, value: &#39;en&#39;},<br>    {label: &#39;Chinese&#39;, value: &#39;zh&#39;},<br>  ]);<br><br>  useEffect(() =&gt; {<br>    i18n.changeLanguage(value);<br>  }, [value]);<br><br>  return (<br>    &lt;View&gt;<br>      &lt;Text&gt;{t(&#39;dummyNamespace.medium&#39;)}&lt;/Text&gt;<br>      &lt;DropDownPicker<br>        open={open}<br>        value={value}<br>        items={items}<br>        setOpen={setOpen}<br>        setValue={setValue}<br>        setItems={setItems}<br>      /&gt;<br>    &lt;/View&gt;<br>  );<br>}</pre><p>Note that this is just a simple example to demonstrate how the language switching mechanism works, you can definitely refactor the code you see fit.</p><p><strong>Better Developer Experience</strong></p><p>The Visual Studio Code extension <a href="https://github.com/lokalise/i18n-ally">i18n Ally</a> offers various useful features to assist developers in handling i18n features more easily. For instance, its inline annotation feature allows you to view the translation content associated with the translation key directly :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yb-OB2pmrNA8yS1qzd9sMQ.gif" /></figure><p>*note that although the above and following code examples are demonstrated in .vue files, they will also work for our React Native JSX syntax.</p><p>All-in-one easy management :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GIJ6FC3j43KA4tcfs-_WWQ.png" /></figure><p>Auto-translation :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PziXolThlD8USWqUs1u0oQ.png" /></figure><p><strong>Wrapping up</strong></p><p>That concludes this article, thanks for reading! But if you are interested in more advanced features of react-i18next, such as interpolation, formatting, and context, then be sure to follow me for updates. Cheers!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ea4e0fa5b3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/complete-i18n-guide-to-support-multi-language-for-your-react-native-app-c5ea4e0fa5b3">Complete i18n Guide To Support Multi-Language For Your React Native App</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ultimate Top 9 Most Popular UI Libraries for Every Vue Project]]></title>
            <link>https://medium.com/@reg9295/ultimate-top-9-most-popular-ui-libraries-for-every-vue-project-6f3af5b87e82?source=rss-61c86d937b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f3af5b87e82</guid>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Reg]]></dc:creator>
            <pubDate>Wed, 11 Jan 2023 14:12:55 GMT</pubDate>
            <atom:updated>2023-01-11T14:12:55.851Z</atom:updated>
            <content:encoded><![CDATA[<p>Vue.js as a JavaScript framework, is a great contender to modern JavaScript frameworks such as React.js and Angular.js due to its simplicity, ease of use and learning curve.</p><p>At the core of Vue.js, components play a big role at abstracting away complex logic which makes your Vue.js projects maintainable. UI libraries on the other hand, are collections of beautifully crafted UI components built by professional teams to enable you to build your website in a consistent-looking and optimized way.</p><p>In this article, I have listed the top 9 most popular (in terms of NPM downloads and Github stars, ranked from top to bottom) UI libraries for you to kick start your dream Vue project.</p><p><a href="https://github.com/vuetifyjs/vuetify"><strong>Vuetify</strong></a><strong> (36.2k stars, 400k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUW3t3GTfo5dErodA4h85w.jpeg" /></figure><p>Vuetify is an UI library that is based on Material UI which helps to build beautiful and high-quality digital experience for your website. The advantages of Vuetify include clear documentation, massive community and support for Vue 3 in its latest release.</p><p><a href="https://github.com/quasarframework/quasar"><strong>Quasar</strong></a><strong> (22.7k stars, 112k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaxvQqlcpcWAuOTWgw66fQ.jpeg" /></figure><p>Quasar framework is more than just a UI library, which is intended to provide a consistent, all-in-one UI solution for your mobile app, web app and desktop app.</p><p><a href="https://github.com/element-plus/element-plus"><strong>Element Plus</strong></a><strong> (18.3k stars, 115k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2K8gNs-dfPxZvKsqc1TWAw.jpeg" /></figure><p>As the third most popular UI library, Element Plus provides several features such as support for Vue 3 composition API, integrated Day.js, i18n support for 52 languages and so much more!</p><p><a href="https://github.com/tailwindlabs/headlessui"><strong>Headless UI</strong></a><strong> (18.5k stars, 70k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bm_Hl7szwFMEwWlrDipG-w.jpeg" /></figure><p>Headless UI features completely un-styled, full accessible UI components, designed to integrate beautifully with Tailwind CSS, which means that you are responsible for providing your own markup and styles, to customize the look and feel for your website.</p><p><a href="https://github.com/vueComponent/ant-design-vue"><strong>Ant Design Vue</strong></a><strong> (17.6k stars, 80k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6PRlOz43bRiR8fQGjvQEA.jpeg" /></figure><p>Ant Design Vue — which is backed by the Chines Tech Giant Alibaba Group, is another popular UI library which specializes the e-commerce ‘feel’. Although much of the documentation are translated to English, but some fonts and links still remain in Chinese which you might need to be beware of.</p><p><a href="https://github.com/bootstrap-vue/bootstrap-vue"><strong>Bootstrap Vue</strong></a><strong> (14.2k stars, 361k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P--TPd_0wtSaVRQnnbUYLw.jpeg" /></figure><p>Bootstrap is an extremely popular UI library that is almost known by all frontend developers, which has ported the Vue version of it — Bootstrap Vue that allows you to build responsive, mobile-first and ARIA accessible projects on the web. However, please note that there is no Vue 3 support at the moment.</p><p><a href="https://github.com/tusen-ai/naive-ui"><strong>Naive UI</strong></a><strong> (11.4k stars, 20k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zkp1oCc6FiCckMuBF-oz5g.jpeg" /></figure><p>Naive UI, as a new and promising UI library that has been tweeted by the creator of Vue, has a set of incredibly fast, uniquely-crafted and adaptable UI components, as well as full support for TypeScript and Vue 3.</p><p><a href="https://github.com/buefy/buefy"><strong>Buefy</strong></a><strong> (9.4k stars, 70k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI2NQYWmZlAtIkE6OXBX9g.png" /></figure><p>Buefy is a lightweight (88kb with min + gzip) UI library that follows the principles of Bulma design and some of the Material Design UX. Unlike other UI libraries, Buefy focuses on usability and performance without over-animating stuff. But unfortunately, at the time of writing, there is no support for Vue 3 yet.</p><p><a href="https://github.com/primefaces/primevue"><strong>Primevue</strong></a><strong> (3.2k stars, 60k weekly downloads)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5VzwodnBNR2SlyicOuTQQ.png" /></figure><p>Primevue focuses on preparing you to develop any complicated, and sophisticated website with its well-designed, cutting-edge and dynamic components. Primevue has also been completely rebuilt with Vue 3 in mind.</p><p>That’s all for this article, thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f3af5b87e82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Tips To Help You Write Better JavaScript Code]]></title>
            <link>https://levelup.gitconnected.com/20-tips-and-best-practices-to-write-better-javascript-code-ae7cd249517b?source=rss-61c86d937b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae7cd249517b</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Reg]]></dc:creator>
            <pubDate>Sun, 08 Jan 2023 14:31:55 GMT</pubDate>
            <atom:updated>2023-01-24T15:36:28.810Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nxtcH59ze-Coyne-" /><figcaption>Photo by <a href="https://unsplash.com/@acharki95?utm_source=medium&amp;utm_medium=referral">Aziz Acharki</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a software developer, writing fast and dirty code may be enough to get things started, but writing cleaner and maintainable code will help you and your team to succeed in the long run. In this article, I will share 10 beneficial tips to take your JavaScript skills to the next level.</p><h4>If Statement With Multiple String Conditions</h4><p>The includes method can determine whether an array includes a certain value among its entries, and we can use it to shorten the lengthy if statement with multiple string conditions.</p><pre>// normal way<br>if (msg === &#39;a&#39; || msg === &#39;b&#39; || msg === &#39;c&#39; || msg === &quot;d&quot;) {...}<br><br>// alternative<br>if ([&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;].includes(msg)) {...}</pre><h4>Multi-line Text Strings</h4><p>When we are dealing with multi-line text, instead of typing ugly \n \t and + , we can instead make use of the template literals.</p><pre>// normal way<br>const text = &#39;aaa aaa aaa\n\t&#39;<br> + &#39;bbb bbb bbb\n\t&#39;;<br><br>// alternative<br>const data = `aaa aaa aaa<br>   bbb bbb bbb`;<br></pre><h4>Object Initializer Shorthand</h4><p>When defining an object whose keys have the same names as the variables assigned to them, we can make use of the new ES6 syntax to shorten the property assignments.</p><pre>const a = 1;<br>const b = 2;<br><br>// normal way<br>const obj = {a: a, b: b};<br>// alternative<br>const obj = {a, b};</pre><h4>Use Guard And Fail Fast</h4><p>Nested if statements are always dreadful to look at or debug, but with this technique, we can use ‘guard’ to check for negative conditions and then ‘fail fast’ — meaning to return the value early.</p><p>This technique is even better in situations where we have more if statements than the demonstrated example.</p><pre>// normal way<br>funtion example(a, b, c) {<br>  if (a) {<br>    if (b) {<br>      if (c) {<br>        console.log(&#39;a, b and c are successful!&#39;);<br>      } else {<br>        return null;<br>      }<br>    } else {<br>      return null;<br>    }<br>  } else {<br>    return null;<br>  }<br>}<br><br>// alternative<br>function example(a, b, c) {<br>  if (!a || !b || !c) {  // use guard<br>    return null;  // and &#39;fail fast&#39;<br>  }<br>  console.log(&#39;a, b and c are successful!&#39;);<br>}</pre><h4>Avoid Returning Error Object</h4><p>Returning objects that are deep in multiple layers of functions will make our code harder to maintain, as a single change will have to be reflected back in all related return statements. By throwing errors, we can save ourselves from such scenarios, because error objects will ‘bubble up’ to the nearest catch and try statement.</p><pre>// normal way<br>function example(a, b) {<br>  const res = validateA(a);<br>  if (res.code === 1 || res.code === 2) {<br>    console.log(res.message);<br>    return;<br>  }<br>  // continue...<br>}<br><br>function validateA(a) {<br>  if (a.length &lt; 5) {<br>    return { code: 1, message: &#39;a is too short&#39;};<br>  }<br>  <br>  if (!findAInDatabase(a)) {<br>    return { code: 2, message: &#39;a is already used&#39;};<br>  }<br>}<br>// alternative<br>function example(a, b) {<br>  try {<br>    validateA(a);<br>  } catch (error) {<br>    console.log(error.message)<br>  }<br>  <br>  // continue...<br>}<br>function validateA(a) {<br>  if (a.length &lt; 5) {<br>    throw new Error(&#39;a is too short&#39;);<br>  }<br>  <br>  if (!findAInDatabase(a)) {<br>    throw new Error(&#39;a is already used&#39;)<br>  }<br>}</pre><h4>Function that checks for undefined value</h4><p>If you have a function that checks for undefined and returns null correspondingly, you simplify your code using logical OR operator short-circuit.</p><pre>// normal way<br>function example(a) {<br> if (a !== undefined) {<br>  return a;<br> } else {<br>  return null;<br> }<br>}<br><br>// alternative<br>function example(a) {<br> return a || null;<br>}<br></pre><h4>Repeated Characters</h4><p>Instead of lengthy for loop to concatenate your characters, you can use the repeat method.</p><pre>// normal<br>let text = &#39;&#39;;<br>for (let i = 0; i &lt; 5; i++) {<br> text += &#39;a&#39;;<br>}<br><br>// better<br>let text = &#39;a&#39;.repeat(5);</pre><h4>Exponent</h4><p>Sometimes an integer with lots of trailing zeros can be hard to read, but by using the e (exponent that represents a power of 10), we can effectively reduce our mental load when reading them.</p><pre>// normal way<br>const a = 100000;<br><br>// alternative<br>const a = 1e5;</pre><h4>Power Made Easy</h4><p>The Math.pow method has an alternative way of achieving the same result.</p><pre>// normal<br>Math.pow(2, 5);<br><br>// alternative<br>2**5;</pre><h4>Unique Set</h4><p>The Set object allows you to store unique values of any type, whether they are primitive values or object references. The spread operator can be used to expand the iterable Set object into a new array.</p><pre>[...new Set([1, 2, 3, 1, 1])]; // [1, 2, 3]</pre><p>This concludes my article, and thanks for reading. Cheers!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae7cd249517b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/20-tips-and-best-practices-to-write-better-javascript-code-ae7cd249517b">10 Tips To Help You Write Better JavaScript Code</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Lesser-known React Functional Component Optimization Techniques]]></title>
            <link>https://medium.com/@reg9295/3-lesser-known-react-functional-component-optimization-techniques-bba814d0e679?source=rss-61c86d937b88------2</link>
            <guid isPermaLink="false">https://medium.com/p/bba814d0e679</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[optimization-techniques]]></category>
            <dc:creator><![CDATA[Reg]]></dc:creator>
            <pubDate>Thu, 05 Jan 2023 12:03:41 GMT</pubDate>
            <atom:updated>2023-01-16T11:35:11.385Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g-ho31Jc-Ka8OwiVvvgTZA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@maartendeckers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Maarten Deckers</a> on <a href="https://unsplash.com/s/photos/architecture?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you stumble upon this post, chances are, you are already familiar with some of the more common React optimization techniques, such as <a href="https://reactjs.org/docs/hooks-reference.html#usecallback">useCallback</a>, <a href="https://reactjs.org/docs/hooks-reference.html#usememo">useMemo</a> and <a href="https://reactjs.org/docs/react-api.html#reactmemo">React.memo</a> to reduce the number of unnecessary re-rendering performed; <a href="https://github.com/bvaughn/react-window">react-window</a> and <a href="https://github.com/twobin/react-lazyload">react-lazyload</a> libraries to lazy load large amount of items in a list / table or images, to avoid unused off-screen DOM elements from being created.</p><p>But in this article, we are going to focus on some of the lesser-known React optimization techniques (well, at least I don’t recall seeing them much on the web).</p><ol><li><strong>Lazy initial state</strong></li></ol><pre>const [state, setState] = useState(expensiveFn());</pre><p>Normally, when you have a computationally expensive function to return the initial state result, the same function will run for any subsequent re-render caused by the state dispatch function.</p><p>This is suboptimal because the expensive function is only needed to run for the initial state result right?</p><pre>const [state, setState] = useState(() =&gt; expensiveFn());</pre><p>To solve the issue, you may provide an arrow function that runs the expensive function instead. Now React will only call the expensive function during first render, and creates a new function for subsequent re-renders (note that we are NOT running the expensive function inside the arrow function anymore, and creating a new function is far cheaper than calling what is inside of it).</p><pre>const [state, setState] = useState(() =&gt; &#39;Hello World!&#39;);</pre><p>However, note that if the initial state is not involving some heavy computation, then it’s ok to not use lazy initialization, as it’s not that expensive to re-create the same value during re-renders.</p><p><strong>2. React.fragment to avoid adding extra HTML tags</strong></p><pre>function Example() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello&lt;/h1&gt;<br>      &lt;p&gt;medium is the best!&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>React functional component can only return a single HTML element, thus sometimes we have to add a new pair of HTML tags (e.g &lt;div&gt; tags) to enclose all other elements to fulfill React’s rule, this however introduces another tag to re-render.</p><p>However, we can replace the extra HTML tags with React fragment, which does not introduce any extra tag to render and fulfill React’s rule at the same time.</p><p>The syntax goes like this :</p><pre>function Example() {<br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Hello&lt;/h1&gt;<br>      &lt;p&gt;medium is the best!&lt;/p&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>or alternatively :</p><pre>function Example() {<br>  return (<br>    &lt;React.fragment&gt;<br>      &lt;h1&gt;Hello&lt;/h1&gt;<br>      &lt;p&gt;medium is the best!&lt;/p&gt;<br>    &lt;/React.fragment&gt;<br>  );<br>}</pre><p><strong>3. State colocation</strong></p><p><strong>State colocation</strong> in React refers to keeping the states as close as to where they are actually needed, but what does it have to do with optimization?</p><pre>function Example() {<br>  const [text, setText] = useState(0);<br><br>  function onChange(e) {<br>    setText(e.target.value)<br>  }<br><br>  return (<br>    &lt;&gt;<br>      &lt;SimpleInput text={text} onChange={onChange}  /&gt;<br>      &lt;ExpensiveComponent /&gt;<br>    &lt;/&gt;<br><br>  )<br><br>}<br><br>function SimpleInput({text, onChange}) {<br>  return (<br>    &lt;&gt;<br>      &lt;input value={text} onChange={(e) =&gt; onChange(e)} /&gt;<br>    &lt;/&gt;<br>  );<br>}<br><br>function ExpensiveComponent({}) {<br>  const expensiveFn = () =&gt; {<br>    for (let i = 0; i &lt; 100000000; i++) {<br>      // nothing<br>    }<br>  };<br><br>  expensiveFn();<br><br>  return &lt;div&gt;slow&lt;/div&gt;;<br>}</pre><p>Take the above code for example, every time the state ‘text’ is updated in the parent component, React will have to go through all of its child components (i.e ‘SimpleInput’ and ‘ExpensiveComponent’ components) to check if DOM manipulation is needed or not, this reduces performance significantly if you have a super expensive component like the ‘ExpensiveComponent’ component.</p><p>To avoid unnecessary checking on the expensive child component, we can co-locate the ‘text’ state to ‘SimpleInput’ component, where it is actually needed, just like the code example below :</p><pre>function Example() {<br>  return (<br>    &lt;&gt;<br>      &lt;SimpleInput /&gt;<br>      &lt;ExpensiveComponent /&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>function SimpleInput({text, onChange}) {<br>  const [text, setText] = useState(0);<br><br>  function onChange(e) {<br>    setText(e.target.value)<br>  }<br><br>  return (<br>    &lt;input value={text} onChange={(e) =&gt; onChange(e)} /&gt;<br>  );<br>}<br><br>function ExpensiveComponent({}) {<br>  const expensiveFn = () =&gt; {<br>    for (let i = 0; i &lt; 100000000; i++) {<br>      // nothing<br>    }<br>  };<br><br>  expensiveFn();<br><br>  return &lt;div&gt;slow&lt;/div&gt;;<br>}</pre><p><strong>Wrapping up</strong></p><p>This sums up the 3 techniques for React optimization, hope you learn something today, and any suggestions for improvement are welcomed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bba814d0e679" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>