<?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 Aravind Madhusudhanan Nair on Medium]]></title>
        <description><![CDATA[Stories by Aravind Madhusudhanan Nair on Medium]]></description>
        <link>https://medium.com/@aravindmnair?source=rss-fc5f64040a2e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ktj--D5i90TCMn3ktp9ThQ.jpeg</url>
            <title>Stories by Aravind Madhusudhanan Nair on Medium</title>
            <link>https://medium.com/@aravindmnair?source=rss-fc5f64040a2e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:25:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aravindmnair/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[Android CI/CD for React Native with Plain GitHub Actions (No Fastlane)]]></title>
            <link>https://aravindmnair.medium.com/android-ci-cd-for-react-native-with-plain-github-actions-no-fastlane-bc923fe8d62d?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc923fe8d62d</guid>
            <category><![CDATA[fastlane]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Thu, 01 Oct 2026 15:41:02 GMT</pubDate>
            <atom:updated>2026-10-01T15:41:02.469Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Nightly builds to Firebase App Distribution, one-click Play Store uploads, and automatic version codes, using nothing but YAML and a few marketplace actions.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-HowdQfdQFDxwjwOLDfsFg.png" /><figcaption><strong>A practical React Native Android CI/CD pipeline built with GitHub Actions, Firebase App Distribution, and Play Store uploads — without Fastlane.</strong></figcaption></figure><p>Almost every React Native CI/CD tutorial starts with “first, install Fastlane.” Fastlane is great, but it adds Ruby, Bundler, a Fastfile and another layer to debug when a build fails at 7 p.m.</p><p>For Android, you don’t need it. I recently set up a complete pipeline for a production React Native app using only GitHub Actions and well-maintained marketplace actions. Here’s the setup, and the gotchas that cost me the most time.</p><h3>What we’re building</h3><ul><li><strong>A PR check</strong> that type-checks, lints and builds every pull request.</li><li><strong>A nightly build</strong> on weekdays that builds a signed release from the release branch and sends it to testers through Firebase App Distribution.</li><li><strong>A manual Play Store upload</strong>: the same workflow, triggered by a button, uploads the AAB to the internal track.</li><li><strong>Automatic version codes</strong>, so nobody ever edits versionCode by hand again.</li></ul><h3>Step 1: Let Gradle read signing and version from the environment</h3><p>The build file shouldn’t contain secrets, and it shouldn’t need editing for every release. Instead, it reads values from environment variables when they exist and falls back to local defaults when they don’t.</p><p>In android/app/build.gradle:</p><pre>def ciVersionCode = System.getenv(&quot;VERSION_CODE&quot;)</pre><pre>android {<br>    defaultConfig {<br>        versionCode ciVersionCode ? ciVersionCode.toInteger() : 1<br>    }</pre><pre>    signingConfigs {<br>        release {<br>            if (System.getenv(&quot;ANDROID_KEYSTORE_PATH&quot;)) {<br>                storeFile file(System.getenv(&quot;ANDROID_KEYSTORE_PATH&quot;))<br>                storePassword System.getenv(&quot;ANDROID_KEYSTORE_PASSWORD&quot;)<br>                keyAlias System.getenv(&quot;ANDROID_KEY_ALIAS&quot;)<br>                keyPassword System.getenv(&quot;ANDROID_KEY_PASSWORD&quot;)<br>            }<br>        }<br>    }</pre><pre>    buildTypes {<br>        release {<br>            signingConfig signingConfigs.release<br>        }<br>    }<br>}</pre><p>Keep your existing settings in these blocks. Only the lines shown need to change.</p><h3>Step 2: Store secrets and variables in GitHub</h3><p>Encode the keystore as base64 so it can live in a secret:</p><pre># macOS<br>base64 -i release.keystore | pbcopy</pre><pre># Linux<br>base64 -w 0 release.keystore</pre><p>Then add these under <strong>Settings → Secrets and variables → Actions</strong>:</p><ul><li><strong>Secrets:</strong> ANDROID_KEYSTORE_BASE64, ANDROID_KEYSTORE_PASSWORD, ANDROID_KEY_ALIAS, ANDROID_KEY_PASSWORD, FIREBASE_SERVICE_ACCOUNT and PLAY_SERVICE_ACCOUNT_JSON.</li><li><strong>Variables:</strong> RELEASE_BRANCH, VERSION_CODE_OFFSET and FIREBASE_APP_ID.</li></ul><p>Using repository variables for the release branch and version offset means you can change them without touching any YAML.</p><h3>Step 3: The PR check</h3><p>This workflow runs on every pull request and cancels older runs when new commits are pushed:</p><pre>name: Android PR Check</pre><pre>on:<br>  pull_request:<br>    paths-ignore: [&#39;ios/**&#39;, &#39;**.md&#39;]</pre><pre>concurrency:<br>  group: android-pr-${{ github.event.pull_request.number }}<br>  cancel-in-progress: true</pre><pre>jobs:<br>  check:<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 45<br>    steps:<br>      - uses: actions/checkout@v4</pre><pre>      - uses: actions/setup-node@v4<br>        with:<br>          node-version-file: .nvmrc<br>          cache: npm</pre><pre>      - uses: actions/setup-java@v4<br>        with:<br>          distribution: zulu<br>          java-version: 17</pre><pre>      - uses: gradle/actions/setup-gradle@v4</pre><pre>      - run: npm ci<br>      - run: npx tsc --noEmit<br>      - run: npm run lint</pre><pre>      - name: Build debug APK<br>        working-directory: android<br>        run: ./gradlew assembleDebug --no-daemon</pre><p>setup-gradle caches Gradle dependencies between runs, which cuts several minutes from every build.</p><h3>Step 4: The nightly build and Play Store upload</h3><p>One workflow handles both jobs. It runs on a schedule for nightly builds, and it can be triggered manually with an option to upload to the Play Store:</p><pre>name: Android Nightly</pre><pre>on:<br>  schedule:<br>    - cron: &#39;30 13 * * 1-5&#39; # 19:00 IST, Monday to Friday<br>  workflow_dispatch:<br>    inputs:<br>      upload_to_play:<br>        description: &#39;Upload AAB to Play Store (internal track)&#39;<br>        type: boolean<br>        default: false</pre><pre>concurrency:<br>  group: android-nightly<br>  cancel-in-progress: false</pre><pre>jobs:<br>  build:<br>    runs-on: ubuntu-latest<br>    timeout-minutes: 60<br>    steps:<br>      - uses: actions/checkout@v4<br>        with:<br>          ref: ${{ github.event_name == &#39;schedule&#39; &amp;&amp; vars.RELEASE_BRANCH || github.ref }}</pre><pre>      - uses: actions/setup-node@v4<br>        with:<br>          node-version-file: .nvmrc<br>          cache: npm</pre><pre>      - uses: actions/setup-java@v4<br>        with:<br>          distribution: zulu<br>          java-version: 17</pre><pre>      - uses: gradle/actions/setup-gradle@v4</pre><pre>      - run: npm ci</pre><pre>      - name: Set version code and commit<br>        run: |<br>          echo &quot;VERSION_CODE=$(( ${{ github.run_number }} + ${{ vars.VERSION_CODE_OFFSET }} ))&quot; &gt;&gt; &quot;$GITHUB_ENV&quot;<br>          echo &quot;SHORT_SHA=$(git rev-parse --short HEAD)&quot; &gt;&gt; &quot;$GITHUB_ENV&quot;</pre><pre>      - name: Decode keystore<br>        run: echo &quot;${{ secrets.ANDROID_KEYSTORE_BASE64 }}&quot; | base64 -d &gt; &quot;$RUNNER_TEMP/release.keystore&quot;</pre><pre>      - name: Build APK and AAB<br>        working-directory: android<br>        env:<br>          ANDROID_KEYSTORE_PATH: ${{ runner.temp }}/release.keystore<br>          ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}<br>          ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}<br>          ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}<br>        run: ./gradlew assembleRelease bundleRelease --no-daemon</pre><pre>      - uses: actions/upload-artifact@v4<br>        with:<br>          name: android-release-${{ env.VERSION_CODE }}<br>          path: |<br>            android/app/build/outputs/apk/release/app-release.apk<br>            android/app/build/outputs/bundle/release/app-release.aab</pre><pre>      - name: Distribute to Firebase<br>        uses: wzieba/Firebase-Distribution-Github-Action@v1<br>        with:<br>          appId: ${{ vars.FIREBASE_APP_ID }}<br>          serviceCredentialsFileContent: ${{ secrets.FIREBASE_SERVICE_ACCOUNT }}<br>          groups: qa<br>          file: android/app/build/outputs/apk/release/app-release.apk<br>          releaseNotes: &#39;Build ${{ env.VERSION_CODE }} (${{ env.SHORT_SHA }})&#39;</pre><pre>      - name: Upload to Play Store<br>        if: github.event_name == &#39;workflow_dispatch&#39; &amp;&amp; inputs.upload_to_play<br>        uses: r0adkll/upload-google-play@v1<br>        with:<br>          serviceAccountJsonPlainText: ${{ secrets.PLAY_SERVICE_ACCOUNT_JSON }}<br>          packageName: com.yourcompany.yourapp<br>          releaseFiles: android/app/build/outputs/bundle/release/app-release.aab<br>          track: internal<br>          status: completed</pre><p>Scheduled runs always build the release branch. Manual runs build whichever branch you pick in the “Run workflow” dropdown, which is handy for testing a feature branch on real devices.</p><h3>How the version code works</h3><p>github.run_number increases by one every time the workflow runs, so it&#39;s a natural build counter. The offset exists for two reasons:</p><ul><li><strong>Your app probably already has releases.</strong> If the Play Console’s highest version code is 250, set the offset to something above that, such as 300, so the first CI build doesn’t get rejected.</li><li><strong>Run numbers can reset.</strong> If the workflow file is renamed or recreated, its run number starts again at 1. Raising the offset gets you back on track without editing any code.</li></ul><p>Note that GitHub’s expression syntax doesn’t support arithmetic, so you can’t write ${{ github.run_number + vars.VERSION_CODE_OFFSET }}. The shell step with $(( ... )) does the addition instead.</p><h3>The gotchas</h3><p><strong>Scheduled workflows run from the default branch.</strong> The workflow file must exist on the default branch, and a scheduled run checks out the default branch unless you pass a ref. That&#39;s why the checkout step points at RELEASE_BRANCH.</p><p><strong>github.sha is wrong on scheduled runs.</strong> It refers to the default branch&#39;s latest commit, not the release branch you built. Read the commit with git rev-parse after checkout, as the workflow above does, or your release notes will point at the wrong code.</p><p><strong>Each workflow has its own run number.</strong> If you split nightly builds and Play uploads into two separate workflows, they’ll produce overlapping version codes. Keeping both in one workflow avoids that.</p><p><strong>Re-running a job reuses the run number.</strong> If a run uploaded to Play and you click “Re-run,” the version code is the same and Play rejects it. Trigger a fresh run instead.</p><p><strong>The first Play Store release must be uploaded by hand.</strong> The Play Developer API can’t create an app’s very first release. Upload one AAB manually in the Play Console first. Also make sure the service account is invited in the Play Console with permission to manage releases.</p><p><strong>Cron uses UTC and isn’t exact.</strong> 30 13 * * 1-5 is 7 p.m. IST. Scheduled runs can also start late when GitHub is busy, so don&#39;t depend on the exact minute.</p><p><strong>Scheduled workflows can switch off.</strong> In public repositories, GitHub disables scheduled workflows after 60 days without repository activity.</p><h3>Why not Fastlane?</h3><p>To be fair, Fastlane has real advantages. You can run the same lanes locally, it manages store metadata and screenshots, and for iOS, match makes certificate sharing much easier.</p><p>For an Android pipeline, though, plain GitHub Actions gave us:</p><ul><li><strong>Fewer moving parts.</strong> There’s no Ruby, Bundler or Gemfile to keep in sync.</li><li><strong>Everything in one place.</strong> The whole pipeline is readable in the YAML, and each step shows up separately in the Actions log.</li><li><strong>Maintained building blocks.</strong> Marketplace actions already handle Firebase distribution and Play uploads.</li></ul><h3>Write a runbook</h3><p>The last piece isn’t code. Add a short CI-SETUP.md to the repo explaining every secret and variable, how to regenerate the service accounts, and what to do when the version code needs a bump. The person who needs it will be under pressure, and it might be you in six months.</p><p><em>Do you run React Native CI with or without Fastlane? I’d love to hear what’s worked for your team in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc923fe8d62d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MobX-State-Tree vs Redux Toolkit: Choosing State Management After Using Both]]></title>
            <link>https://aravindmnair.medium.com/mobx-state-tree-vs-redux-toolkit-choosing-state-management-after-using-both-0821070b4ea0?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0821070b4ea0</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[mobx]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 17:41:01 GMT</pubDate>
            <atom:updated>2026-09-30T17:41:01.771Z</atom:updated>
            <content:encoded><![CDATA[<p><em>One lets you mutate a living model. The other makes every change an explicit event. Here’s how they compare in real React Native apps, and how I decide between them.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xP2Dc-oWXzvw9T17Ow298Q.png" /><figcaption>MobX-State-Tree vs Redux Toolkit: lessons from using both in real React Native apps.</figcaption></figure><p>Most “MobX vs Redux” articles are written by someone who clearly prefers one and tolerated the other for a weekend. I’ve shipped production React Native apps with both MobX-State-Tree (MST) and Redux Toolkit (RTK), and I’ve debugged both at inconvenient hours.</p><p>My conclusion isn’t that one is better. They’re built on different ideas about what state <em>is</em>, and once you see that, choosing between them gets much easier.</p><h3>The core difference</h3><p><strong>MobX-State-Tree treats state as a living object graph.</strong> You define models with types, views and actions. You change data by calling actions that mutate it directly, and components that read that data re-render automatically.</p><p><strong>Redux Toolkit treats state as a series of events.</strong> Every change is an action object dispatched to a reducer, which produces the next state. Components subscribe to the slices they select.</p><p>Put another way: MST asks <em>“what does the data look like right now?”</em>, and Redux asks <em>“what happened?”</em></p><h3>The same cart, both ways</h3><p>Here’s a small cart with a derived total, a quantity action and an async load.</p><h3>MobX-State-Tree</h3><pre>import { types, flow, applySnapshot } from &#39;mobx-state-tree&#39;;</pre><pre>const CartItem = types.model(&#39;CartItem&#39;, {<br>  id: types.identifier,<br>  name: types.string,<br>  price: types.number,<br>  qty: types.number,<br>});</pre><pre>export const CartStore = types<br>  .model(&#39;CartStore&#39;, {<br>    items: types.array(CartItem),<br>    loading: false,<br>  })<br>  .views(self =&gt; ({<br>    get total() {<br>      return self.items.reduce((sum, i) =&gt; sum + i.price * i.qty, 0);<br>    },<br>  }))<br>  .actions(self =&gt; ({<br>    increment(id: string) {<br>      const item = self.items.find(i =&gt; i.id === id);<br>      if (item) item.qty += 1;<br>    },<br>    load: flow(function* () {<br>      self.loading = true;<br>      const data = yield api.getCart();<br>      applySnapshot(self.items, data.items);<br>      self.loading = false;<br>    }),<br>  }));</pre><pre>const CartTotal = observer(() =&gt; {<br>  const { cart } = useStores();<br>  return &lt;Text&gt;{cart.total}&lt;/Text&gt;;<br>});</pre><h3>Redux Toolkit</h3><pre>import { createSlice, createAsyncThunk, createSelector, PayloadAction } from &#39;@reduxjs/toolkit&#39;;</pre><pre>export const loadCart = createAsyncThunk(&#39;cart/load&#39;, () =&gt; api.getCart());</pre><pre>const cartSlice = createSlice({<br>  name: &#39;cart&#39;,<br>  initialState: { items: [] as CartItem[], loading: false },<br>  reducers: {<br>    increment(state, action: PayloadAction&lt;string&gt;) {<br>      const item = state.items.find(i =&gt; i.id === action.payload);<br>      if (item) item.qty += 1;<br>    },<br>  },<br>  extraReducers: builder =&gt; {<br>    builder<br>      .addCase(loadCart.pending, state =&gt; {<br>        state.loading = true;<br>      })<br>      .addCase(loadCart.fulfilled, (state, action) =&gt; {<br>        state.items = action.payload.items;<br>        state.loading = false;<br>      });<br>  },<br>});</pre><pre>export const selectCartTotal = createSelector(<br>  (state: RootState) =&gt; state.cart.items,<br>  items =&gt; items.reduce((sum, i) =&gt; sum + i.price * i.qty, 0),<br>);</pre><pre>function CartTotal() {<br>  const total = useSelector(selectCartTotal);<br>  return &lt;Text&gt;{total}&lt;/Text&gt;;<br>}</pre><p>Modern Redux doesn’t look very different. Thanks to Immer, RTK reducers also read like mutations. The real differences are in where logic lives, how re-renders are decided, and what tooling you get.</p><h3>Where MobX-State-Tree shines</h3><p><strong>Derived data is effortless.</strong> A view like cart.total is a cached computed value. It recalculates only when an item it depends on changes, and you never write a memoized selector by hand.</p><p><strong>Re-renders are precise by default.</strong> An observer component tracks exactly which properties it read during render. If it reads only cart.total, changing an unrelated field won&#39;t re-render it. With Redux, you get the same result only if your selectors are written carefully.</p><p><strong>Rich domain models feel natural.</strong> Orders that reference products, users with nested addresses, carts with promotions: MST’s identifiers and references let you model relationships directly instead of normalizing everything into ID maps.</p><p><strong>Snapshots make persistence simple.</strong> getSnapshot, applySnapshot and onSnapshot turn the whole tree into plain JSON and back, which makes saving to AsyncStorage or MMKV a few lines of code.</p><p><strong>Runtime type checks catch bad API data.</strong> If the backend sends a string where the model expects a number, MST throws in development, close to the source of the bug.</p><h3>Where MobX-State-Tree hurts</h3><p><strong>The learning curve is real.</strong> Views, volatile state, flows, references, snapshots versus instances: new team members need time before they’re productive.</p><p><strong>Async typing is awkward.</strong> Generator-based flow actions don&#39;t infer the types of yield results well, so you end up adding type annotations by hand.</p><p><strong>TypeScript can get slow.</strong> Large MST model trees produce complex types, and editor responsiveness can suffer in big codebases.</p><p><strong>“Magic” makes some bugs harder to trace.</strong> When a component doesn’t re-render, it’s usually because it isn’t wrapped in observer or it read a value outside render. These bugs are easy to fix once you know the pattern, but they&#39;re confusing the first time.</p><p><strong>The ecosystem is smaller.</strong> There are fewer tutorials, fewer Stack Overflow answers, and fewer developers who already know it.</p><h3>Where Redux Toolkit shines</h3><p><strong>Everything is traceable.</strong> Every change is a named action. Redux DevTools shows exactly what happened, in what order, with the state before and after. In a large app with many developers, that predictability is worth a lot.</p><p><strong>RTK Query handles server state.</strong> Caching, deduplication, refetching and invalidation come built in. In most apps, the majority of “state” is really a cache of server data, and RTK Query handles that better than a hand-written store in either library.</p><p><strong>Onboarding is easier.</strong> Far more developers already know Redux. Documentation, examples and hiring are all easier.</p><p><strong>Reducers are easy to test.</strong> A reducer is a pure function. Give it a state and an action, and check the result.</p><h3>Where Redux Toolkit hurts</h3><p><strong>Derived data takes discipline.</strong> Selectors that build a new array or object on every call cause re-renders every time the store changes. You need createSelector and some care to avoid that.</p><p><strong>More ceremony for simple changes.</strong> RTK removed most of the old boilerplate, but a small feature still involves a slice, actions, selectors and sometimes a thunk.</p><p><strong>Relationships need normalization.</strong> Nested, interconnected data has to be flattened into ID maps, often with createEntityAdapter, and reassembled with selectors.</p><h3>Performance in React Native</h3><p>Both are fast enough for nearly every app. The difference is in the default behaviour. MST’s fine-grained tracking gives you efficient re-renders without extra effort. Redux gives you equally efficient re-renders if you select narrowly and memoize derived data.</p><p>On a screen with a long FlatList, that difference shows up in practice. Wrap row components in observer with MST, or select per-item data with Redux, so that updating one row doesn&#39;t re-render all of them.</p><h3>How I decide</h3><p><strong>I lean towards MobX-State-Tree when:</strong></p><ul><li>The app has a rich domain model with lots of relationships and derived values.</li><li>Much of the state is client-side and long-lived, such as a cart, a multi-step form or an offline-first workflow.</li><li>The team is small and willing to learn MST well.</li></ul><p><strong>I lean towards Redux Toolkit when:</strong></p><ul><li>Most of the state comes from the server, so RTK Query can do the heavy lifting.</li><li>The team is large or changes often, so familiarity and predictability matter more.</li><li>Traceability matters, such as in payment flows where you need to know exactly what happened and in what order.</li></ul><p>And one rule that applies to both: <strong>separate server state from client state.</strong> Put API data in a caching layer, such as RTK Query or TanStack Query, and you’ll often find the client state left over is small enough that the choice matters much less than you expected.</p><h3>If you inherit an app that uses both</h3><p>It happens, especially in older codebases that migrated partway. Don’t rush a rewrite. Draw a clear boundary, such as “new features use X, and each store owns its own data,” and avoid syncing the same data between the two. Duplicated state is where the worst bugs live.</p><p><em>Which one do you use, and would you choose it again? I’d love to hear in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0821070b4ea0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useState vs useRef in React Native: When Should a Value Re-render?]]></title>
            <link>https://aravindmnair.medium.com/usestate-vs-useref-in-react-native-when-should-a-value-re-render-15218ae3f294?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/15218ae3f294</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 14:51:01 GMT</pubDate>
            <atom:updated>2026-09-29T14:51:01.585Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Both hooks remember values between renders. Only one of them tells React to update the screen, and choosing wrong causes some of the most confusing bugs in React Native.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EmHHk0YyXqt9NNtfd9_olg.png" /><figcaption><strong>useState re-renders. useRef remembers.</strong> A simple mental model for choosing the right hook in React Native.</figcaption></figure><p>Early in my React Native career, I treated useRef as &quot;the hook for focusing a TextInput&quot; and useState as &quot;the hook for everything else.&quot; That mental model worked until it didn&#39;t. I hit double-submitted orders, listeners reading old values, and screens that re-rendered on every keystroke for no reason.</p><p>The difference between the two hooks fits in one sentence, and once it clicks, most of those bugs disappear.</p><h3>The one-sentence difference</h3><p><strong>Both </strong><strong>useState and </strong><strong>useRef keep a value alive across renders. Changing state re-renders the component. Changing a ref does not.</strong></p><p>That’s it. Everything else follows from it.</p><p>A helpful way to think about it:</p><ul><li><strong>State is what the screen shows.</strong> If a value appears in your UI or decides what gets rendered, it belongs in state.</li><li><strong>A ref is the component’s notebook.</strong> It’s a place to write things down that the component needs to remember but the user never sees directly: a timer ID, a “request in progress” flag, a handle to a native view.</li></ul><h3>See the difference</h3><p>Here’s a component that tracks the same number twice, once in state and once in a ref:</p><pre>function Counter() {<br>  const [count, setCount] = useState(0);<br>  const taps = useRef(0);</pre><pre>  return (<br>    &lt;Pressable<br>      onPress={() =&gt; {<br>        setCount(c =&gt; c + 1);<br>        taps.current += 1;<br>      }}<br>    &gt;<br>      &lt;Text&gt;State: {count}&lt;/Text&gt;<br>      &lt;Text&gt;Ref: {taps.current}&lt;/Text&gt;<br>    &lt;/Pressable&gt;<br>  );<br>}</pre><p>Both lines update here, but only because setCount triggers a re-render and the ref gets read along the way. Remove the setCount call and tap all you like. taps.current keeps counting, but the screen stays frozen at 0, because nothing told React to render again.</p><p>A ref is a plain object, { current: value }, that React keeps for you between renders. Mutating it is instant and silent.</p><h3>When to reach for useState</h3><p>Use state whenever changing the value should change what the user sees:</p><ul><li>Form values that are displayed or validated as the user types</li><li>Loading, error and empty states</li><li>Selected tabs, toggles and modal visibility</li><li>Data fetched from an API and rendered in a list</li></ul><p>One gotcha: state updates aren’t immediate. After you call a setter, the variable in your current function still holds the old value until the next render.</p><pre>const onPress = () =&gt; {<br>  setCount(count + 1);<br>  console.log(count); // still the old value<br>};</pre><p>If the new value depends on the old one, use the updater form, setCount(c =&gt; c + 1), so React always hands you the latest value.</p><h3>When to reach for useRef</h3><h3>1. Handles to native components</h3><p>This is the use case most React Native developers learn first. A ref gives you the underlying component so you can call its methods:</p><pre>const passwordRef = useRef&lt;TextInput&gt;(null);</pre><pre>&lt;TextInput<br>  placeholder=&quot;Email&quot;<br>  returnKeyType=&quot;next&quot;<br>  onSubmitEditing={() =&gt; passwordRef.current?.focus()}<br>/&gt;<br>&lt;TextInput ref={passwordRef} placeholder=&quot;Password&quot; secureTextEntry /&gt;</pre><p>The same pattern works for scrollTo on a ScrollView, scrollToIndex on a FlatList, or opening a bottom sheet imperatively.</p><h3>2. Guarding against double taps</h3><p>This bug shows up in almost every payment or checkout screen. A user taps “Place order” twice in quick succession, and two orders go through.</p><p>The obvious fix is to check a loading state:</p><pre>const [loading, setLoading] = useState(false);</pre><pre>const onPlaceOrder = async () =&gt; {<br>  if (loading) return;<br>  setLoading(true);<br>  await submitOrder();<br>  setLoading(false);<br>};</pre><p>This doesn’t fully work. If both taps land before React re-renders, both handlers come from the same render, where loading is still false. Both pass the check.</p><p>A ref fixes it, because writing to a ref takes effect immediately:</p><pre>const submitting = useRef(false);<br>const [loading, setLoading] = useState(false);</pre><pre>const onPlaceOrder = async () =&gt; {<br>  if (submitting.current) return;<br>  submitting.current = true;<br>  setLoading(true);<br>  try {<br>    await submitOrder();<br>  } finally {<br>    submitting.current = false;<br>    setLoading(false);<br>  }<br>};</pre><p>Notice that both hooks are used, each for its own job. The ref is the lock, and the state drives the spinner the user sees.</p><h3>3. Timers and subscriptions</h3><p>Timer IDs, subscription handles and similar bookkeeping never appear on screen, so they belong in refs:</p><pre>const timeoutRef = useRef&lt;ReturnType&lt;typeof setTimeout&gt; | null&gt;(null);</pre><pre>const onChangeText = (text: string) =&gt; {<br>  if (timeoutRef.current) clearTimeout(timeoutRef.current);<br>  timeoutRef.current = setTimeout(() =&gt; search(text), 300);<br>};</pre><pre>useEffect(() =&gt; () =&gt; {<br>  if (timeoutRef.current) clearTimeout(timeoutRef.current);<br>}, []);</pre><p>Putting a timer ID in state would trigger a pointless re-render every time the user types a character.</p><h3>4. Reading the latest value inside a long-lived listener</h3><p>Listeners you register once, such as AppState, Keyboard or a BackHandler, capture the values from the render where they were created. That&#39;s called a stale closure. To read the latest value without re-registering the listener on every change, mirror it into a ref:</p><pre>const draftRef = useRef(draft);</pre><pre>useEffect(() =&gt; {<br>  draftRef.current = draft;<br>}, [draft]);</pre><pre>useEffect(() =&gt; {<br>  const sub = AppState.addEventListener(&#39;change&#39;, next =&gt; {<br>    if (next === &#39;background&#39;) saveDraft(draftRef.current);<br>  });<br>  return () =&gt; sub.remove();<br>}, []);</pre><p>The listener is registered once, and it always saves the latest draft.</p><h3>5. Animated values</h3><p>With React Native’s Animated API, the value object must survive re-renders without being recreated, and animating it shouldn’t re-render the component on every frame:</p><pre>const opacity = useRef(new Animated.Value(0)).current;</pre><pre>useEffect(() =&gt; {<br>  Animated.timing(opacity, {<br>    toValue: 1,<br>    duration: 300,<br>    useNativeDriver: true,<br>  }).start();<br>}, []);</pre><p>If you use Reanimated, useSharedValue fills the same role.</p><h3>Common mistakes</h3><p><strong>Rendering from a ref.</strong> If ref.current appears in your JSX and you expect the screen to update when it changes, you want state. The UI will only catch up by accident, the next time something else re-renders.</p><p><strong>Putting ref.current in a dependency array.</strong> Changing a ref doesn’t cause a render, so React never gets the chance to compare the new value. An effect depending on ref.current won&#39;t run when the ref changes.</p><p><strong>Putting everything in state.</strong> The opposite mistake is just as common. Values that only matter inside event handlers, like a previous scroll offset or a “has already tracked this analytics event” flag, cause unnecessary re-renders when stored in state. On a heavy screen with a long FlatList, those re-renders add up.</p><p><strong>Mutating state like a ref.</strong> Writing items.push(newItem) changes the array but not its identity, so React doesn&#39;t see a change. Create a new array instead: setItems(prev =&gt; [...prev, newItem]).</p><h3>The quick decision rule</h3><p>When you’re unsure, ask one question: <strong>“If this value changes, should the user see something different?”</strong></p><ul><li><strong>Yes:</strong> use useState.</li><li><strong>No, but I need to remember it between renders:</strong> use useRef.</li><li><strong>No, and it can be calculated from other values:</strong> use neither. Calculate it during render, or use useMemo if the calculation is expensive.</li></ul><p>And when a single feature needs both an instant lock and a visible spinner, as with the double-tap guard, use both.</p><p><em>What’s the most confusing useState or useRef bug you’ve run into? Share it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15218ae3f294" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Under2K: What I Learned Rebuilding a UPI Bill Splitter in React Native]]></title>
            <link>https://aravindmnair.medium.com/under2k-what-i-learned-rebuilding-a-upi-bill-splitter-in-react-native-210b3faab645?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/210b3faab645</guid>
            <category><![CDATA[skeuomorphism]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 14:31:01 GMT</pubDate>
            <atom:updated>2026-09-28T14:31:01.739Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Integer paise, typed translations in 11 Indian languages, and leather and steel made from nothing but gradients and shadows.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dfj-AkffIIJFHK92CWBPBg.png" /><figcaption>Under2K — a React Native UPI bill splitter to skip MDR fees, rebuilt from scratch.</figcaption></figure><p>A while ago I came across <a href="https://github.com/TechnoAman/SplitPe">SplitPe</a> by TechnoAman, an experimental Flutter app with a simple premise: take a UPI bill and split it into payments of ₹2,000 or less. The idea behind it is that a single merchant payment above ₹2,000 may attract a fee(MDR fees), while smaller ones don’t.</p><p>I liked the idea, and I wanted an excuse to build something I rarely get to build at work: an interface that looks and feels like real physical objects. So I rebuilt the concept in React Native with Expo and TypeScript and called it <strong>Under2K</strong>. All credit for the original idea goes to SplitPe.</p><blockquote><em>A note before we start: the fee model in Under2K is an assumption, not a fact. Real fees depend on the payment type, your bank, the merchant’s agreement and current regulation. Under2K is a practice and learning project, and every “fee saved” number in it is an estimate.</em></blockquote><h3>What the app does</h3><p>Under2K has three screens:</p><ul><li><strong>Pay bill:</strong> choose a shop, key in the amount, and see it cut into equal slices. Then pay each slice through your own UPI app.</li><li><strong>Group split:</strong> divide a dinner bill among 2–8 people, each with their own payment ticket and QR code.</li><li><strong>Fee gauge:</strong> estimate what payment fees cost a shop per year from its monthly UPI sales.</li></ul><p>It has no accounts, no analytics and no server. Everything runs on the device.</p><h3>Lesson 1: Money is an integer</h3><p>The first rule of any money app is to never use floating point for amounts. Under2K stores every amount as integer <strong>paise</strong>, so slices always add up to the exact bill with no rounding drift.</p><p>The slicing rule is simple:</p><ol><li>If the bill is ₹1,999 or less, it’s a single payment.</li><li>Otherwise, use the fewest slices that keep each one under the cap: ceil(total / ₹1,999).</li><li>Divide evenly and spread the remainder one unit at a time, so slices differ by at most ₹1 (or 1 paisa if the bill has paise).</li></ol><p>The core idea looks roughly like this:</p><pre>const CAP = 199900; // ₹1,999 in paise</pre><pre>export function slice(totalPaise: number): number[] {<br>  if (totalPaise &lt;= CAP) return [totalPaise];<br>  const count = Math.ceil(totalPaise / CAP);<br>  const unit = totalPaise % 100 === 0 ? 100 : 1;<br>  const units = totalPaise / unit;<br>  const base = Math.floor(units / count);<br>  const extra = units % count;<br>  return Array.from({ length: count }, (_, i) =&gt;<br>    (base + (i &lt; extra ? 1 : 0)) * unit<br>  );<br>}</pre><p>A ₹4,750 bill becomes ₹1,584 + ₹1,583 + ₹1,583. A ₹6,800 bill becomes four slices of ₹1,700. Because a whole-rupee bill always produces whole-rupee slices, nobody is asked to pay ₹1,583.33.</p><h3>Lesson 2: Skeuomorphism without a single image asset</h3><p>This was the fun part. Every surface in Under2K is meant to look like a physical object: a desk with brushed grain, stitched leather panels, brushed steel nameplates with screws, raised keys, an odometer with rolling drums for the amount, an analog fee gauge with a needle, brass-knobbed faders, torn-edge thermal paper receipts and a rubber “PAID” stamp that slams down.</p><p>None of it uses image assets. It’s all built from expo-linear-gradient, react-native-svg, layered shadows and haptics. That has real advantages:</p><ul><li><strong>It scales.</strong> Gradients and SVG stay sharp on every screen density, with no @2x or @3x exports.</li><li><strong>It themes.</strong> The same materials render in Midnight, Emerald or Graphite by swapping color tokens.</li><li><strong>It stays small.</strong> The bundle doesn’t grow with every new texture.</li></ul><p>The biggest lesson was that skeuomorphism is as much about feel as looks. Every key gives a light haptic when pressed. The soundbox reads the settled amount aloud with expo-speech, like the payment speakers in Indian shops. Small touches like these make a flat screen feel physical.</p><h3>Lesson 3: Read theme colors at render time</h3><p>Under2K switches themes live without losing your amount or shop. The theme is a mutable color object that setTheme() updates. This works well, with one catch: <strong>anything that copies a color into a module-level constant won&#39;t update.</strong> A StyleSheet.create at the top of a file captures the colors once, at import time.</p><p>The fix is to read colors inside the component at render time. It’s a small discipline, but it’s the difference between a theme switch that works everywhere and one that leaves half the screen in the old palette.</p><h3>Lesson 4: Eleven languages, checked by the compiler</h3><p>Under2K ships in English, Hindi, Bengali, Marathi, Telugu, Tamil, Gujarati, Kannada, Malayalam, Punjabi and Odia. It follows the device language on first launch, using expo-localization.</p><p>The key design choice: en.ts defines the required keys, and every other language file must match them exactly. TypeScript rejects a file with a missing or extra key, so a new string can never ship half-translated:</p><pre>// en.ts is the source of truth<br>export const en = {<br>  payBill: &#39;Pay bill&#39;,<br>  slices: &#39;{n:slice|slices}&#39;,<br>};</pre><pre>// ta.ts must have exactly the same keys<br>export const ta: Record&lt;keyof typeof en, string&gt; = {<br>  payBill: &#39;...&#39;,<br>  slices: &#39;...&#39;,<br>};</pre><p>Indian scripts brought two surprises:</p><ul><li><strong>Display fonts have no Indic glyphs.</strong> Indic text falls back to the system font, while digits and Latin text keep the display fonts.</li><li><strong>Letter-spacing breaks joined letters.</strong> Many Indic scripts combine characters into conjuncts. Adding letter-spacing, which looks great on engraved English labels, pulls them apart. Letter-spacing has to be switched off for Indic text.</li></ul><p>Amounts always use Latin digits and the ₹ sign, so figures read the same in every language. Urdu isn’t included yet, because right-to-left layout needs mirroring.</p><h3>Lesson 5: UPI is just a link</h3><p>Under2K never touches money. Each slice is a paper ticket with a upi://pay QR code that opens in any UPI app, can be copied as a link, or can be scanned from another phone.</p><p>Scanning a shop’s QR happens on the device with expo-camera, and nothing is uploaded. Because QR codes are untrusted input, the parser validates the UPI ID format, rejects web links and non-INR codes, strips HTML from names, and recognizes common app and bank handles.</p><p>One honest limitation: the app can’t see whether a payment succeeded. You tap “I’ve paid” after your UPI app confirms it, and the receipt reflects only what you confirmed. I think being upfront about that is better than pretending otherwise.</p><h3>Lesson 6: One codebase, a free web demo</h3><p>Expo’s web target gave me a live demo for free. A GitHub Actions workflow type-checks the project, runs npx expo export --platform web and deploys to GitHub Pages on every push to main.</p><p>The gotcha: GitHub Pages serves the site from a sub-path, so the web build needs a base URL. I set EXPO_BASE_URL only in that workflow, because setting it for native builds breaks the iOS asset bundle.</p><h3>Takeaways</h3><ul><li>Store money as integers, and design your rounding so totals are always exact.</li><li>Gradients, SVG, shadows and haptics can take you a long way without a single image asset.</li><li>Read theme values at render time if your themes switch live.</li><li>Let the type system enforce translation completeness.</li><li>Test Indic scripts early: fonts and letter-spacing will surprise you.</li><li>Treat scanned QR data as untrusted input.</li></ul><p>Rebuilding someone else’s idea in a different framework turned out to be a great way to learn. The problem was already defined, so all my energy went into craft.</p><p><em>Under2K is open source under the MIT license. You can try the </em><a href="https://aravi365.github.io/under2k/"><em>live web demo</em></a><em> or browse the code on </em><a href="https://github.com/aravi365/under2k"><em>GitHub</em></a><em>. If you speak one of the supported languages, I’d love a review of the translations. They haven’t been checked by native speakers yet.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=210b3faab645" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Syncing Step Data in React Native in 2026: HealthKit, Health Connect, and What Happened to Google…]]></title>
            <link>https://medium.com/swlh/syncing-step-data-in-react-native-in-2026-healthkit-health-connect-and-what-happened-to-google-8d6cf79c63a7?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d6cf79c63a7</guid>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Sun, 27 Sep 2026 06:18:53 GMT</pubDate>
            <atom:updated>2026-09-27T06:53:13.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>Syncing Step Data in React Native in 2026: HealthKit, Health Connect, and What Happened to Google Fit</h3><p><em>What I wish I’d known before scoping a step-sync feature for a production app.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgy9eseIFfkwk523W6husA.png" /><figcaption>HealthKit on iOS, Health Connect on Android, and Fitbit through Google, all syncing into a single backend.</figcaption></figure><p>“Just show the user’s steps” sounds like a two-day ticket. Then you learn that iOS and Android store health data completely differently, that Google Fit is on its way out, and that step counts can be off by thousands depending on how you query them.</p><p>I recently scoped a step-sync feature for a production React Native app. This is what I wish I’d known on day one.</p><h3>The landscape has changed</h3><p>For years, the Android answer was Google Fit. That is no longer true. Google has deprecated the Fit APIs in favor of <strong>Health Connect</strong>, an on-device health data store built into Android 14+ and available as an app on older versions. If your app still reads from Google Fit, you have a migration ahead of you.</p><p>On iOS, <strong>HealthKit</strong> remains the source of truth. It’s stable, but it has its own surprises.</p><p>Wearables complicate the picture further. Fitbit can sync into Health Connect on Android, but it doesn’t write to Apple Health. So for Fitbit users on iPhone, there’s nothing on-device to read. You have to go through Google’s health cloud API instead, with the backend doing the fetching.</p><p>So a realistic 2026 architecture has three sources:</p><ul><li><strong>iOS:</strong> HealthKit, read on-device</li><li><strong>Android:</strong> Health Connect, read on-device</li><li><strong>Fitbit on iOS:</strong> Google’s health cloud API, via Google Sign-In and your backend</li></ul><h3>Decision 1: One backend table, one active provider</h3><p>The most important choice we made was treating the backend as the source of truth. Every provider writes to a single table, roughly daily_activity(user_id, date, steps, provider, synced_at), instead of the app showing raw on-device numbers.</p><p>We also allowed only <strong>one active provider per user</strong>. If someone has an iPhone, an Apple Watch, and a Fitbit, summing everything means double-counting the same walk. You let the user pick a source, and you switch cleanly when they change it.</p><p>This keeps leaderboards, challenges, and rewards consistent. Two devices should never disagree about what the user “really” walked.</p><h3>Decision 2: Never sum raw samples</h3><p>This is the bug almost everyone ships.</p><p>Both HealthKit and Health Connect store <em>samples</em> from multiple sources. An iPhone and an Apple Watch worn together both record steps for the same walk. If you fetch the samples and add them up, you’ll inflate the count.</p><p>The fix on both platforms is to use the <strong>aggregation APIs</strong>:</p><ul><li>On iOS, use a statistics query with cumulative sum. HealthKit dedupes overlapping sources for you, and the result matches what the Health app shows.</li><li>On Android, use Health Connect’s aggregate API with StepsRecord.COUNT_TOTAL instead of reading raw StepsRecords.</li></ul><pre>// Android (react-native-health-connect)<br>const result = await aggregateRecord({<br>  recordType: &#39;Steps&#39;,<br>  timeRangeFilter: {<br>    operator: &#39;between&#39;,<br>    startTime: startOfDay.toISOString(),<br>    endTime: endOfDay.toISOString(),<br>  },<br>});<br>const steps = result.COUNT_TOTAL;</pre><p>If your number doesn’t match the OS health app, this is almost always the reason.</p><h3>Decision 3: Let the backend own the Fitbit connection</h3><p>For the Fitbit path on iOS, the app’s job is small. It only has to get the user’s consent and hand it off:</p><ol><li>The app uses Google Sign-In to request the health scopes you need, with offline access enabled.</li><li>Sign-In returns a one-time <strong>server auth code</strong>. The app sends that code to your backend and nothing else.</li><li>The backend exchanges the code for access and refresh tokens and stores the refresh token securely.</li><li>The backend fetches daily steps from Google’s health API on its own schedule and writes them to the same daily_activity table as everything else.</li></ol><p>Tokens never live on the device, sync keeps working when the app is closed, and the rest of your system can’t tell whether a day’s steps came from HealthKit or Fitbit.</p><p>One thing to budget time for: health scopes are restricted, so Google requires OAuth consent screen verification before you can ship to real users. Start that process early. It takes longer than the code.</p><h3>Decision 4: Day boundaries belong to the user’s time zone</h3><p>“Today’s steps” means midnight-to-midnight in the <strong>user’s local time</strong>, not UTC. Compute the day boundaries on the device and send the local date to the backend along with the count. Otherwise, a user in IST sees their morning walk counted toward yesterday.</p><h3>The permission gotchas</h3><p><strong>HealthKit hides read denials.</strong> For privacy reasons, iOS won’t tell you whether the user denied <em>read</em> access. A denied permission looks exactly like “no data.” Design your UI for that: show a zero state that says “No steps found — check Health permissions” with a deep link to Settings, not an error.</p><p><strong>Health Connect limits history.</strong> By default, your app can read only about 30 days of data before the permission was granted. Anything older needs the separate history permission. Background reads also need their own permission. Request each one only when you actually need it, or Play review will ask questions.</p><p><strong>Health Connect might not be installed.</strong> On Android versions before 14, check SDK availability and send the user to the Play Store if needed. Don’t assume it’s present.</p><h3>Sync strategy</h3><p>What worked for us:</p><ol><li><strong>Sync on app foreground</strong>, starting from the last synced date, capped at a reasonable window such as 7 days.</li><li><strong>Upsert per day</strong> on the backend, so re-syncing the same day overwrites it instead of duplicating it.</li><li><strong>Re-sync the last day or two every time.</strong> Wearables often upload late, so yesterday’s count keeps changing for a while.</li><li><strong>Treat background sync as a bonus.</strong> iOS background delivery and Android background reads both work, but neither is guaranteed. Foreground sync is your reliable path.</li></ol><h3>Libraries</h3><ul><li><strong>iOS:</strong> @kingstinct/react-native-healthkit, which is TypeScript-first and exposes statistics queries directly</li><li><strong>Android:</strong> react-native-health-connect</li><li><strong>Fitbit on iOS:</strong> Google Sign-In for the server auth code; your backend does the rest</li></ul><p>Whichever library you pick, make sure it exposes the platform’s aggregation APIs, not just raw sample reads.</p><h3>Takeaways</h3><ul><li>Google Fit is ending, so move to Health Connect now.</li><li>Always use aggregation APIs and never sum raw samples.</li><li>Use one active provider per user, with the backend as the source of truth.</li><li>Compute days in the user’s local time zone.</li><li>Design for silent permission denials on iOS.</li><li>Re-sync recent days, because wearable data arrives late.</li></ul><p>Step counting looks trivial until your leaderboard shows someone walking 60,000 steps because their watch and phone both counted the same trip to the grocery store. Get the architecture right first. The UI is the easy part.</p><p><em>If you’ve shipped health integrations in React Native, I’d love to hear what tripped you up. Drop it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d6cf79c63a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/syncing-step-data-in-react-native-in-2026-healthkit-health-connect-and-what-happened-to-google-8d6cf79c63a7">Syncing Step Data in React Native in 2026: HealthKit, Health Connect, and What Happened to Google…</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Siri-Style Edge Glow in React Native (and the corner-radius rabbit hole it led me down)]]></title>
            <link>https://aravindmnair.medium.com/building-a-siri-style-edge-glow-in-react-native-and-the-corner-radius-rabbit-hole-it-led-me-down-2438525791e4?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2438525791e4</guid>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[siri]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Sat, 18 Jul 2026 17:25:03 GMT</pubDate>
            <atom:updated>2026-07-18T17:25:03.192Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0nRdv2KhY_CHL6bjzzWgtA.jpeg" /></figure><p>You’ve seen it. Hold down the side button for Siri, or press-and-hold in the Gemini app, and a soft rainbow glow blooms around the edges of the screen and slowly sweeps around. It’s a tiny detail, but it feels <em>alive</em> — and it’s the kind of polish that makes an app feel expensive.</p><p>I wanted that in a React Native app. I couldn’t find a drop-in that did exactly this — a glow that hugs the <strong>screen edges</strong> and follows the device’s real rounded corners — so I built one and published it as <a href="https://www.npmjs.com/package/react-native-edge-glow">react-native-edge-glow</a>.</p><p>This post is the story of building it: the approach that seemed obvious and failed, the one that worked, and the corner-radius problem that sent me into the Android platform APIs. If you just want to use it, skip to Using it at the bottom</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*tg7BMWqRiZosDSL4PaMScQ.gif" /></figure><h3>The effect, broken into parts</h3><p>A glow like this is really three things happening at once:</p><ol><li>A <strong>multi-color gradient</strong> wrapped around the screen border.</li><li>That gradient <strong>sweeping</strong> around continuously.</li><li>A soft <strong>bloom</strong> that fades inward from the edge to transparent.</li></ol><p>And two constraints that make it interesting:</p><ul><li>It has to run at 60fps without stuttering — so the animation can’t live on the JS thread.</li><li>It has to look right on <strong>both</strong> iOS and Android, whose screens have very different corners.</li></ul><h3>Attempt #1: the “obvious” way that fell apart</h3><p>My first instinct was SVG masks and filters. Draw a big rainbow rectangle, mask it to a border shape, blur it with &lt;FeGaussianBlur&gt;, and rotate the whole thing to get the sweep. It worked beautifully… on iOS.</p><p>On Android it rendered <strong>nothing</strong>. A blank screen, no error.</p><p>It turns out SVG &lt;Mask&gt; and &lt;Filter&gt; support in react-native-svg is inconsistent across platforms — the exact combination I leaned on simply didn’t paint on Android. This is the sort of thing you only discover by testing on a real device on both platforms, which is a lesson worth internalizing: <em>“it works on iOS” is half an answer.</em></p><p>So I threw it out and looked for a technique that used only primitives both platforms render identically.</p><h3>Attempt #2: animate the gradient itself</h3><p>Instead of rotating a masked, blurred shape, I animate the <strong>gradient’s coordinates</strong>.</p><p>A &lt;LinearGradient&gt; in SVG is defined by a start point (x1, y1) and an end point (x2, y2). If you slide those points diagonally across the screen over time, the colors appear to sweep around the border — no rotation math, no masks, no filters. Just four numbers changing.</p><pre>// The gradient is painted onto the stroke of a rounded rect.<br>// Animating x1/y1/x2/y2 slides the colors around the edge.<br>&lt;LinearGradient id=&quot;glow&quot; x1=&quot;-60%&quot; y1=&quot;140%&quot; x2=&quot;40%&quot; y2=&quot;240%&quot;&gt;<br>  &lt;Stop offset=&quot;0%&quot;   stopColor=&quot;#8B5CF6&quot; /&gt;<br>  &lt;Stop offset=&quot;50%&quot;  stopColor=&quot;#06B6D4&quot; /&gt;<br>  &lt;Stop offset=&quot;100%&quot; stopColor=&quot;#8B5CF6&quot; /&gt;<br>&lt;/LinearGradient&gt;</pre><p>Because the first and last color are the same, the loop is seamless — when the sweep wraps around, there’s no visible jump.</p><h3>The bloom: no blur filter allowed</h3><p>I still needed the soft glow that fades inward. SVG blur was off the table (see attempt #1), so I faked it with geometry.</p><p>The trick: draw the border as <strong>many concentric rounded rectangles</strong>, each one reaching a little deeper into the screen, all at a low opacity. Where they overlap — right at the edge — they stack up bright. As you move inward, fewer rings reach, so it fades to transparent. The composite <em>is</em> a gradient, built out of nothing but stroked rects.</p><pre>// ~12 rings, each deeper and low-opacity; their overlap forms the fade.<br>{rings.map(r =&gt; (<br>  &lt;Rect<br>    x={r.depth / 2} y={r.depth / 2}<br>    width={W - r.depth} height={H - r.depth}<br>    rx={cornerRadius} ry={cornerRadius}<br>    stroke=&quot;url(#glow)&quot; strokeWidth={r.depth}<br>    strokeOpacity={0.07} fill=&quot;none&quot;<br>  /&gt;<br>))}</pre><h3>Keeping it off the JS thread</h3><p>Animating those gradient coordinates every frame from JavaScript is a recipe for jank — every frame has to cross the bridge, and any hiccup in your JS thread (a fetch resolving, a re-render) shows up as a stutter in the glow.</p><p><a href="https://docs.swmansion.com/react-native-reanimated/">Reanimated</a> solves this. A shared value drives the animation on the <strong>UI thread</strong>, and useAnimatedProps feeds the animated coordinates straight into the SVG gradient without touching JS per frame:</p><pre>const progress = useSharedValue(0);<br>useEffect(() =&gt; {<br>  progress.value = withRepeat(<br>    withTiming(1, { duration: 2600, easing: Easing.linear }),<br>    -1, // forever<br>    false,<br>  );<br>}, []);<br>const gradientProps = useAnimatedProps(() =&gt; {<br>  &#39;worklet&#39;;<br>  const p = progress.value;<br>  return {<br>    x1: `${-60 + p * 200}%`,<br>    y1: `${140 - p * 200}%`,<br>    x2: `${40 + p * 200}%`,<br>    y2: `${240 - p * 200}%`,<br>  };<br>});</pre><p>Now the glow keeps sweeping smoothly even while your app is busy doing real work. Measured on a mid-range device it holds ~60fps with the JS thread completely idle between frames.</p><h3>The rabbit hole: what corner radius?</h3><p>Here’s the part I didn’t expect to spend an evening on.</p><p>The glow is drawn on a rounded rectangle. What radius? If I guess too small, the glow cuts across a rounded iPhone corner. Too big on a squared-off Android phone, and it bulges past the screen. <strong>Every device is different.</strong></p><p><strong>iOS.</strong> There is <em>no public API</em> for the display’s corner radius. Apple just doesn’t expose it. So iOS gets a fixed, hand-tuned approximation (~55pt) that matches modern iPhones well enough. (There’s a private _displayCornerRadius KVC trick, but shipping private API is an App Store risk I wasn’t willing to take on other people’s behalf.)</p><p><strong>Android.</strong> This is the fun bit. Since <strong>Android 12 (API 31)</strong>, there’s a <em>public, documented</em> API that reports the physical corner radius of the display: <a href="https://developer.android.com/reference/android/view/WindowInsets#getRoundedCorner(int)">WindowInsets.getRoundedCorner()</a>. Most people have never heard of it. So I wrote a tiny native module that reads it:</p><pre>val insets = decorView.rootWindowInsets<br>val radiusPx = insets<br>  ?.getRoundedCorner(RoundedCorner.POSITION_TOP_LEFT)<br>  ?.radius ?: 0<br>promise.resolve(radiusPx / density) // -&gt; dp</pre><p>On my Pixel emulator this returned <strong>30.33dp</strong> — the real, physical curvature of that screen. The glow now traces the actual corner instead of guessing. On devices below API 31 (or genuinely square screens) it reports 0 and the glow falls back to square corners, which is correct.</p><p>That’s the difference between an effect that looks <em>bolted on</em> and one that looks <em>native</em>: it matches the hardware.</p><h3>Presets, pulse, and accessibility</h3><p>Once the core worked, the rest was ergonomics:</p><ul><li><strong>Presets</strong> — rainbow, siri, gemini, aurora, sunset — so you don’t have to hand-pick colors.</li><li>A <strong>breathing pulse</strong> that gently fades the whole glow in and out (very Siri), togglable and tunable.</li><li><strong>Reduce Motion</strong> support — if the OS accessibility setting is on, the glow holds still instead of animating. Free respect for users who need it.</li></ul><h3>Using it</h3><pre>npm install react-native-edge-glow react-native-svg react-native-reanimated</pre><p>Render it as the last child of a full-screen container — it positions itself absolutely and ignores touches:</p><pre>import { useState } from &#39;react&#39;;<br>import { Pressable } from &#39;react-native&#39;;<br>import EdgeGlow from &#39;react-native-edge-glow&#39;;<br>function Screen() {<br>  const [holding, setHolding] = useState(false);<br>  return (<br>    &lt;Pressable<br>      style={{ flex: 1 }}<br>      onPressIn={() =&gt; setHolding(true)}<br>      onPressOut={() =&gt; setHolding(false)}<br>    &gt;<br>      {/* your content */}<br>      &lt;EdgeGlow active={holding} preset=&quot;siri&quot; /&gt;<br>    &lt;/Pressable&gt;<br>  );<br>}</pre><p>That’s it. Colors, sweep speed, glow width, pulse, corner radius — all props, all documented in the README.</p><h3>The honest part: know its limits</h3><p>I’ll be straight about the tradeoff. Because the gradient coordinates change every frame, the SVG is <strong>re-rasterized on the CPU each frame</strong>. For a press-and-hold effect that runs for a few seconds, that’s completely smooth and totally fine. If you need a glow running <em>continuously</em> for minutes, glowing around arbitrary components, or targeting very low-end hardware, you want GPU rendering instead — reach for <a href="https://www.npmjs.com/package/react-native-animated-glow">react-native-animated-glow</a>, which is Skia-based and built for exactly that. Different tools for different jobs; I’d rather point you to the right one than pretend mine does everything.</p><h3>Wrapping up</h3><p>What started as “I want that Siri glow” turned into a nice little tour: why SVG filters aren’t portable, how to fake a bloom with geometry, how to keep animation off the JS thread, and a genuinely useful Android API almost nobody uses.</p><p>If you build something with it, I’d love to see it.</p><ul><li><strong>npm:</strong> <a href="https://www.npmjs.com/package/react-native-edge-glow">react-native-edge-glow</a></li><li><strong>GitHub:</strong> <a href="https://github.com/aravi365/react-native-edge-glow">aravi365/react-native-edge-glow</a> <em>(stars very welcome)</em></li></ul><p><em>Thanks for reading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2438525791e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Better way to import components in large react/react native projects]]></title>
            <link>https://aravindmnair.medium.com/a-better-way-to-import-components-in-a-large-react-react-native-projects-c820a57c743a?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c820a57c743a</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Wed, 23 Feb 2022 05:53:08 GMT</pubDate>
            <atom:updated>2022-02-24T10:42:53.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*S_ONvFeu4WRBJZ5r6DMPwg.jpeg" /><figcaption>Image Credits: Medium/<a href="https://medium.com/@rooney.reeves?source=post_page-----14065ce5b0c3-----------------------------------">Rooney Reeves</a></figcaption></figure><p>A Component is the basic building block of <strong>React</strong>. They are<strong> independent reusable bits of code</strong> and comes in two types - Class and Functional components.</p><p>Ok, now let’s get straight to the point and discuss how to structure your project when you have a large number of components when you are working on a large project.</p><p>Generally when you are using components in a particular screen or file, we import it like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cadbd7b93a591385acccaa5a7c24978b/href">https://medium.com/media/cadbd7b93a591385acccaa5a7c24978b/href</a></iframe><p>which will look cluttered when the codebase grows.</p><p>For better readability, we can create an <em>index.js</em> file in our root component directory and export all the components as named export like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1ec26c75da1d99c09b47ce5afcf7363/href">https://medium.com/media/f1ec26c75da1d99c09b47ce5afcf7363/href</a></iframe><p>Now, we can write our screens file like below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3dc2d91d5f669d8b6a112081c7be01c/href">https://medium.com/media/e3dc2d91d5f669d8b6a112081c7be01c/href</a></iframe><p>And with this approach, in a single line you can import multiple components if you want to access them, instead of having multiple import statements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c820a57c743a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add custom fonts to react-native 0.60+ easily in 3 steps]]></title>
            <link>https://aravindmnair.medium.com/add-custom-fonts-to-react-native-0-60-easily-in-3-steps-fcd71459f4c9?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcd71459f4c9</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[fonts]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[user-interface]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Tue, 05 May 2020 08:09:14 GMT</pubDate>
            <atom:updated>2023-06-01T14:28:12.606Z</atom:updated>
            <content:encoded><![CDATA[<h3>Add custom fonts to react-native easily in 3 steps [updated 2023]</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*m65WQUMvbI8sp0iCMjKovw.jpeg" /><figcaption>Image Courtesy: Brands Everywhere</figcaption></figure><p>In this article I will give you the steps to include custom fonts in any react-native project (0.60 to any newer version).</p><h4>1. Get the font file needed for your project</h4><p>You need to obtain the required font files either in <strong>.ttf</strong> or <strong>.otf</strong> format. You can get some free fonts from <a href="https://www.fontspace.com/category/opentype">Fontspace</a> or <a href="https://candyfonts.com/">Candyfonts</a>. Place the font files in a folder you prefer. Here i am adding my fonts in <strong>App/assets/fonts</strong></p><h4>2. Create a configuration file</h4><p>Create a configuration file <strong><em>react-native.config.js</em> </strong>in the <strong>root project directory </strong>and add the code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0c35314238f58b89110a6bf97c4f43a/href">https://medium.com/media/c0c35314238f58b89110a6bf97c4f43a/href</a></iframe><h4>3 (a).Linking the font assets (For RN version &lt; 0.69)</h4><p>Link the newly added asset by running the command:</p><pre><strong>yarn react-native link </strong></pre><p>or</p><pre><strong>npx react-native link </strong>//only if React Native version &lt; 0.69</pre><h4>3 (b). Linking the font assets (For RN version &gt; 0.69)</h4><p>For React Native versions above 0.69, autolinking, link and unlink commands have been removed and so you can link your assets using the below command:</p><pre>npx react-native-asset </pre><p>The above command uses <a href="https://www.npmjs.com/package/react-native-asset">react-native-asset</a> to copy the assets to respective native directories and make all the required changes.</p><p>If everything is right, you will see something like below, and you can see the new font assets in android/app/src/main/assets/fonts in the case of android and changes in the Info.plist in case of iOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*_69fZsmwOrYfkK9KLydOTw.png" /><figcaption>Success message when linked with <strong>yarn react-native link</strong></figcaption></figure><p>and finally, <strong>Re-run your app</strong> to initialise with the newly bundled resources (i.e the fonts).</p><pre><strong>npx react-native run-android</strong></pre><p>or</p><pre><strong>yarn run android</strong></pre><p><strong><em>Note: Make sure to link the font assets every time you add a new font to your project.</em></strong></p><p>Do comment, if you have any doubts or queries.</p><p>Always happy to help. Cheers 🍻</p><p>[This story is last updated on 01-Jun-2023]</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcd71459f4c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meet the new diagnostic tool for react-native : react-native doctor]]></title>
            <link>https://aravindmnair.medium.com/meet-the-new-diagnostic-tool-for-react-native-react-native-doctor-b3b0df20eec7?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3b0df20eec7</guid>
            <category><![CDATA[hybrid-app-development]]></category>
            <category><![CDATA[react-native-developers]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Tue, 19 Nov 2019 17:04:44 GMT</pubDate>
            <atom:updated>2019-11-20T03:56:46.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ygFb0A1EG-xQRTvVydC7HQ.jpeg" /></figure><p>If you’ve been in to flutter for sometime, you may know the usage of flutter doctor command. If not, the doctor command checks your developer environment and displays a report of the status of your React Native setup and let you know what all to be done to make it work properly. It is used to diagnose if there are any platform dependencies that are pending to be completely setup.</p><p>Recently, a new command was launched as per the<a href="https://facebook.github.io/react-native/blog/2019/11/18/react-native-doctor"> react-native community blog</a> which performs the same as what flutter doctor does. As mentioned in the official blog post in react native community, it was inspired from Expo and Homebrew’s own doctor command with a pinch of UI inspired from Jest.</p><h3>Working</h3><p>The doctor command supports almost all the libraries associated with the react-native like the Cocoapods, Xcode , Android SDK etc. By using the doctor command, it will be easier for the developer to fix the issues with the development environment automatically. Even if doctor isn’t able to fix them automatically, you’ll be given proper links or guides so that you can fix it without hazzling over the internet.</p><h3>How to use react-native doctor</h3><p>The doctor command is a part of the react-native@0.62. If you are using and older version of react-native, you can try it without upgrading by running the command below from the project directory.</p><pre>npx @react-native-community/cli doctor</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*AoANoA10wnx-omqAclESeA.gif" /><figcaption>Source: <a href="https://facebook.github.io/react-native/blog/2019/11/18/react-native-doctor">React Native Blog Post</a></figcaption></figure><h3>Supported checks (as of now)</h3><ul><li>Node.js (&gt;= 8.3)</li><li>yarn (&gt;= 1.10)</li><li>npm (&gt;= 4)</li><li>Watchman (&gt;= 4), used for watching changes in the filesystem when in development mode.</li></ul><p>Specific to the Android environment:</p><ul><li>Android SDK (&gt;= 26), the software runtime for Android.</li><li>Android NDK (&gt;= 19), the native development toolkit for Android.</li><li>ANDROID_HOME, environment variable required by the Android SDK setup.</li></ul><p>And to the iOS environment:</p><ul><li>Xcode (&gt;= 10), IDE for developing, building and shipping iOS applications.</li><li>CocoaPods, library dependency management tool for iOS applications.<br>ios-deploy (optional), library used internally by the CLI to install applications on a physical iOS device.</li><li>ios-deploy (optional), library used internally by the CLI to install applications on a physical iOS device.</li></ul><h3>EndNote</h3><p>This is one useful command for developers to troubleshoot and fix issues in the development environment so that they can spend more time building apps, rather than fixing issues. Huge thanks to react-native community for working on this 🍻 !</p><p>Reference(s):</p><ol><li><a href="https://facebook.github.io/react-native/blog/2019/11/18/react-native-doctor">React Native Blog Post</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3b0df20eec7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Firebase Authentication using React Native 0.60+ and React Native Firebase]]></title>
            <link>https://medium.com/swlh/learn-firebase-authentication-using-react-native-0-60-and-react-native-firebase-2319c4d60ebe?source=rss-fc5f64040a2e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2319c4d60ebe</guid>
            <category><![CDATA[firebaseauthentication]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[react-native-firebase]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Aravind Madhusudhanan Nair]]></dc:creator>
            <pubDate>Wed, 13 Nov 2019 06:07:31 GMT</pubDate>
            <atom:updated>2019-11-19T04:06:34.961Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbD95SG4xXUb8U7fznp9MQ.png" /></figure><p>This is a quick tutorial to make a react native authentication app using react-native-firebase. To start with, Create a new react-native project like something below</p><pre>react-native init learnfirebase</pre><p>Now, we have got a new project with the latest react native and associated dependencies.</p><h4>Step 1: Configure the Firebase console</h4><p>Moving on to the firebase configuration part, Go to the <a href="https://console.firebase.google.com/u/0/"><strong>Firebase Console</strong></a> and create a new Project with name of your choice as shown below:</p><figure><img alt="React-native firebase authentication setup in Firebase console" src="https://cdn-images-1.medium.com/max/1024/1*Zu6fiEyEXrNQI-o0YMcAuA.png" /></figure><p>In step 2, you can either proceed with Google analytics or just skip and choose <strong>Create Project.</strong> Wait for some seconds, and you are up with a new project in the Firebase console. Click on the <strong>Continue</strong> button and proceed to the Project view.</p><p>In the right side of the Project View, you can see a sidebar. Choose <strong>Authentication</strong> from there, and then choose the <strong>Sign-in method</strong> under the Authentication options and enable <strong>Email/Password</strong> from the list.</p><figure><img alt="React-native firebase authentication setup in Firebase console" src="https://cdn-images-1.medium.com/max/1024/1*wngXHDbU-pawZT6TgS8Nwg.png" /></figure><p>Now, open the Project Settings by clicking on the <strong>Gear button</strong> from the sidebar near to Project Overview and then choosing<strong> Project Settings</strong>. At the bottom, you can see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dB8dKHOwcgR2fzYqaPI-ug.png" /><figcaption>Proceed with creating an android app in the firebase project.</figcaption></figure><p>Click on the android logo and proceed with creating a new App in the project by giving the android app package name matching with the project you have created. In the next step, you will get a config file, Download the file and place it in the file path like below</p><pre>{ProjectDirectory}/android/app/google-services.json</pre><p>That’s all we need to do in the firebase console side. Now, let’s proceed with the codes.</p><h4>Step 2: Install and setup the dependencies</h4><p>Start with the installation of <a href="https://www.npmjs.com/package/react-native-firebase">react-native-firebase</a> dependency by opening up your terminal to run this command.</p><pre>npm i react-native-firebase</pre><p>or</p><pre>yarn add react-native-firebase</pre><p>After done with the installation, you need to manually configure the android files to make it work.</p><p>I guess, you remember we have added google-services.json file inside the android/app/directory. In order for Android to parse this file, add the google-services gradle plugin as a dependency to your project in the <em>project</em> level build.gradle file:</p><pre>buildscript {<br> // …<br> dependencies {<br> // …<br> classpath ‘com.google.gms:google-services:4.2.0’<br> }<br>}</pre><p>To apply the plugin to your project, add the following to the <strong>VERY BOTTOM</strong> of your app android/app/build.gradle file:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;</pre><p>Now, we need to add the firebase modules. In the android/app/build.gradle file, add the following:</p><pre>dependencies {<br> // This should be here already<br> implementation project(‘:react-native-firebase’)</pre><pre>// Firebase dependencies<br> implementation “com.google.android.gms:play-services-base:16.1.0”<br> implementation “com.google.firebase:firebase-core:16.0.9”<br> implementation &quot;com.google.firebase:firebase-auth:17.0.0&quot;</pre><pre>…</pre><p>Now, add the RNFirebaseAuthPackage to your android/app/src/main/java/com/[app name]/MainApplication.java:</p><pre>// …<br>import com.facebook.react.ReactApplication;<br><strong>import io.invertase.firebase.auth.RNFirebaseAuthPackage; </strong>/<em>/ ← Add this line</em></pre><pre>public class MainApplication extends Application implements ReactApplication {<br> // …</pre><pre><a href="http://twitter.com/Override">@Override</a><br> protected List&lt;ReactPackage&gt; getPackages() {<br> <a href="http://twitter.com/SuppressWarnings">@SuppressWarnings</a>(“UnnecessaryLocalVariable”)<br> List&lt;ReactPackage&gt; packages = new PackageList(this).getPackages();<br> // Packages that cannot be autolinked yet can be added manually here, for example:<br> // packages.add(new MyReactNativePackage());<br><strong> packages.add(new RNFirebaseAuthPackage()); </strong><em>// ← Add this line<br> return packages;</em><br> }<br> };<br> // …<br>}</pre><h4>Step 3: Baking the code to communicate with Firebase</h4><p>To start with , you need to structure the project in your own way or something like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*jfRAAY4DvjAegF8A9NWqRQ.png" /></figure><p>We will create four screens for our app, these four screens are <strong><em>SplashScreen</em></strong>, <strong><em>SignUp</em></strong>, <strong><em>Login, </em></strong>and <strong><em>Home</em></strong>.</p><p>A <strong><em>SplashPage</em></strong> page gives a loading feel to the user until we determine the auth state of the user, a <strong><em>SignUp screen -</em></strong>for the user account creation, a <strong><em>Login screen</em> — </strong>for<strong> </strong>an existing user login, and a <strong><em>Home</em> <em>screen</em></strong> to show the details of an authenticated user.</p><p>We’re going to be using <a href="https://reactnavigation.org/docs/en/getting-started.html"><strong><em>react-navigation</em></strong></a> and <strong><em>react-navigation-stack</em></strong> for our app’s navigation, so let’s set up our navigator and create our screens with yarn or npm.</p><pre>yarn add react-navigation </pre><pre>yarn add react-navigation-stack</pre><p>and then follow the instructions for completing the installation as per <a href="https://reactnavigation.org/docs/en/getting-started.html"><strong>React Navigation documentation.</strong></a></p><p>Assuming, you have completed all the steps till now, we’ll proceed with creation of the screens.</p><p><strong>SplashPage/index.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41d179beb6e81b0a2987437805abc8be/href">https://medium.com/media/41d179beb6e81b0a2987437805abc8be/href</a></iframe><p><strong>Signup/index.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/507d4ef562ef044af53a5987b65a37b3/href">https://medium.com/media/507d4ef562ef044af53a5987b65a37b3/href</a></iframe><p><strong>Login/index.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/607b11382860711ab5a3360b39fa4564/href">https://medium.com/media/607b11382860711ab5a3360b39fa4564/href</a></iframe><p><strong>Home/index.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ea33a4676b24c0cad40ae6dc5fddf04/href">https://medium.com/media/2ea33a4676b24c0cad40ae6dc5fddf04/href</a></iframe><p>We have created all the basic screens and so, now we can create the navigation of our app inside the <strong>App.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/305a8dc4e5b4cd98a95d5bf52406ae7f/href">https://medium.com/media/305a8dc4e5b4cd98a95d5bf52406ae7f/href</a></iframe><p>Now, at this stage if we run our app it will be stuck at the Splash Screen itself as it is not checking whether the user is authenticated or not. So, now lets proceed to add firebase authentication to the codes we have just created.</p><p>First, we need to check whether the user is authenticated or not from the SplashPage. If the user is authenticated, navigate the user to Home screen, else route him to the Signup page. Here is the new <strong>SplashPage</strong> code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f86cf1548819f55acea66ecfbd1b364c/href">https://medium.com/media/f86cf1548819f55acea66ecfbd1b364c/href</a></iframe><p>We are using Firebase’s <strong>onAuthStateChanged</strong> listener to get the current authentication state of the user. If the user is authenticated, we route them to the Home screen, and if not, we send them to the SignUp screen. Since we’re not logged in at the moment, you should see the Loading screen for a brief moment, and then routed to the SignUp screen at first.</p><p>Now, we need to create a new user. For that we use the <strong>createUserWithEmailAndPassword(email,password) </strong>method and pass the email and password we stored in our states. If there are any errors, it will be displayed or else, after validations the user will be navigated to the Home screen, which shows a successful signup.</p><p>Here is the new <strong>Signup</strong> page :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3d8d832e651c4bfdcba7542d5e0c744/href">https://medium.com/media/f3d8d832e651c4bfdcba7542d5e0c744/href</a></iframe><p>We are there in the <strong>Home</strong> page, and is logged in. But, we don’t have any information about the logged-in user, do we? So, now we will get the current user details from firebase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c7a0a25a55136d7126cd085606f4c0e/href">https://medium.com/media/2c7a0a25a55136d7126cd085606f4c0e/href</a></iframe><p>Now, even after reloading the app, it stays at the Home page instead of Signup page as the user is already authenticated.</p><p>The last thing we need to do is to make the already signed-up users login to our app. The Login process is almost the same. We are using the <strong>signInWithEmailAndPassword(email, password)</strong> to sign in the user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/399978a12c9d8fb8e27d55110e7de5d6/href">https://medium.com/media/399978a12c9d8fb8e27d55110e7de5d6/href</a></iframe><p>…and here are the screens after everything is done right:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*5YKW5Y4zrLhvu7esMi9jNw.png" /></figure><p><strong>That’s it ! We have created a simple Firebase authentication app using react-native. Thank you for reading! 😎 ☕️</strong></p><p>Do comment, if you have any doubts or queries. Also, check the <strong>Github Repo </strong>of this tutorial <a href="https://github.com/aravi365/learn-firebase"><strong>here</strong></a>.</p><p>Always happy to help. Cheers 🍻</p><h4><strong>References:</strong></h4><ol><li><a href="https://rnfirebase.io/docs/v5.x.x/getting-started">React Native Firebase</a></li><li><a href="https://reactnavigation.org/docs/en/getting-started.html">React Navigation</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2319c4d60ebe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/learn-firebase-authentication-using-react-native-0-60-and-react-native-firebase-2319c4d60ebe">Learn Firebase Authentication using React Native 0.60+ and React Native Firebase</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>