<?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 Chiraag on Medium]]></title>
        <description><![CDATA[Stories by Chiraag on Medium]]></description>
        <link>https://medium.com/@chiraag918?source=rss-696b01b6f982------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HOVPC6yHbYfzHcmD</url>
            <title>Stories by Chiraag on Medium</title>
            <link>https://medium.com/@chiraag918?source=rss-696b01b6f982------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:02:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chiraag918/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[I Rebuilt React Hooks from Scratch ⚛️ Here’s What I Learned ]]></title>
            <link>https://medium.com/@chiraag918/i-rebuilt-react-hooks-from-scratch-%EF%B8%8F-heres-what-i-learned-2f4d0dc200b4?source=rss-696b01b6f982------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f4d0dc200b4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[polyfill]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Chiraag]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 23:52:21 GMT</pubDate>
            <atom:updated>2025-09-14T23:52:21.802Z</atom:updated>
            <content:encoded><![CDATA[<p>React Hooks have completely changed the way we write components. They’re simple to use, but for many developers they feel like “magic.” You call useState, and somehow React knows which component and which variable to update.</p><p>But here’s the thing: React Hooks aren’t magic. They’re built on some clever but surprisingly understandable principles. So I decided to <strong>rebuild </strong><strong>useState, </strong><strong>useEffect, and </strong><strong>useRef from scratch</strong> — and here’s what I learned along the way.</p><p>We’ll explore how they’re conceptually similar to React’s internal working, why it’s valuable to understand what’s happening under the hood, and how React itself uses clever tricks (like useReducer inside useState) to achieve the re-rendering behaviour.</p><p>👉 You can play with the full code here: <a href="https://codesandbox.io/p/sandbox/gracious-ellis-rrp9zf">CodeSandbox Template</a>.</p><h3>Why bother re-implementing Hooks?</h3><p>Hooks are fundamental to modern React. They let us manage state, lifecycle, and refs without classes. But as developers, we often just “use” them without deeply understanding:</p><ul><li><strong>How React stores hook values across re-renders?</strong></li><li><strong>How dependency tracking works in </strong><strong>useEffect ?</strong></li><li><strong>Why </strong><strong>useState updates trigger re-renders, but </strong><strong>useRef does not.</strong></li></ul><p>By writing a polyfill, we strip Hooks down to their essence. This gives us a clear mental model of what’s happening inside React every time we call a Hook.</p><h3>Step 1: Setting Up a Hooks System</h3><p>At its core, React keeps track of hooks for each component in a <strong>linked list</strong>, but for simplicity we’ll use an array and an <strong>index pointer</strong> to know which hook call corresponds to which stored value.:</p><pre>// React stores hooks state/value for each component in an array called hooksArr<br>// Uses hooksIndex to access respective hooks state<br><br>const hooksArr = []; // stores state, deps, cleanup, refs<br>let hooksIndex = 0;  // tracks which hook we&#39;re on</pre><ul><li>hooksArr acts as our storage.</li><li>hooksIndex keeps track of which hook is currently being executed.</li><li>Every time the component re-renders, we reset hooksIndex to 0, and as hooks are called in order, we fetch/update the right slot in the array.</li><li>Each hook call (useState, useEffect, etc.) consumes the next slot in hooksArr.</li></ul><p>This ordering is <em>exactly why</em> React enforces: <em>“hooks must be called in the same order on every render.”</em></p><h3>Step 2: Rebuilding useState</h3><p>In React, useState lets you declare a state variable that <strong>persists between re-renders</strong>.</p><pre>const [count, setCount] = useState(0);</pre><ul><li>On the first render, React stores 0 in its internal state array.</li><li>On subsequent renders, React retrieves the stored value instead of reinitialising it.</li><li>Calling setCount updates the value <strong>and schedules a re-render</strong>.</li></ul><p>Here’s the polyfill:</p><pre>import { useReducer } from &quot;react&quot;;<br><br>// useState polyfill<br>// Stores state value in hooksArr<br>const useState = (initialValue) =&gt; {<br>  const currIndex = hooksIndex;<br><br>  // Check if the state at the current hooksIndex exists<br>  // Else store it with initialValue<br>  if (!hooksArr[hooksIndex]) {<br>    hooksArr[hooksIndex] = { value: initialValue };<br>  }<br><br>  // Get the current value<br>  const currValue = hooksArr[hooksIndex].value;<br><br>  // To trigger re-render, uses dispatch from useReducer hook<br>  // React too uses useReducer in useState definition to trigger re-render<br>  const [, rerender] = useReducer(() =&gt; ({})),<br>    forceUpdate = () =&gt; {<br>      // reset hooksIndex to 0, since all hook values will need to be accessed correctly<br>      hooksIndex = 0;<br>      rerender();<br>    };<br><br>  // setState implementation<br>  const setState = (newValue) =&gt; {<br>    let updatedValue;<br><br>    // callback passed to setState<br>    if (typeof newValue === &quot;function&quot;) {<br>      updatedValue = newValue(hooksArr[currIndex].value);<br>    } else {<br>      updatedValue = newValue;<br>    }<br><br>    // update hooksArr with updated value<br>    hooksArr[currIndex] = { value: updatedValue };<br><br>    // trigger re-render<br>    forceUpdate();<br>  };<br><br>  // auto-increment for next hook<br>  hooksIndex++;<br><br>  return [currValue, setState];<br>};</pre><ul><li>It stores value in global hooksArr.</li><li>If it’s the first time running, it initialises with the given value.</li><li>On updates, it overwrites that value.</li><li>To force a re-render, we piggyback on useReducer, <strong>React does the same thing internally</strong>! You can see it in the <a href="https://github.com/facebook/react/blob/16.8.6/packages/react-dom/src/server/ReactPartialRendererHooks.js#L255">React source code</a>. That’s why every state update resets the hook index to 0 and re-runs the component.</li></ul><p>So, our polyfill captures the <strong>idea of persistent state across renders</strong> without any “magic.”</p><h3>Step 3: Rebuilding useEffect</h3><p>In React, useEffect is used for <strong>side effects</strong> — things that happen outside the render cycle:</p><ul><li>Fetching data</li><li>Subscribing to events</li><li>Updating the DOM manually</li></ul><pre>useEffect(() =&gt; {<br>  console.log(&quot;Count changed&quot;);<br>  return () =&gt; console.log(&quot;cleanup&quot;); // optional cleanup<br>}, [count]);</pre><p>How React handles it:</p><ul><li>On first render, it runs the effect.</li><li>On later renders, it compares dependencies ([count]) with the previous ones.</li><li>If dependencies changed, it runs the cleanup (if any), then the new effect.</li></ul><p>Here’s the polyfill:</p><pre>// useEffect polyfill<br>// Stores cleanupFunc &amp; prevDependencies in hooksArr<br>const useEffect = (sideEffect, currDeps) =&gt; {<br>  const currIndex = hooksIndex,<br>    { deps, cleanup } = hooksArr[currIndex] ?? {};<br><br>  // keep depHasChanged as true, since the first run of the hook, hooksArr won&#39;t have hooks state/data and we will need to run the sideEffect once, and then store cleanup function<br>  let depHasChanged = true;<br><br>  // check if dependencies have changed by comparing current dependencies(currDeps) &amp; previous dependencies(deps)<br>  if (Array.isArray(currDeps) &amp;&amp; Array.isArray(deps))<br>    depHasChanged = currDeps.some((dep, idx) =&gt; dep !== deps[idx]);<br><br>  if (depHasChanged) {<br>    // execute previous cleanup function before running new side effect<br>    if (typeof cleanup === &quot;function&quot;) cleanup();<br><br>    // store new cleanup &amp; deps<br>    hooksArr[currIndex] = {<br>      deps: currDeps,<br>      // run new side effect &amp; get the new cleanup<br>      cleanup: typeof sideEffect === &quot;function&quot; ? sideEffect() : null,<br>    };<br>  }<br><br>  // auto-increment hooksIndex for the next hook<br>  hooksIndex++;<br>};</pre><ul><li>Each effect stores its last dependencies and its cleanup function in hooksArr.</li><li>On every render, we compare the new dependencies with the old ones.</li><li>If something has changed, we run the cleanup first (if it exists), then run the new effect, and store its cleanup for next time.</li></ul><p>This reproduces the <strong>dependency-driven lifecycle</strong> of React’s useEffect.</p><p>So when you see useEffect(() =&gt; {}, [dep]), just remember: React is <strong>comparing deps</strong> behind the scenes.</p><h3>Step 4: Rebuilding useRef</h3><p>useRef gives you a <strong>mutable object</strong> that persists across renders. Unlike state, updating it does <strong>not</strong> cause a re-render.</p><pre>const ref = useRef(0);<br>ref.current = ref.current + 1;</pre><p>This is useful for:</p><ul><li>Storing values that don’t need re-renders (like timers or previous props).</li><li>Directly accessing DOM nodes (ref={myRef}).</li></ul><p>Here’s the polyfill:</p><pre>// useRef polyfill<br>// Stores ref value in hooksArr<br>const useRef = (initialValue) =&gt; {<br>  const currIndex = hooksIndex;<br><br>  // initialise ref object<br>  if (!hooksArr[currIndex]) hooksArr[currIndex] = { current: initialValue };<br><br>  // auto-increment hooksIndex for the next hook<br>  hooksIndex++;<br><br>  // return the ref object<br>  return hooksArr[currIndex];<br>};</pre><ul><li>They are just objects with a .current property.</li><li>Unlike state, updating .current doesn’t trigger a re-render — it just mutates the value.</li><li>Our polyfill initialises this object once and persists it in hooksArr.</li></ul><p>This matches React’s behaviour of <strong>keeping mutable values that survive re-renders</strong>.</p><p>It’s essentially just:</p><pre>{ current: value }</pre><p>stored in hooksArr.</p><h3>Step 5: Using Our Polyfills</h3><p>Here’s how we can use our polyfilled Hooks:</p><pre>export default function App() {<br>  const [count, setCount] = useState(0);<br>  const [count2, setCount2] = useState(0);<br>  const ref = useRef(15);<br><br>  const incrementCount = () =&gt; {<br>    setCount((prev) =&gt; prev + 1);<br>  };<br>  const decrementCount = () =&gt; {<br>    setCount((prev) =&gt; prev - 1);<br>  };<br>  const incrementCount2AndRef = () =&gt; {<br>    ref.current = ref.current + 1;<br>    setCount2((prev) =&gt; prev + 1);<br>  };<br>  const decrementCount2AndRef = () =&gt; {<br>    ref.current = ref.current - 1;<br>    setCount2((prev) =&gt; prev - 1);<br>  };<br><br>  const incrementRef = () =&gt; {<br>    ref.current = ref.current + 1;<br>  };<br>  const decrementRef = () =&gt; {<br>    ref.current = ref.current - 1;<br>  };<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;Count changed: &quot;, count);<br>  }, [count]);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;Count2 changed: &quot;, count2);<br>  }, [count2]);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;ref val changed: &quot;, ref.current);<br>  }, [ref.current]);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;React Hooks Polyfill&lt;/h1&gt;<br>      &lt;h2&gt;Count 1: {count} &lt;/h2&gt;<br>      &lt;button onClick={incrementCount}&gt;+&lt;/button&gt;<br>      &lt;button onClick={decrementCount}&gt;-&lt;/button&gt;<br>      &lt;p&gt;Updates only count 1&lt;/p&gt;<br>      &lt;br /&gt;<br><br>      &lt;h2&gt;Count 2: {count2} &lt;/h2&gt;<br>      &lt;button onClick={incrementCount2AndRef}&gt;+&lt;/button&gt;<br>      &lt;button onClick={decrementCount2AndRef}&gt;-&lt;/button&gt;<br>      &lt;p&gt;Updates both count 2 &amp; ref value&lt;/p&gt;<br>      &lt;br /&gt;<br><br>      &lt;h2&gt;Ref Value: {ref.current} &lt;/h2&gt;<br>      &lt;button onClick={incrementRef}&gt;+&lt;/button&gt;<br>      &lt;button onClick={decrementRef}&gt;-&lt;/button&gt;<br>      &lt;p&gt;Updates only ref value&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The App component in the demo stitches these hooks together. You’ll see:</p><ul><li>useState manages count and count2 like normal state.</li><li>useRef keeps track of a mutable ref value.</li><li>useEffect logs changes whenever dependencies update.</li></ul><p>The result feels almost like React itself — because under the hood, React really is just juggling arrays, indexes, and dependency checks in a more optimised way.</p><h3>Why This Matters</h3><ul><li><strong>Better Debugging:</strong> Understanding hooks’ mechanics helps debug tricky bugs (like why changing a ref doesn’t re-render).</li><li><strong>Avoiding Pitfalls:</strong> You’ll never again forget that Hooks must be called in the same order.</li><li><strong>Deeper Learning:</strong> Looking at the internals of useState, useEffect, and useRef makes you appreciate the simplicity and brilliance of React’s design.</li></ul><h3>Final Thoughts</h3><p>This polyfill is not production-ready — but it captures the <strong>core mental model of how React Hooks work</strong>. React’s real implementation is far more optimised and complex, but conceptually, it’s not that different.</p><p>Next time you write const [state, setState] = useState(), you’ll know there’s an array and an index silently working behind the scenes, keeping your component in sync.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f4d0dc200b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Notes from Supervised Machine Learning: Regression and Classification — Part 1]]></title>
            <link>https://medium.com/@chiraag918/notes-from-supervised-machine-learning-regression-and-classification-part-1-88cc58121a48?source=rss-696b01b6f982------2</link>
            <guid isPermaLink="false">https://medium.com/p/88cc58121a48</guid>
            <dc:creator><![CDATA[Chiraag]]></dc:creator>
            <pubDate>Wed, 14 May 2025 06:01:32 GMT</pubDate>
            <atom:updated>2025-05-14T06:06:22.279Z</atom:updated>
            <content:encoded><![CDATA[<h3>Notes from Supervised Machine Learning: Regression and Classification — Part 1</h3><p>Notes from the week 1 material. This covers liner regression, cost function, and gradient descent</p><ul><li>What is machine learning?</li><li>Supervised learning</li><li>Unsupervised learning</li><li>Regression — linear regression</li><li>Cost function</li><li>Visualizing cost function</li><li>Gradient descent</li><li>Effective gradient descent</li></ul><h3>Overview of machine learning</h3><p>We use machine learning application without explicitly knowing about. here are some examples —</p><ul><li>Web search</li><li>Labelling your friends in a photo on a social network</li><li>Movie recommendation on Netflix or any other streaming service</li><li>Speech Recognition like siri assistant</li><li>Spam filter</li><li>Machine Learning in optimise turbine power generation</li><li>Computer vision on factory floors inspecting components</li></ul><p>We can write a program to find optimal distance b/w 2 points in a graph, but for things where we don’t know how to write a program for ex:</p><ul><li>Speech Recognition, street view of map, recommender ads, finding payment frauds etc…</li></ul><p>Machine learning comes into the play when we do not know how to explicitly write a program for example —</p><ul><li>Finding a disease in the x-ray</li><li>Self-driving car</li><li>Recognizing human speech</li></ul><p>ML will most likely impact significantly almost all fields/industries in the near fuutre.</p><p><strong>AGI — Artificial General Intelligence</strong> — intelligent system as a human. Will take longer than hyped and will mostly need to be built using learning algorithms taking the human brain/mind inspiration.</p><p>It is also important to use the right ML algorithm for the right problem.</p><h3>Supervised machine learning vs. unsupervised machine learning</h3><p>As per Arthur Samuel machine learning is a “Field of study that gives computers the ability to learn without being explicitly programmed.”Arthur Samuel wrote a computer program to play checkers programs. The computer program was allowed to play against itself and determine which positions would help to win and thereby training itself, it was able to learn itself to play checkers better without explicitly being programmed. More opportunities you give to such programs/learning algorithm to learn, better it will perform.</p><p>Learning algorithms are great tools and it is equally important that you learn how to apply them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z19dcOwmuJZKlEcL8EObrA.png" /></figure><h3>Supervised learning</h3><p>99% of economic value is created by supervised learning. In supervised learning, you take a data set that has an input/variable say ‘x’ and output target/label ‘y’ and you provide many examples of this data set to a learning algorithm.</p><p>By seeing this mapping (correct label ‘y’ of an input ‘x’), a learning algorithm learns and when you provide just an input ‘x’, it will predict ‘y’</p><p>Some examples are -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*aPDVYqKduDeSxNTx.png" /></figure><p>Machine learning examples — image by the author</p><h3>Regression and Classification</h3><p>Regression and classification are 2 major types of supervised learning. Predicting prices of houses is an example of regression, here your learning algorithm can predict any number. In classification, it predicts a category that belongs to a small set of possible outcomes.</p><p><strong>Example of Regression: Housing Price Predictor</strong></p><p>Regression models try to output a number out of infinite number-set outpt targets/lables from X-Y mappings. In the below example, we have a plot of house size on X vs price on Y. House size would be X(input variable) and price Y would be the output(target/label) in X-Y mapping dataset. Now, to predict for a random X input, we would need the algorithm to fit a line or a curve or a function more complex, throught the plotted points. So we need a learning algorithm which would accurately choose a function to best fit the plot to output accurate predictions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8iFz1N6-m77IeP4Mk7PRQ.png" /></figure><p><strong>Example of Classification: Breast cancer detection</strong></p><p>Classification models try to output a number out of a finite set of output classes/categories from X-Y mappings. In the below example, we have a plot of cell size and whether they are benign or malignant(with diff cancer types). Since, we have one input, cell size, we can plot it on 1D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ixu9bKd25MzaI3yVkCboUA.png" /></figure><p>If the classification algorithm had 2 inputs. There can be multiple such input parameters which our learning algorithm should take account to when predicting a probable output when dealing with supervised learning. In the below plot, the algorithm will draw a line in b/w benign &amp; malignant classes, and if an unknown input X is tested, then based on which category output Y falls, that will be the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mWULEzstU18unfqYTvmUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sl7N6jY1kRAgO4EsUuURcw.png" /></figure><h3>Unsupervised learning</h3><p>In supervised classification, training set has labelled output data. In the unsupervised learning, output label is not provided. Learning algorithm then creates clusters of all input data. For example, a dataset of tumors that is labelled with benign or malignant is used in supervised learning. If the dataset does not have this label, unsupervised learning will create clusters from the input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sO83N9QaXYd06J2X.png" /></figure><p>Supervised vs. unsupervised clustering examples — image by Andrew Ng</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W1-8ABvT2VKe6UfJ1JdiBg.png" /></figure><p>In Unsupervised learning, the learning algorithm isn’t bothered outputting labels or classes but instead finding patterns in the dataset and identifying different groups made of similar items, in them to be able to draw inferences from these groups.</p><h3>Using unsupervised learning</h3><ul><li>Grouping similar news articles, since news topics change daily, labelling them manually is not a good approach. As it can be seen in the below example, “panda giving birth to twins in a zoo” news has been grouped together using ML, and the common thing to be noted is the words, panda, twin, birth, zoo etc… are the common words in the headline which would help the ML to cluster these data together.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zmYTmo3TZF0i5AlWmmPmOg.png" /></figure><ul><li>Grouping different types of people based on their gene makeup. Here, in the below example, each column identifies a person and each row would be a specific gene, where green determines whether the gene is active and red where it is inactive and this can be a percentage of active/inactive, where the gradient of the color depicts it. Genes can be eye sight, height or hatred towards vegetables etc…</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFlx8qaN0R50WRRKL2fdrw.png" /></figure><ul><li>Customers/users clustering to understand their segments</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NraJcRXuxM1Hj-UMN76Qg.png" /></figure><h3>Other types of unsupervised learning</h3><p>Other than clustering, unsupervised learning is also used for anomaly detection(for fraud detection) and dimensionality reduction(reducing the sample size).</p><h3>Jupyter notebook</h3><p>Most widely used tool by machine learning and data science practitioners.</p><h3>Regression Model</h3><p>Regression is a type of supervised learning which is the most popular. In Regression there are different models but here we focus on Linear Regression, speicifically, Linear Regressio with a single variable or a Univariate Linear Regression Model.</p><p>Linear regression model is used to fit a line across your data points. House pricings make a great starting example for this. You just take one data point that is the size of the house and based on that, you can predict the price of another house. So you plot all the pricing and try to fit a line that should be closest to all data point. Finding this line that fits best the data point is “linear regression”. Regression model predicts a number that could be any number depending on the underlying data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YFrOGWv7NztpzbPu0HxcyQ.png" /></figure><p>Another popular model is classification model, here output is limited to a small set of possible outcomes such as if an image is of a cat or a dog. If this outcome set has ten possible diseases and outcome will be limited to this set only.</p><p>Another way of representing a plot of data is via table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOQaqQRNJCJYCN_VXGGyww.png" /></figure><h3>Some notations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GXrGWKTvjQQTYGsO15RWfA.png" /></figure><p>Training set — the data that has inputs and outputs and is used to train an algorithm is called training set.</p><ul><li>Input variable ‘x’ also called as feature</li><li>Output variable ‘y’ also called as target</li><li>A training set will have many training examples and each example can be identified by x superscript in parenthesis i and y superscript in parenthesis i. So for an ith training example in the training set. it will be written as</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*LWMq_tFpfbou12r0.png" /></figure><p>a training set representation</p><h3>Model notation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*kityQkE1Jj2pZ1KT.png" /></figure><p>Model example — image from deeplearning.ai</p><p>Training set is input\trained on to the learning algorithm which then produces a model\hypothesis function which predicts the y-hat value for any input x.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n24ihLzJ-EYMDtbBOWHXTw.png" /></figure><p>Training set — having datapoints with features and targets values</p><p>Learning algorithm — it produces some function ‘f,’ also known as hypothesis</p><p>This function ‘f’ takes an input feature and predicts a value y^ (y hat)</p><p>y hat is predicted value</p><p>y denotes the target value (that is from the training set)</p><p>A simple liner function (a straight line) is denoted below —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*pnm-suRg48DtZMw8.png" /></figure><p>Linear function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jSDBWhtgRqMKoaWWEBlNGA.png" /></figure><p>Here for a value of x, predicted value will be wx +b. w and b are called parameters. Parameters in a model influence how good the prediction is.</p><p>It can also be represented as f of x and do not need to put w and b in front of ‘f’</p><p>Different plots for different values of w &amp; b, for linear regression model with straight line function as model (wx + b = y-hat)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkjTEzZVjvM8aEUs-TaE2g.png" /></figure><p>Plot 1: if w = 0, then f(x) is dependent only on constant b, hence output will be a constant</p><p>Plot 2: if b= 0, &amp; w = 0.5 or some value, then f(x) is linearlly proportional to x. The slope of the line will be w = 0.5, according to:</p><p>1. <strong>Using the Two Points</strong></p><p>The formula for the slope m is:</p><p>m = (y2−y1) / (x2−x1)</p><p>This gives the rate of change in y with respect to x.</p><p>2. <strong>Using the Line’s Equation</strong></p><p>If the line is in the form y=mx+by = mx + by=mx+b, then mmm is the slope directly.</p><p>Plot 3: if b= 1, &amp; w = 0.5 or some value, then f(x) is linearlly proportional to x similar to plot 2. The slope of the line will also be w = 0.5, but plot will be shifted by b on y-axis.</p><p>There are non-liner functions too that can be used for regression, but to begin with we are using a liner function only.</p><h3>Cost function</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGMWhAmrY55_kfZzbUbFbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaqTyFDugllMpFM3kLpWDw.png" /></figure><p>In order to build a liner regression model, i.e. trying to find out which straight line is going to be the best fit. A cost function enables us to find the best fit. For example, we are discussing house pricing and have all data points. Once we have found a straight line, for any point x, model will predict ‘y hat’, that will be slightly different than the ‘y’. We square this error and sum them up for all data points and divided by 2 times of number of data points (m).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*khXuWnNLP8hpGxNj.png" /></figure><p>Cost function — Image from Deeplearning.ai</p><p>The best cost function is the lowest value that we can get for all data points in the training set. The goal is to minimize w,b for function J(w,b).</p><p>Tuning w &amp; b values will allow us to reduce the squared-error cost function value. For simplicity, since, we made b = 0, we only need to tune w. Here’s plot of x vs J(x) for diff values of w and their respective x vs f(x) for that w.</p><p>Training set is: [(1,1), (2,2), (3,3)]</p><p>Plot 1:</p><p>w = 1 =&gt; J(w) = 0, ideal cost function value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBMhJAHJM2tlDA5tKPCOuw.png" /></figure><p>Plot 2:</p><p>w = 0.5=&gt; J(w) = 0.58</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WYxwUeePcS_O3784nTyMTw.png" /></figure><p>Plot 3:</p><p>w = 0 =&gt; J(w) = 2.3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkoCTCMbjNxWbxc4kXr6_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ybxYvCKyafgvPw5jslJdjg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wttqtf2ug8F1l7xk8jprhQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WER6voAgl3ozH7oB_qrMcw.png" /></figure><p>Here is a graph for different w for the cost function J. Here on x axis, we have value of w and on y axis cost. Plot all values for different w and find out the minimum J(w), here this is for w =1, here b was equal to zero to keep it simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*embe2IW5lBA-fnqw.png" /></figure><p>Cost function — Image from Deeplearning.ai</p><p><strong>Visualizing Cost function</strong></p><p>So far, we have seen following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3rhOZlgksRve1lGK.png" /></figure><p>Image by deeplearnig.ai</p><p>Now once we start adding b along with w, the resultant graphic will look like a soup bowl (3D plot of w &amp; b vs J). This is also represented by a contour graph (2D representation of a 3D plot), where all points at different heights are available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*aIyVraYOj3YYgWhp.png" /></figure><p>Example of a contour map — image by deeplearning.ai</p><p>Key idea is that J is same for an ellipse in the contour map. In the example able all three points (blue, yellow, and green x) are resulting in the same cost of J since all of them are on the same ellipse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8RWGtX2MPVgYtNDXVp8yw.png" /></figure><p>Here, the 3 set of values of w &amp; b, have plots for x vs f(x), w-b vs J (3D plot) and w-b countour plot, where J is the value of different contours, where each countour have the same height for diff w-b values. Countour plots to easily visualise 3D plots.</p><p>Different w-b value plots:</p><p>Bad w-b plot, J is very far from the lowest value at the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lgce8L84bFgWq4PVXsk2rw.png" /></figure><p>Better than previous plot but still a bad w-b plot, J is far from the lowest value at the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uf6VfEcrUCZvNtFhyGvzA.png" /></figure><p>Bad w-b plot, J is very far from the lowest value at the center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wJcCdqAH9UJR6vXqIYm84w.png" /></figure><p>Best w-b plot, J is close to the lowest value at the center. f(x) seems to fit data nicely and J cost function value is also minimal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y74XYDXdQruqxNekrftpVQ.png" /></figure><h3>Gradient Descent</h3><p>Gradient descent algorithm is used to find out the minimum value of cost function J(w, b). Also, used in training Neural Networks. Gradient descent algorithm is one of the most important building blocks in the machine learning.</p><p>Gradient descent can be applied to other general functions as well. For example, multivariate linear regression, where cost function has n parameters J(w_1,w_2,…w_n, b).</p><p>For linear regression function, you can start with any initial value, in practice it can 0 for w and b and keep changing them a little till you get the minimum J.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFfP9wUcfmQ4IbfwpffM7w.png" /></figure><p>Gradient Descent Algorithm:</p><ol><li>Start with some w, b values. For Linear Regression, it doesn’t matter, so we can start with w = 0 &amp; b =0.</li><li>Spin around 360deg, and baby step(alpha value) in the direction(derivative d(J(w,b))/dw) of the max steep descent.</li><li>Repeat 2 till we reach a local monimum.</li><li>If we had started at a different point initially, with different w-b values, we might’ve ended in a different local minima.</li></ol><p>Notes:</p><ol><li>For some cost function, it can have more than one possible minimum. In this case, plot of J(w,b) vs (w,b) won’t be bowl/hammock shaped.</li><li>With Linear Regression, cost function will always be Squared Error Cost Function and it’ll be bow shaped.</li><li>Neural Networks will have complex cost functions and their plots will reflect that.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dETElJIyCvlzXGXkLBPk0A.png" /></figure><p>For linear regression — squared error cost function, J is always a bowl shape. For functions that are not squared error cost functions (neural network), there can be multiple minimums and the cost function shape is not bowl or hammock shape. One way to imagine is that you are in a golf course having small mounds. You are on top of the any mound and you need to descent to the lowest point. One way of doing this is to look around and take the steepest descent. Starting point matters as you will end up at different lowest point based on your starting point. In summary there can be more than one minimum and your starting point plays a role in it.</p><h3>Implementing gradient descent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*blHgnm2yT7lwKCvz.png" /></figure><p>In gradient descent algorithm, we change the value of w and b by a little and assign changed values to w and b. In the equation above ‘=’ equal sign operator is used for assignment. Alpha is the learning rate, a big alpha mean a big step, a small alpha is a small step, derivative of J of w and b decides the direction of the descent.</p><p>Correct implementation of this algorithm requires simultaneous updates to w and b value.</p><p><strong>Important:</strong></p><ol><li>If alpha is very large -&gt; large baby steps (may not converge)</li></ol><p>2. If alpha is very small -&gt; small baby steps (longer to converge)</p><p>3. Derivative term determines which direction we’ll take -&gt; direction with steepest descent -&gt; basically derivative is the rate of change of that qty, here, cost function.</p><p>4. At convergence point or at a local minima, values of w &amp; b no longer change when using the ‘Simaltaneous update’ formulas.</p><p><strong>Gradient descent intuition</strong></p><p>Simplifying the cost function, to better understand Gradient Descent intuition. So we set b = 0 and now J(w) only depends on w.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ai8kQ9sQKVz8oyxT.png" /></figure><p>Image from Deeplearning.ai</p><p>Objective is to minimize J of w and b. Here in the equation above alpha is learning rate and derivative of J(w, b) decides the direction of the movement.</p><p>To better understand, simplify the equation by making b equal to zero. In this case the function will look like. To easily undertsand, 2D plot of J(w) vs 3D plot or J(w) vs w vs b which would be the case in J(w, b), if we considered both w &amp; b.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vsih9STDHVwe6WBD.png" /></figure><p>Here w is on x axis, J(w) is on y axis. For a value of w that is on the right side of the minimum, take any point and draw a tangent line. Tangent will be pointing up so the slope will be positive, for any positive number, w will be reduced, so by each step we will be moving towards the minimum.</p><p>If we start at the left side of the minimum and draw a tangent on any point, this line will be point down and the slope will be negative, in this scenario will be adding the derivative value to the w and w will increase and start moving towards minimum.</p><p>Side note: The tangent line is said to be “going in the same direction” as the curve and that’s what decides if the tangent line is pointing downward or upward.</p><p>Slope of a line is derivative of the curve J at that point where it touches the curve.</p><h3>Learning Rate</h3><p>Alpha is the learning rate and determines how big a step is going to be. If we take a very small Alpha, it will move very slow thus will take very long time to find the minimum. If learning rate is very big, it will not only miss global minimum but will cause divergence.</p><p>Choice of Learning Rate influences the efficiency of the Gradient Descent Algo. If choosen poorly gradient descent may not work and instead of diverging, may converge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZR-kLl9qy4mTpoIJuZiQQ.png" /></figure><h3>What happens if you are already at a local minimum</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FKKDWYswQ0ygLGyW-uFyAA.png" /></figure><p>In the example shown, the function is not a squared error sum function and has 2 local minimums. If you are at a local minimum, the slope is 0 hence the partial derivative of function f of x will be zero so when you take next step, you multiply learning rate with the resultant derivative that is zero hence value of w will remain unchanged.</p><p>Near a local minima, gradient descent takes smaller steps.</p><h3>Local minimum can be reached with a fixed learning rate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0yEXk6zb3grdGoYK.png" /></figure><p>In the previous image, as we start from a point A and update value to w, we see that in the next step the slope is less than the previous step, hence derivative becomes small and the update steps become smaller. As a result, this step becomes smaller and smaller as we approach global minimum.</p><h3>Gradient descent for linear regression</h3><p>We have discussed so far</p><ul><li>Linear regression model</li><li>Cost function</li><li>Gradient descent algorithm</li></ul><p>Let us look gradient descent in more details</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u-nvaRNTlh058CiN.png" /></figure><p>Image from Deeplearning.ai</p><p>In gradient descent, we are calculating w by finding out the derivative of cost function J with respect to w. For calculating b, we are finding out the derivative of cost function J with respect to b. Above slide shows the resulting values. Take the cost function that is 1 over 2m into the sum of all term from 1 to m, (f of x super i minus y super i) squared. replace f of x super i with w.x super i + b. Do the partial derivative and you get above terms. J with respect to w has x super i and J with respect to b does not have x super i.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S3ycrpFZiC192lP0-64VQQ.png" /></figure><p><strong>Gradient Descent Alogorithm with both parameters (w &amp; b) in cost function:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HgMGvi8Mh5hKACW7apD8KQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhEKZlJnNoLTFt5n-c1DOQ.png" /></figure><p>For Linear Regression Model, cost func. J(w) vs w vs b is bowl shaped, technically, its called a <strong>Convex Function</strong>.</p><p>Convex functions only have one global minima and no other local minimas, and we don’t have to worry about making gradient descent work for cost funcs. with multiple local minimas.</p><p>As long as alpha is chosen appropriately, it will always converge using gradient descent for Linear Regression with Squared Error Cost Function.</p><p><strong>Gradient Descent in action:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Utw4l94a_BL8HWRnGA-Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jhVJP_hFjGIHsX8gfSk7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BNqVncZvgXUBOIv7bokobw.png" /></figure><h3>Batch gradient descent</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w8RNMnnjBzUcesD-KpPNFg.png" /></figure><p>Batch gradient descent means that at each steps all data in the training set are used to calculate partial derivatives instead of subset of data in the training set.</p><h3>Summary</h3><p>This week covers an overview of machine learning applications, introduces notations, introduces a simple regression model, cost function and gradient descent.</p><h3><strong>Acknowledgement</strong></h3><p>My notes took <a href="https://medium.com/u/5b5e3bdec1ea">Pradeep Goel</a>’s notes as the base on top of which I’ve added more conetnt: <a href="https://medium.com/@pradeepgoel/notes-from-supervised-machine-learning-regression-and-classification-part-1-b5212591916c">https://medium.com/@pradeepgoel/notes-from-supervised-machine-learning-regression-and-classification-part-1-b5212591916c</a>. Would like to extend my gratitude towards <a href="https://medium.com/u/5b5e3bdec1ea">Pradeep Goel</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88cc58121a48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Native Timers in React Native: A Case Study of the NEWME App]]></title>
            <link>https://medium.com/@chiraag918/implementing-native-timers-in-react-native-a-case-study-of-the-newme-app-7baf5dbf7883?source=rss-696b01b6f982------2</link>
            <guid isPermaLink="false">https://medium.com/p/7baf5dbf7883</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[objective-c]]></category>
            <dc:creator><![CDATA[Chiraag]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 09:19:41 GMT</pubDate>
            <atom:updated>2024-11-04T09:19:41.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JykI4NziNiXgnciNCm32w.png" /></figure><p>In the rapidly evolving world of mobile applications, user experience is paramount. For our fast fashion app, NEWME (<a href="https://play.google.com/store/apps/details?id=com.newme.mobile&amp;hl=en_IN&amp;pli=1">Android</a> &amp; <a href="https://apps.apple.com/in/app/newme-freshest-fashion-fastest/id6445953273?platform=iphone">iOS</a>), targeted towards women, it was essential to ensure that every interaction felt seamless and responsive. We encountered performance issues while working with JavaScript timers. When making API calls, especially with large JSON payloads, the timer UI would freeze or would jump ahead by a few seconds, leading to a sub-optimal experience for our users.</p><p>To address these issues, we turned to native timers — an effective solution that allows us to leverage the performance of the underlying mobile platforms (iOS and Android). Native timers operate outside of the JavaScript thread, significantly reducing the risk of UI freezes. By implementing native code for our timers, we could ensure smoother interactions, more accurate countdowns, and an overall improved app performance.</p><p>This blog post will outline the steps we took to integrate native timers into our React Native application, the benefits we observed, and other areas where native functionalities can enhance the user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*-bJZFEcjYEy3Zry4TBcO-Q.png" /><figcaption>Timer Module snap shot from the NEWME app</figcaption></figure><h3>Why Native Timers?</h3><p>JavaScript timers, while easy to implement, can become a bottleneck in performance-sensitive applications. They can often lead to UI freezing, especially when heavy computations or API calls are involved. In our case, using JSON.parse() on API responses while simultaneously managing timers caused noticeable delays in UI updates. Users expect real-time feedback, especially in a fast-paced shopping environment where seconds can make a difference. By switching to native timers, we aimed to achieve:</p><ul><li><strong>Smooth UI Performance</strong>: Native timers run on the native thread, preventing UI blocking.</li><li><strong>Improved Accuracy</strong>: Native implementations provide more precise timing mechanisms compared to JavaScript.</li></ul><h3>Steps to Implement Native Timers</h3><blockquote><strong>Modify Android Files</strong></blockquote><p>For Android, we had to create a TimerModule. This approach allowed us to handle countdown events and send updates back to the JavaScript side.</p><p><strong>TimerModule.kt</strong><br>We created a TimerModule to handle the countdown logic. Using Java&#39;s Timer and TimerTask, we managed the countdown efficiently without blocking the UI thread.</p><pre>import java.util.Timer<br>import java.util.TimerTask<br><br>class TimerModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {<br><br>    private var timer: Timer? = null<br>    private var remainingTime: Long = 0<br><br>    override fun getName(): String {<br>        return &quot;TimerModule&quot;<br>    }<br><br>    @ReactMethod<br>    fun startCountdown(endTime: Double) {<br>        stopCountdown() // Stop any existing countdown<br><br>        // Calculate remaining time in milliseconds<br>        remainingTime = (endTime * 1000).toLong() - System.currentTimeMillis()<br>        if (remainingTime &gt; 0) {<br>            timer = Timer()<br>            timer?.scheduleAtFixedRate(object : TimerTask() {<br>                override fun run() {<br>                    remainingTime -= 1000<br>                    if (remainingTime &lt;= 0) {<br>                        sendEvent(0)<br>                        stopCountdown()<br>                    } else {<br>                        sendEvent(remainingTime / 1000)<br>                    }<br>                }<br>            }, 0, 1000)<br>        }<br>    }<br><br>    @ReactMethod<br>    fun stopCountdown() {<br>        timer?.cancel()<br>        timer = null<br>    }<br><br>    private fun sendEvent(remainingTime: Long) {<br>        val params = WritableNativeMap()<br>        params.putDouble(&quot;remainingTime&quot;, remainingTime.toDouble())<br>        reactApplicationContext<br>            .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)<br>            .emit(&quot;CountdownEvent&quot;, params)<br>    }<br>}</pre><p><strong>TimerPackage.kt</strong><br>Next, we defined the package to ensure the timer module could be imported throughout the app.</p><pre>class TimerPackage : ReactPackage {<br>    override fun createNativeModules(reactContext: ReactApplicationContext) =<br>        listOf(TimerModule(reactContext))<br><br>    override fun createViewManagers(reactContext: ReactApplicationContext) = emptyList&lt;ViewManager&lt;*, *&gt;&gt;()<br>}</pre><p><strong>MainApplication.kt</strong><br>Finally added the TimerPackage to our MainApplication.kt, enabling our React Native app to utilize the native timer functionality seamlessly.</p><pre>import com.newme.mobile.TimerPackage<br><br>class MainApplication : Application(), ReactApplication {<br>    override fun getPackages(): List&lt;ReactPackage&gt; {<br>        return PackageList(this).packages.apply {<br>            add(TimerPackage())<br>        }<br>    }<br>}</pre><blockquote><strong>Modify iOS Files</strong></blockquote><p>For iOS, we similarly created a TimerModule using NSTimer.</p><p><strong>TimerModule.h</strong><br>We define the interface for our timer module.</p><pre>#import &lt;React/RCTBridgeModule.h&gt;<br>#import &lt;React/RCTEventEmitter.h&gt;<br><br>@interface TimerModule : RCTEventEmitter &lt;RCTBridgeModule&gt;<br>@end</pre><p><strong>TimerModule.m</strong><br>The implementation for iOS follows a similar logic as Android.</p><pre>#import &quot;TimerModule.h&quot;<br><br>@implementation TimerModule {<br>  BOOL hasListeners;<br>  NSTimer *timer;<br>  NSDate *endDate;<br>}<br><br>RCT_EXPORT_MODULE();<br><br>- (NSArray&lt;NSString *&gt; *)supportedEvents {<br>  return @[@&quot;CountdownEvent&quot;];<br>}<br><br>- (void)startObserving {<br>  hasListeners = YES;<br>}<br><br>- (void)stopObserving {<br>  hasListeners = NO;<br>}<br><br>RCT_EXPORT_METHOD(startCountdown:(double)endTime) {<br>  dispatch_async(dispatch_get_main_queue(), ^{<br>    if (timer) {<br>      [timer invalidate];<br>      timer = nil;<br>    }<br>    endDate = [NSDate dateWithTimeIntervalSince1970:endTime];<br>    timer = [NSTimer scheduledTimerWithTimeInterval:1.0<br>                                             target:self<br>                                           selector:@selector(timerFired)<br>                                           userInfo:nil<br>                                            repeats:YES];<br>  });<br>}<br><br>RCT_EXPORT_METHOD(stopCountdown) {<br>  [timer invalidate];<br>  timer = nil;<br>}<br><br>- (void)timerFired {<br>  if (!hasListeners) {<br>    [self stopCountdown];<br>    return;<br>  }<br><br>  NSTimeInterval remainingTime = [endDate timeIntervalSinceNow];<br>  if (remainingTime &lt;= 0) {<br>    [self sendEventWithName:@&quot;CountdownEvent&quot; body:@{@&quot;remainingTime&quot;: @0}];<br>    [self stopCountdown];<br>  } else {<br>    [self sendEventWithName:@&quot;CountdownEvent&quot; body:@{@&quot;remainingTime&quot;: @(ceil(remainingTime))}];<br>  }<br>}<br><br>@end</pre><blockquote><strong>Create a Custom Timer Hook</strong></blockquote><p>We developed a custom React hook, useTimer.ts, to encapsulate the timer logic for easy integration within our React components.</p><pre>import { useEffect, useRef } from &#39;react&#39;;<br>import TimerModule from &#39;@components/timer-module/TimerModule&#39;;<br>import { isNumber, isUndefinedOrNull } from &#39;@utils&#39;;<br><br>const defaultTimeLeftState = { days: 0, hours: 0, minutes: 0, seconds: 0 };<br><br>export const formatTimeLeft = (time) =&gt; {<br>    if (!isNumber(time)) return defaultTimeLeftState;<br><br>    const days = Math.floor(time / (60 * 60 * 24)),<br>          hours = Math.floor((time % (60 * 60 * 24)) / (60 * 60)),<br>          minutes = Math.floor((time % (60 * 60)) / 60),<br>          seconds = Math.floor(time % 60);<br><br>    return { days, hours, minutes, seconds };<br>};<br><br>const useTimerHook = (timeLeft, setTimeLeft, initialTime) =&gt; {<br>    const hasTimerStarted = useRef(false);<br><br>    useEffect(() =&gt; {<br>        TimerModule.stopCountdown();<br><br>        if (!isNumber(initialTime) || initialTime &lt;= 0 || typeof setTimeLeft !== &#39;function&#39; || isUndefinedOrNull(timeLeft)) {<br>            setTimeLeft({});<br>            return;<br>        }<br><br>        const subscription = TimerModule.addListener(event =&gt; {<br>            if (event.remainingTime &gt;= 0) setTimeLeft(formatTimeLeft(event.remainingTime));<br>        });<br><br>        if (!hasTimerStarted.current) {<br>            hasTimerStarted.current = true;<br>            const endDate = new Date(Date.now() + initialTime);<br>            TimerModule.startCountdown(endDate.getTime() / 1000);<br>        }<br><br>        return () =&gt; {<br>            setTimeLeft({});<br>            hasTimerStarted.current = false;<br>            TimerModule.stopCountdown();<br>            TimerModule.removeListener(subscription);<br>        };<br>    }, [initialTime]);<br>};<br><br>export default useTimerHook;</pre><blockquote><strong>Utilise the Timer in Components</strong></blockquote><p>We then integrated our custom hook into a React Native component, allowing us to display countdowns easily.</p><pre>const TimerComponent = () =&gt; {<br>    const [timeLeft, setTimeLeft] = useState({});<br>    useTimerHook(timeLeft, setTimeLeft, initialTime);<br><br>    return (<br>        &lt;Text&gt;{`Time left: ${timeLeft.hours}:${timeLeft.minutes}:${timeLeft.seconds}`}&lt;/Text&gt;<br>    );<br>};</pre><h3>Benefits of Using Native Timers</h3><p>Transitioning to native timers brought several significant benefits:</p><ol><li><strong>Performance</strong>: Native timers operate on the native thread, which means they can execute without hindering the performance of the JavaScript thread. This separation helps maintain smooth UI updates, even during heavy computational tasks.</li><li><strong>Accuracy</strong>: Native implementations deliver precise timer calculations. In a fast-paced shopping environment, where users rely on accurate countdowns for promotions, this reliability is crucial.</li><li><strong>User Experience</strong>: The transition to native timers has transformed our app’s interactivity. Users can now enjoy real-time countdowns without interruptions, enhancing their engagement and satisfaction with the app.</li><li><strong>Scalability</strong>: As our app grows and incorporates more features — like enhanced promotions, live sales, or complex animations — native functionalities can easily scale to meet increased demands without sacrificing performance.</li><li><strong>Reduced JavaScript Overhead</strong>: Offloading time-sensitive tasks to native modules reduces the load on the JavaScript engine, allowing it to focus on other crucial aspects of the application, such as rendering UI components and handling user interactions.</li></ol><h3>Further Improvements for the Timer Module</h3><p>As we refine our native timer implementation in the NEWME app, we are considering several enhancements to ensure it meets our evolving needs and maximises user engagement. Here are some key improvements we’re exploring:</p><h4>1. Pause and Resume Functionality</h4><p>Adding the ability to pause and resume timers would provide users with greater control. This feature is particularly useful during sales events where users may need to step away or multitask. Implementing this functionality will enhance the user experience by allowing flexibility without losing track of remaining time.</p><h4>2. Improved Error Handling</h4><p>Building robust error handling mechanisms will ensure the timer operates smoothly across various scenarios. This includes gracefully managing cases where the timer might fail to start, ensuring that users receive appropriate feedback if there are issues, and implementing retries where necessary.</p><h4>3. Multiple Timers Support</h4><p>Expanding the module to support multiple concurrent timers would allow users to track several events at once. This could be beneficial for promotions or sales that involve different countdowns, such as multiple product launches or limited-time offers.</p><h3>Conclusion</h3><p>The decision to implement native timers in our NEWME app has proven invaluable in enhancing performance, accuracy, and overall user experience. By utilising the native capabilities of iOS and Android, we effectively addressed the challenges posed by JavaScript timers, ensuring that our app remains responsive and engaging for our audience.</p><p>As we continue to innovate and expand the features of NEWME, leveraging native functionalities will play a critical role in maintaining our competitive edge. The successful integration of native timers not only resolved our immediate challenges but also laid a strong foundation for future enhancements. We look forward to exploring more native capabilities to enrich our users’ experiences and provide them with the best possible shopping journey in the fast fashion landscape.</p><h3>Contact Us</h3><p>You can reach out to us on LinkedIn at <a href="http://linkedin.com/in/kushagra-agarwal-3a2709127">@kushagra</a> or <a href="https://www.linkedin.com/in/chiraag-arun-kumar-a959441a4?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_contact_details%3BztOUraMcQwaYC3IQuK2D3Q%3D%3D">@chiraag</a>, for any questions that you might have.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7baf5dbf7883" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>