<?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 Anumothu Rajendran on Medium]]></title>
        <description><![CDATA[Stories by Anumothu Rajendran on Medium]]></description>
        <link>https://medium.com/@anumothurajendran?source=rss-8e23d382d6bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zb90kFUYqD3NMO5C.</url>
            <title>Stories by Anumothu Rajendran on Medium</title>
            <link>https://medium.com/@anumothurajendran?source=rss-8e23d382d6bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:59:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anumothurajendran/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[ Mastering React Rendering: A Practical Guide to memo, useMemo, useCallback, and useState]]></title>
            <link>https://medium.com/@anumothurajendran/mastering-react-rendering-a-practical-guide-to-memo-usememo-usecallback-and-usestate-2df2b998f016?source=rss-8e23d382d6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df2b998f016</guid>
            <dc:creator><![CDATA[Anumothu Rajendran]]></dc:creator>
            <pubDate>Mon, 08 Dec 2025 11:24:51 GMT</pubDate>
            <atom:updated>2025-12-08T11:26:17.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔥 Mastering React Rendering: A Practical Guide to memo, useMemo, useCallback, and useState (With a Real Demo)</h3><p>If you’ve ever wondered <em>“Why is my React component re-rendering even when the props didn’t change?”</em> — this article will make everything crystal clear. We’re going to walk through a real working demo, see how React rendering actually works, and then fix unnecessary re-renders step-by-step using React.memo, useMemo, and useCallback.</p><p>By the end, you’ll <strong>understand React’s rendering behavior deeply</strong>, not just memorize definitions.</p><p>Let’s begin. 🚀</p><p><strong>Understanding the Problem: Why React Re-renders More Than You Expect</strong></p><p>Here’s the unoptimized version of our simple component:</p><ul><li>A counter button</li><li>Two child components &lt;A /&gt; and &lt;B /&gt;</li><li>An input field</li><li>Some logs inside components to track rendering</li></ul><p><strong>Initial Code (No Memoization)</strong></p><pre>import React, { useState } from &quot;react&quot;;<br>export default function MyApp() {<br>  const [count, setCount] = useState(0);<br>  const [inputValue, setInputValue] = useState(&quot;&quot;);<br><br>  const user = {<br>    name: &quot;Alice&quot;,<br>  };<br><br>  const handleChange = (event) =&gt; {<br>    setInputValue(event.target.value);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setCount((c) =&gt; c + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;A user={user} /&gt;<br>      &lt;B text={inputValue} onChange={handleChange} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>const A = ({ user }) =&gt; {<br>  console.log(&quot;A rendered&quot;, user);<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>};<br><br>const B = ({ text, onChange }) =&gt; {<br>  console.log(&quot;B rendered&quot;, text);<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      id=&quot;my-text-input&quot;<br>      value={text}<br>      onChange={onChange}<br>      placeholder=&quot;Type something here...&quot;<br>    /&gt;<br>  );<br>};</pre><pre>┌──────────────────────────┐<br>│        MyApp (parent)    │<br>└──────────────┬───────────┘<br>               │ re-render<br>    ┌──────────┴─────────────┐<br>    │                        │<br>┌───────┐               ┌────────┐<br>│   A   │               │   B    │<br>└───────┘               └────────┘<br>  re-render               re-render<br> (user object recreated) (function recreated)</pre><h3>🔍 What Happens When You Click “Increment”?</h3><p>React re-renders the parent component (MyApp).<br> But because we recreated:</p><ul><li>user → new object</li><li>handleChange → new function</li></ul><p>…both &lt;A /&gt; and &lt;B /&gt; re-render too.</p><p>Even though user.name is still &quot;Alice&quot;.</p><h3>💡 Why?</h3><p>Because <strong>React compares props by reference</strong>, not value.</p><p>{ name: &quot;Alice&quot; } !== { name: &quot;Alice&quot; }<br> Two objects with the same content are still different references.</p><p>So every render = new object = new prop = new render.</p><h3>🚀 Step-by-Step Optimization Using React’s Tools</h3><p>Here’s the optimized version using:</p><ul><li>React.memo → avoid re-render if props didn’t change</li><li>useMemo → stabilize object references</li><li>useCallback → stabilize function references</li></ul><p><strong>Lets Start our Optimization</strong></p><h3>React.memo(Component)</h3><p>Wraps a component and re-renders it <strong>only if its props changed</strong> (shallow compare). Wrap our child components using React.memo</p><pre>const A = React.memo(({ user }) =&gt; {<br>  console.log(&quot;A rendered&quot;, user);<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>});<br><br>const B = React.memo(({ text, onChange }) =&gt; {<br>  console.log(&quot;B rendered&quot;, text);<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      id=&quot;my-text-input&quot;<br>      value={text}<br>      onChange={onChange}<br>      placeholder=&quot;Type something here...&quot;<br>    /&gt;<br>  );<br>});</pre><p>If props look like this:</p><ul><li>primitive values → compared by value</li><li>objects/functions → compared by reference</li></ul><p>That’s why we needed stable references.</p><h3>useMemo(factory, deps)</h3><p>Memoizes a <strong>value</strong>. Now our object memorized. So when the parent gets render, Component A wont.</p><pre>const user = useMemo(() =&gt; ({ name: &quot;Alice&quot; }), []);</pre><ul><li>The factory runs once</li><li>The object reference stays the same until deps change</li></ul><p>Perfect for passing objects as props.</p><h3>useCallback(fn, deps)</h3><p>Memoizes a <strong>function reference</strong>. Our handleChange function will be memorized.</p><pre>const handleChange = useCallback((e) =&gt; {<br>  setInputValue(e.target.value);<br>}, []);</pre><p>Without this, a new function is created every render → child re-renders unnecessarily.</p><p>Our Final Optimized Code</p><pre>import React, { memo, useCallback, useMemo, useState } from &quot;react&quot;;<br>export default function MyApp() {<br>  const [count, setCount] = useState(0);<br>  const [inputValue, setInputValue] = useState(&quot;&quot;);<br><br>  const user = useMemo(<br>    () =&gt; ({<br>      name: &quot;Alice&quot;,<br>    }),<br>    []<br>  );<br><br>  const handleChange = useCallback((event) =&gt; {<br>    setInputValue(event.target.value);<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setCount((c) =&gt; c + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;A user={user} /&gt;<br>      &lt;B text={inputValue} onChange={handleChange} /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>const A = React.memo(({ user }) =&gt; {<br>  console.log(&quot;A rendered&quot;, user);<br>  return &lt;div&gt;{user.name}&lt;/div&gt;;<br>});<br><br>const B = React.memo(({ text, onChange }) =&gt; {<br>  console.log(&quot;B rendered&quot;, text);<br>  return (<br>    &lt;input<br>      type=&quot;text&quot;<br>      id=&quot;my-text-input&quot;<br>      value={text}<br>      onChange={onChange}<br>      placeholder=&quot;Type something here...&quot;<br>    /&gt;<br>  );<br>});</pre><pre>┌──────────────────────────────┐<br>│            MyApp             │<br>└───────────────┬──────────────┘<br>                │ re-render<br>       ┌────────┴─────────┐<br>       │                  │<br>┌───────────┐       ┌───────────┐<br>│     A     │       │     B     │<br>└───────────┘       └───────────┘<br>   does NOT            does NOT<br>    re-render           re-render<br> (stable object)     (stable function)</pre><h3>🎉 Now Observe the Magic</h3><h3>🔸 On Increment click</h3><ul><li>count changes → parent re-renders</li><li>But <strong>user does NOT change</strong> → A does NOT re-render</li><li>And <strong>handleChange is stable</strong> → B does NOT re-render</li></ul><h3>🔸 When typing in the input</h3><ul><li>Only &lt;B /&gt; re-renders</li><li>&lt;A /&gt; stays untouched</li></ul><p>You <em>just prevented unnecessary renders</em> — the heart of React performance tuning.</p><h3><strong>Conclusion</strong></h3><h4>Before Optimization</h4><p>Click Increment → A re-renders<br> Click Increment → B re-renders<br> Type input → both re-render</p><h4>After Optimization</h4><p>Click Increment → <strong>no children re-render</strong><br> Type input → <strong>only B re-renders</strong></p><p>Massive win. 🎯</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df2b998f016" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Health Connect — React Native CLI— Android]]></title>
            <link>https://medium.com/@anumothurajendran/google-health-connect-react-native-cli-android-7c7c4c533a75?source=rss-8e23d382d6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c7c4c533a75</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[health-connect]]></category>
            <dc:creator><![CDATA[Anumothu Rajendran]]></dc:creator>
            <pubDate>Fri, 19 Jul 2024 19:35:19 GMT</pubDate>
            <atom:updated>2024-07-19T19:35:19.005Z</atom:updated>
            <content:encoded><![CDATA[<h3>Google Health Connect — React Native CLI— Android</h3><h3>Introduction</h3><p>With the continuous evolution of health and fitness applications, keeping up with the latest integrations is essential for providing accurate and comprehensive data to users. Initially, many developers relied on Google Fit to gather health-related data. However, Google has recently transitioned to Health Connect, a more robust solution for health data integration. This blog post will guide you through the process of integrating Google Health Connect into your React Native project.</p><h3>Prerequisites</h3><p>Before diving into the integration steps, ensure that your development environment meets the following requirements:</p><ol><li><strong>React Native version</strong>: 0.71 or higher</li><li><strong>Android Target SDK</strong>: 34</li><li><strong>Health Connect App</strong>:</li></ol><ul><li>If your device is running Android 14 or higher, Health Connect comes bundled with the Android package.</li><li>For devices running versions below Android 14, you will need to install the Health Connect app separately.</li></ul><p><strong>4. Google Play Submission</strong>: If you plan to submit your app to the Google Play Store, you need to complete and submit a declaration form for approval.</p><h3>Step-by-Step Integration</h3><h3>Step 1: Install the Package</h3><p>In your React Native project, install the react-native-health-connect package using Yarn:</p><pre>yarn add react-native-health-connect</pre><h3>Step 2: Modify the MainActivity File</h3><p>Depending on whether your MainActivity is in Kotlin or Java, follow the appropriate instructions below.</p><h4>For Kotlin:</h4><p>Add the following code to your MainActivity:</p><pre>package com.healthconnectexample<br><br>+ import android.os.Bundle<br>import com.facebook.react.ReactActivity<br>import com.facebook.react.ReactActivityDelegate<br>import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled<br>import com.facebook.react.defaults.DefaultReactActivityDelegate<br>+ import dev.matinzd.healthconnect.permissions.HealthConnectPermissionDelegate<br><br>class MainActivity : ReactActivity() {<br>    /**<br>     * Returns the name of the main component registered from JavaScript. This is used to schedule<br>     * rendering of the component.<br>     */<br>    override fun getMainComponentName(): String = &quot;HealthConnectExample&quot;<br><br>+ override fun onCreate(savedInstanceState: Bundle?) {<br>+   super.onCreate(savedInstanceState)<br>+   // In order to handle permission contract results, we need to set the permission delegate.<br>+   HealthConnectPermissionDelegate.setPermissionDelegate(this)<br>+ }<br><br>    /**<br>     * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]<br>     * which allows you to enable New Architecture with a single boolean flags [fabricEnabled]<br>     */<br>    override fun createReactActivityDelegate(): ReactActivityDelegate =<br>        DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)<br>}</pre><p>For Java</p><pre>package com.healthconnectexample;<br><br>+ import android.os.Bundle;<br>import com.facebook.react.ReactActivity;<br>+ import dev.matinzd.healthconnect.permissions.HealthConnectPermissionDelegate;<br><br>public class MainActivity extends ReactActivity {<br>    @Override<br>    protected void onCreate(Bundle savedInstanceState) {<br>        super.onCreate(null);<br> +       HealthConnectPermissionDelegate.INSTANCE.setPermissionDelegate(this, &quot;com.google.android.apps.healthdata&quot;);<br>    }<br><br>    @Override<br>    protected String getMainComponentName() {<br>        return &quot;HealthConnectExample&quot;;<br>    }<br>}</pre><h3>Step 3: Update the Android Manifest</h3><p>In your AndroidManifest.xml file, add the following permissions and activities:</p><pre>&lt;uses-permission android:name=&quot;android.permission.health.READ_HEART_RATE&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.health.WRITE_HEART_RATE&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.health.READ_STEPS&quot;/&gt;<br>&lt;uses-permission android:name=&quot;android.permission.health.WRITE_STEPS&quot;/&gt;<br><br>&lt;queries&gt;<br>    &lt;package android:name=&quot;com.google.android.apps.healthdata&quot; /&gt;<br>&lt;/queries&gt;<br><br>&lt;application&gt;<br>    &lt;!-- For supported versions through Android 13, create an activity to show the rationale<br>         of Health Connect permissions once users click the privacy policy link. --&gt;<br>    &lt;activity<br>        android:name=&quot;.PermissionsRationaleActivity&quot;<br>        android:exported=&quot;true&quot;&gt;<br>        &lt;intent-filter&gt;<br>            &lt;action android:name=&quot;androidx.health.ACTION_SHOW_PERMISSIONS_RATIONALE&quot; /&gt;<br>        &lt;/intent-filter&gt;<br>    &lt;/activity&gt;<br><br>    &lt;!-- For versions starting Android 14, create an activity alias to show the rationale<br>         of Health Connect permissions once users click the privacy policy link. --&gt;<br>    &lt;activity-alias<br>        android:name=&quot;ViewPermissionUsageActivity&quot;<br>        android:exported=&quot;true&quot;<br>        android:targetActivity=&quot;.PermissionsRationaleActivity&quot;<br>        android:permission=&quot;android.permission.START_VIEW_PERMISSION_USAGE&quot;&gt;<br>        &lt;intent-filter&gt;<br>            &lt;action android:name=&quot;android.intent.action.VIEW_PERMISSION_USAGE&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.HEALTH_PERMISSIONS&quot; /&gt;<br>        &lt;/intent-filter&gt;<br>    &lt;/activity-alias&gt;<br>&lt;/application&gt;</pre><h3>Step 4: Implement Health Connect in React Native</h3><ol><li><strong>Create a HealthManager.js file</strong></li><li><strong>Import the package and respective functions</strong>:</li></ol><pre>import {<br>  initialize,<br>  requestPermission,<br>  readRecords,<br>  getGrantedPermissions,<br>  getSdkStatus,<br>  revokeAllPermissions,<br>} from &#39;react-native-health-connect&#39;;</pre><p><strong>3. Initialize Health Connect</strong>:</p><pre>export const init = async () =&gt; {<br>  await initialize();<br>};</pre><p>4. <strong>Check if the SDK is available</strong>:</p><pre>export const isAvailable = async () =&gt; {<br>  const res = await getSdkStatus();<br>  if (res === 1) {<br>    return { status: false, message: &quot;SDK unavailable&quot; };<br>  } else if (res === 2) {<br>    return { status: false, message: &quot;SDK update required&quot; };<br>  } else if (res === 3) {<br>    return { status: true, message: &quot;Health Connect available&quot; };<br>  }<br>};</pre><p>5. <strong>Declare the permissions you want to request</strong>:</p><pre>export const getPermission = async () =&gt;<br>  new Promise((resolve, reject) =&gt; {<br>    requestPermission([<br>      { accessType: &#39;read&#39;, recordType: &#39;TotalCaloriesBurned&#39; },<br>      { accessType: &#39;read&#39;, recordType: &#39;Steps&#39; },<br>      { accessType: &#39;read&#39;, recordType: &#39;HeartRate&#39; },<br>      { accessType: &#39;read&#39;, recordType: &#39;Distance&#39; },<br>      { accessType: &#39;read&#39;, recordType: &#39;SleepSession&#39; },<br>    ])<br>      .then(permissions =&gt; {<br>        console.log(&#39;Requested permissions:&#39;, permissions);<br>        resolve(permissions.length &gt; 0);<br>      })<br>      .catch(e =&gt; {<br>        reject(Error(e.message));<br>      });<br>  });</pre><p>Once you initiate the permission request, the app will show a popup for users to grant permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*LFDdKBLJpMfrlRoNV6G39Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXvN9shMLPzwMTQZkYJR2Q.png" /></figure><p><strong>6. Read Health Data</strong>:</p><pre>const result = await readRecords(&#39;Steps&#39;, {<br>  timeRangeFilter: {<br>    operator: &#39;between&#39;,<br>    startTime: date,<br>    endTime: new Date().toISOString(),<br>  },<br>});<br>console.log(&#39;Health data:&#39;, result);</pre><p>The response will be like,</p><pre>[<br>  {<br>    &quot;count&quot;: 30,<br>    &quot;endTime&quot;: &quot;2024-07-19T03:44:54.899Z&quot;,<br>    &quot;metadata&quot;: {<br>      &quot;clientRecordId&quot;: null,<br>      &quot;clientRecordVersion&quot;: 0,<br>      &quot;dataOrigin&quot;: &quot;com.google.android.apps.fitness&quot;,<br>      &quot;device&quot;: 0,<br>      &quot;id&quot;: &quot;ffbd88ae-c7f1-4f52-ad2f-a4dbad3f0132&quot;,<br>      &quot;lastModifiedTime&quot;: &quot;2024-07-19T03:55:49.557Z&quot;,<br>      &quot;recordingMethod&quot;: 0<br>    },<br>    &quot;startTime&quot;: &quot;2024-07-19T03:43:54.898Z&quot;<br>  }]</pre><p>Thats it. The integration is completed. You can follow more details here</p><p><a href="https://matinzd.github.io/react-native-health-connect/docs/intro/">Introduction | React Native Health Connect</a></p><h3>Conclusion</h3><p>By following these steps, you can integrate Google Health Connect into your React Native application, ensuring you can access and manage health-related data seamlessly. For more detailed information and advanced configurations, refer to the official <a href="https://developer.android.com/health-and-fitness/guides/health-connect/develop/get-started">Google Health Connect documentation</a>.</p><p>Stay updated with the latest developments in health tech and continue to provide your users with the best possible experience!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c7c4c533a75" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Destructuring Props Vs Props Object in React / React Native]]></title>
            <link>https://medium.com/@anumothurajendran/destructuring-props-vs-props-obect-in-react-react-native-2fe8c66ea279?source=rss-8e23d382d6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fe8c66ea279</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Anumothu Rajendran]]></dc:creator>
            <pubDate>Mon, 15 Jul 2024 13:33:18 GMT</pubDate>
            <atom:updated>2025-12-08T11:27:21.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*mz-hlONvgbDPKChSo-yrzg.png" /></figure><p>When building React components, passing data through props is a common practice. However, developers often debate whether to destructure props directly in the function signature or to use the props object inside the function body. In this article, we’ll explore both approaches, discuss their pros and cons, and provide code examples to illustrate best practices.</p><h3>Why Props Matter</h3><p>Props are the primary way to pass data from parent to child components in React. They make components reusable and maintainable by allowing you to customize the behavior and appearance of each instance.</p><h3>Destructuring Props Directly in the Function Signature</h3><pre>const MyComponent = ({ text, label, placeholder }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{label}&lt;/label&gt;<br>      &lt;input type=&quot;text&quot; placeholder={placeholder} value={text} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>text, label, placeholder — restructuring the properties from the props</p><h4>Pros</h4><ul><li><strong>Readability</strong>: It’s immediately clear which props the component expects.</li><li><strong>Less Boilerplate</strong>: You don’t need to prefix each prop with props..</li><li><strong>Autocomplete</strong>: Modern IDEs and code editors provide better autocomplete support.</li></ul><h4>Cons</h4><ul><li><strong>Function Signature Length</strong>: If the component has many props, the function signature can become lengthy.</li><li><strong>Default Values</strong>: You may need additional syntax to provide default values.</li></ul><h3>Using the props Object</h3><pre>const MyComponent = (props) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{props.label}&lt;/label&gt;<br>      &lt;input type=&quot;text&quot; placeholder={props.placeholder} value={props.text} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h4>Pros</h4><ul><li><strong>Simplicity</strong>: The function signature remains short regardless of the number of props.</li><li><strong>Flexibility</strong>: Easy to pass the entire props object to child components if needed.</li></ul><h4>Cons</h4><ul><li><strong>Readability</strong>: It’s less clear which props are being used.</li><li><strong>Repetition</strong>: You need to prefix each prop with props..</li><li>setting the default value is hard.</li></ul><h3>Best Practice: Combining Approaches</h3><p>For optimal readability and maintainability, you can combine both approaches. Destructure the props inside the function body to keep the function signature clean while still benefiting from restructuring.</p><pre>const MyComponent = (props) =&gt; {<br>  const { text, label} = props;<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{label}&lt;/label&gt;<br>      &lt;input type=&quot;text&quot; placeholder={props.placeholder} value={text} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>Providing Default Values for Optional Fields</p><pre>const MyComponent = (props) =&gt; {<br>  const { text, label = &#39;title&#39;} = props;<br>  <br>  return (<br>    &lt;div&gt;<br>      &lt;label&gt;{label}&lt;/label&gt;<br>      &lt;input type=&quot;text&quot; placeholder={props.placeholder} value={text} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Conclusion</h3><p>Both approaches to passing props have their merits. Destructuring directly in the function signature is excellent for readability and simplicity, while using the props object offers flexibility and a cleaner function signature. Combining these approaches allows you to take advantage of the benefits of both. By following these best practices, you can write more readable, maintainable, and robust React components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fe8c66ea279" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a React Native App with SQLite — Clean Code Structure]]></title>
            <link>https://medium.com/@anumothurajendran/building-a-react-native-app-with-sqlite-clean-code-structure-a07152213291?source=rss-8e23d382d6bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/a07152213291</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[solid]]></category>
            <dc:creator><![CDATA[Anumothu Rajendran]]></dc:creator>
            <pubDate>Thu, 20 Jun 2024 03:06:33 GMT</pubDate>
            <atom:updated>2024-06-20T03:06:33.043Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a React Native App with SQLite — Clean Code Structure</h3><p>In this tutorial, we’ll build a React Native app that uses SQLite for managing tasks and reports. We’ll structure the code using the SOLID principles, service layers, and hooks. We’ll also keep our SQL queries in a separate .sql file for better maintainability.</p><p>In this tutorial, we will focus on task and report management. We will use three tables: User, Task, and Report. Based on these, we will create React Native code.</p><h3>Project Setup</h3><p>First, let’s set up the project structure:</p><p>my-react-native-app/<br>├── node_modules/<br>├── public/<br>├── src/<br>│ ├── components/<br>│ │ ├── TaskList.js<br>│ │ └── Report.js<br>│ ├── hooks/<br>│ │ ├── useTasks.js<br>│ │ └── useReports.js<br>│ ├── services/<br>│ │ ├── database.js<br>│ │ ├── taskService.js<br>│ │ └── reportService.js<br>│ ├── sql/<br>│ │ └── create_tables.sql<br>│ ├── App.js<br>│ ├── index.js<br>│ └── config.js<br>├── package.json<br>└── README.md</p><h3>Step 1: Create SQL File</h3><p>Create a file named create_tables.sql inside the src/sql/ directory with the following content:</p><pre>CREATE TABLE IF NOT EXISTS Users (<br>  id INTEGER PRIMARY KEY AUTOINCREMENT,<br>  name TEXT,<br>  email TEXT,<br>  role TEXT<br>);<br><br>CREATE TABLE IF NOT EXISTS Tasks (<br>  id INTEGER PRIMARY KEY AUTOINCREMENT,<br>  name TEXT,<br>  assignee TEXT,<br>  assigned DATE,<br>  status TEXT<br>);<br><br>CREATE TABLE IF NOT EXISTS Reports (<br>  id INTEGER PRIMARY KEY AUTOINCREMENT,<br>  date DATE,<br>  total_assigned_tasks INTEGER,<br>  total_completed_tasks INTEGER<br>);</pre><h3>Step 2: Create Configuration File</h3><p>Create a file named config.js inside the src/ directory with the following content:</p><pre>export const DATABASE_NAME = &#39;TaskApp.db&#39;;<br>export const SQL_FILE_PATH = &#39;./src/sql/create_tables.sql&#39;;</pre><p><strong>Install needed Package</strong></p><pre>npm install react-native-fs react-native-sqlite-storage</pre><h3>Step 3: Initialize the Database</h3><p>Create a file named database.js inside the src/services/ directory with the following content:</p><pre>import SQLite from &#39;react-native-sqlite-storage&#39;;<br>import RNFS from &#39;react-native-fs&#39;;<br>import { DATABASE_NAME, SQL_FILE_PATH } from &#39;../config&#39;;<br><br>const db = SQLite.openDatabase(<br>  { name: DATABASE_NAME, location: &#39;default&#39; },<br>  () =&gt; console.log(&#39;Database opened&#39;),<br>  error =&gt; console.log(&#39;Error: &#39;, error)<br>);<br><br>const readSQLFile = async () =&gt; {<br>  try {<br>    const sqlFileContent = await RNFS.readFile(SQL_FILE_PATH, &#39;utf8&#39;);<br>    return sqlFileContent;<br>  } catch (error) {<br>    console.error(&#39;Error reading SQL file:&#39;, error);<br>  }<br>};<br><br>export const initializeDatabase = async () =&gt; {<br>  const sqlFileContent = await readSQLFile();<br>  db.transaction(tx =&gt; {<br>    sqlFileContent.split(&#39;;&#39;).forEach(query =&gt; {<br>      if (query.trim()) {<br>        tx.executeSql(query);<br>      }<br>    });<br>  });<br>};<br><br>export default db;</pre><h3>Step 4: Create Services for Tasks and Reports</h3><h4>Task Service</h4><p>Create a file named taskService.js inside the src/services/ directory with the following content:</p><pre>import db from &#39;./database&#39;;<br><br>export const addTask = (task) =&gt; {<br>  db.transaction(tx =&gt; {<br>    tx.executeSql(<br>      &#39;INSERT INTO Tasks (name, assignee, assigned, status) VALUES (?, ?, ?, ?)&#39;,<br>      [task.name, task.assignee, task.assigned, task.status]<br>    );<br>  });<br>};<br><br>export const getTasks = (callback) =&gt; {<br>  db.transaction(tx =&gt; {<br>    tx.executeSql(<br>      &#39;SELECT * FROM Tasks&#39;,<br>      [],<br>      (tx, results) =&gt; {<br>        const tasks = [];<br>        for (let i = 0; i &lt; results.rows.length; i++) {<br>          tasks.push(results.rows.item(i));<br>        }<br>        callback(tasks);<br>      }<br>    );<br>  });<br>};</pre><h4>Report Service</h4><p>Create a file named reportService.js inside the src/services/ directory with the following content:</p><pre>import db from &#39;./database&#39;;<br><br>export const addReport = (report) =&gt; {<br>  db.transaction(tx =&gt; {<br>    tx.executeSql(<br>      &#39;INSERT INTO Reports (date, total_assigned_tasks, total_completed_tasks) VALUES (?, ?, ?)&#39;,<br>      [report.date, report.total_assigned_tasks, report.total_completed_tasks]<br>    );<br>  });<br>};<br><br>export const getReports = (callback) =&gt; {<br>  db.transaction(tx =&gt; {<br>    tx.executeSql(<br>      &#39;SELECT * FROM Reports&#39;,<br>      [],<br>      (tx, results) =&gt; {<br>        const reports = [];<br>        for (let i = 0; i &lt; results.rows.length; i++) {<br>          reports.push(results.rows.item(i));<br>        }<br>        callback(reports);<br>      }<br>    );<br>  });<br>};</pre><h3>Step 5: Create Hooks for Tasks and Reports</h3><h4>Hook for Tasks</h4><p>Create a file named useTasks.js inside the src/hooks/ directory with the following content:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { getTasks } from &#39;../services/taskService&#39;;<br><br>export const useTasks = () =&gt; {<br>  const [tasks, setTasks] = useState([]);<br><br>  useEffect(() =&gt; {<br>    getTasks(setTasks);<br>  }, []);<br><br>  return tasks;<br>};</pre><h4>Hook for Reports</h4><p>Create a file named useReports.js inside the src/hooks/ directory with the following content:</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import { getReports } from &#39;../services/reportService&#39;;<br><br>export const useReports = () =&gt; {<br>  const [reports, setReports] = useState([]);<br><br>  useEffect(() =&gt; {<br>    getReports(setReports);<br>  }, []);<br><br>  return reports;<br>};</pre><h3>Step 6: Create Components for Task List and Report</h3><h4>Task List Component</h4><p>Create a file named TaskList.js inside the src/components/ directory with the following content:</p><pre>import React from &#39;react&#39;;<br>import { View, Text, FlatList } from &#39;react-native&#39;;<br>import { useTasks } from &#39;../hooks/useTasks&#39;;<br><br>const TaskList = () =&gt; {<br>  const tasks = useTasks();<br><br>  return (<br>    &lt;FlatList<br>      data={tasks}<br>      keyExtractor={item =&gt; item.id.toString()}<br>      renderItem={({ item }) =&gt; (<br>        &lt;View&gt;<br>          &lt;Text&gt;{item.name}&lt;/Text&gt;<br>          &lt;Text&gt;{item.assignee}&lt;/Text&gt;<br>          &lt;Text&gt;{item.assigned}&lt;/Text&gt;<br>          &lt;Text&gt;{item.status}&lt;/Text&gt;<br>        &lt;/View&gt;<br>      )}<br>    /&gt;<br>  );<br>};<br><br>export default TaskList;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*whA2WGwiyHrzI47J8J6X0Q.png" /></figure><h4>Report Component</h4><p>Create a file named Report.js inside the src/components/ directory with the following content:</p><pre>import React from &#39;react&#39;;<br>import { View, Text, FlatList } from &#39;react-native&#39;;<br>import { useReports } from &#39;../hooks/useReports&#39;;<br><br>const Report = () =&gt; {<br>  const reports = useReports();<br><br>  return (<br>    &lt;FlatList<br>      data={reports}<br>      keyExtractor={item =&gt; item.id.toString()}<br>      renderItem={({ item }) =&gt; (<br>        &lt;View&gt;<br>          &lt;Text&gt;{item.date}&lt;/Text&gt;<br>          &lt;Text&gt;Total Assigned Tasks: {item.total_assigned_tasks}&lt;/Text&gt;<br>          &lt;Text&gt;Total Completed Tasks: {item.total_completed_tasks}&lt;/Text&gt;<br>        &lt;/View&gt;<br>      )}<br>    /&gt;<br>  );<br>};<br><br>export default Report;</pre><h3>Step 7: Create the Main Application File</h3><p>Create a file named App.js inside the src/ directory with the following content:</p><pre>import React, { useEffect } from &#39;react&#39;;<br>import { View } from &#39;react-native&#39;;<br>import TaskList from &#39;./components/TaskList&#39;;<br>import Report from &#39;./components/Report&#39;;<br>import { initializeDatabase } from &#39;./services/database&#39;;<br><br>const App = () =&gt; {<br>  useEffect(() =&gt; {<br>    initializeDatabase();<br>  }, []);<br><br>  return (<br>    &lt;View&gt;<br>      &lt;TaskList /&gt;<br>      &lt;Report /&gt;<br>    &lt;/View&gt;<br>  );<br>};<br><br>export default App;</pre><h3>Step 8: Initialize the Application</h3><p>Create a file named index.js inside the src/ directory with the following content:</p><pre>import { AppRegistry } from &#39;react-native&#39;;<br>import App from &#39;./App&#39;;<br>import { name as appName } from &#39;./app.json&#39;;<br><br>AppRegistry.registerComponent(appName, () =&gt; App);</pre><h3>Conclusion</h3><p>By following this tutorial, you now have a React Native app that uses SQLite for managing tasks and reports. The app structure follows the SOLID principles, with separate service layers and hooks for managing data. All SQL queries are kept in a separate .sql file for better maintainability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a07152213291" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>