<?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 Arati AK Bhandare on Medium]]></title>
        <description><![CDATA[Stories by Arati AK Bhandare on Medium]]></description>
        <link>https://medium.com/@arati.anand.bhandare?source=rss-2f8bd7c43f76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*430OZZNKGa40KLF6YE_eBA.jpeg</url>
            <title>Stories by Arati AK Bhandare on Medium</title>
            <link>https://medium.com/@arati.anand.bhandare?source=rss-2f8bd7c43f76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 20:51:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arati.anand.bhandare/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[TypeScript in React Props — 1]]></title>
            <link>https://medium.com/@arati.anand.bhandare/typescript-in-react-props-1-6c157cb3c886?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c157cb3c886</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Mon, 25 May 2026 13:09:59 GMT</pubDate>
            <atom:updated>2026-05-25T13:09:59.423Z</atom:updated>
            <content:encoded><![CDATA[<p>In React with TypeScript, you use types/interfaces <em>(shape)</em> to define what props a component accepts.</p><p>This gives:</p><ul><li>Compile-time error checking</li><li>Better readability</li><li>Safer refactoring</li></ul><p>Let’s start with simple example below:</p><pre><br>import ProductCard from &quot;./components/ProductCard.tsx&quot;<br><br>export default function App(){<br>  <br>  return(<br>    &lt;&gt;<br>      &lt;p&gt;Vite + React&lt;/p&gt;<br>      &lt;ProductCard name=&quot;TV&quot; price=55000 /&gt;<br>    &lt;/&gt;<br>  )<br><br>}</pre><pre><br>interface ProductCardProps{<br>    name: string;<br>    price: number;<br>    isSpecial?: boolean;<br>}<br><br>export default function ProductCard({name, price, isSpecial = false} : CardProps){<br>  return(<br>    &lt;div&gt;<br>        &lt;h2&gt;{name} &amp;nbsp;{ isSpecial &amp;&amp; &lt;span&gt;**&lt;/span&gt;}&lt;/h2&gt;<br>        &lt;p&gt;{price}&lt;/p&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><ul><li>Here “ProductCardProps” — is the interface<em> or shape</em> of props to be sent to the “ProductCard” component.</li></ul><p>❌ Wrong usage:</p><pre>&lt;ProductCard name=&quot;TV&quot; price=&quot;55000&quot; /&gt;</pre><p>TypeScript error because price should be a number.</p><p>“isSpecial” has a question mark is optional prop value, false by default.</p><h4>Function Props</h4><p>Very common in React.</p><pre>type CounterProps = {<br>  increment: () =&gt; void;<br>};<br>function Counter({ increment }: CounterProps) {<br>  return &lt;button onClick={increment}&gt;Increment&lt;/button&gt;;<br>}</pre><p>Usage:</p><pre>function App() {<br>  const handleIncrement = () =&gt; {<br>    console.log(&quot;Incremented&quot;);<br>  };<br>  return &lt;Counter increment={handleIncrement} /&gt;;<br>}</pre><h4>Function Props With Parameters</h4><pre>type UserProps = {<br>  onSelect: (id: number) =&gt; void;<br>};<br>function User({ onSelect }: UserProps) {<br>  return (<br>    &lt;button onClick={() =&gt; onSelect(10)}&gt;<br>      Select User<br>    &lt;/button&gt;<br>  );<br>}</pre><h4>Array Props</h4><pre>type ListProps = {<br>  items: string[];<br>};<br><br>function List({ items }: ListProps) {<br>  return (<br>    &lt;ul&gt;<br>      {items.map((item) =&gt; (<br>        &lt;li key={item}&gt;{item}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}</pre><p>Usage:</p><pre>&lt;List items={[&quot;React&quot;, &quot;TypeScript&quot;, &quot;Next.js&quot;]} /&gt;</pre><h4>Object Props</h4><pre>type User = {<br>  id: number;<br>  name: string;<br>};<br><br>type ProfileProps = {<br>  user: User;<br>};<br><br>function Profile({ user }: ProfileProps) {<br>  return &lt;h2&gt;{user.name}&lt;/h2&gt;;<br>}</pre><p>Usage:</p><pre>&lt;Profile user={{ id: 1, name: &quot;Arati&quot; }} /&gt;</pre><h4>Children Props</h4><p>When a component wraps other JSX.</p><pre>type CardProps = {<br>  children: React.ReactNode;<br>};<br>function Card({ children }: CardProps) {<br>  return &lt;div className=&quot;card&quot;&gt;{children}&lt;/div&gt;;<br>}</pre><p>Usage:</p><pre>&lt;Card&gt;<br>  &lt;h1&gt;Hello&lt;/h1&gt;<br>  &lt;p&gt;Welcome&lt;/p&gt;<br>&lt;/Card&gt;</pre><h4>Using interface Instead of type</h4><p>Both work.</p><pre>interface ProductProps {<br>  title: string;<br>  price: number;<br>}<br>function Product({ title, price }: ProductProps) {<br>  return (<br>    &lt;div&gt;<br>      {title} - ₹{price}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Extending Existing HTML Props</h4><p>Useful for reusable buttons/inputs.</p><pre>type CustomButtonProps =<br>  React.ButtonHTMLAttributes&lt;HTMLButtonElement&gt; &amp; {<br>    variant: &quot;primary&quot; | &quot;secondary&quot;;<br>  };<br>function CustomButton({<br>  variant,<br>  children,<br>  ...rest<br>}: CustomButtonProps) {<br>  return (<br>    &lt;button className={variant} {...rest}&gt;<br>      {children}<br>    &lt;/button&gt;<br>  );<br>}</pre><p>Usage:</p><pre>&lt;CustomButton<br>  variant=&quot;primary&quot;<br>  onClick={() =&gt; alert(&quot;Clicked&quot;)}<br>&gt;<br>  Submit<br>&lt;/CustomButton&gt;</pre><p>You automatically get:</p><ul><li>onClick</li><li>disabled</li><li>type</li><li>etc.</li></ul><h4>Union Types</h4><pre>type StatusProps = {<br>  status: &quot;loading&quot; | &quot;success&quot; | &quot;error&quot;;<br>};<br>function Status({ status }: StatusProps) {<br>  return &lt;div&gt;{status}&lt;/div&gt;;<br>}</pre><p>Usage:</p><pre>&lt;Status status=&quot;loading&quot; /&gt;</pre><p>❌ Invalid:</p><pre>&lt;Status status=&quot;pending&quot; /&gt;</pre><h4>Generic Props</h4><p>Very useful for reusable components.</p><pre>type TableProps&lt;T&gt; = {<br>  data: T[];<br>  renderItem: (item: T) =&gt; React.ReactNode;<br>};<br>function Table&lt;T&gt;({<br>  data,<br>  renderItem,<br>}: TableProps&lt;T&gt;) {<br>  return (<br>    &lt;div&gt;<br>      {data.map((item, index) =&gt; (<br>        &lt;div key={index}&gt;{renderItem(item)}&lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Usage:</p><pre>&lt;Table<br>  data={[1, 2, 3]}<br>  renderItem={(num) =&gt; &lt;p&gt;{num}&lt;/p&gt;}<br>/&gt;</pre><p><strong>Destructuring + Inline Types</strong></p><p>Small components sometimes use inline typing.</p><pre>function Welcome({<br>  name,<br>  age,<br>}: {<br>  name: string;<br>  age: number;<br>}) {<br>  return &lt;div&gt;{name} - {age}&lt;/div&gt;;<br>}</pre><h3>Best Practices</h3><p><strong>Prefer </strong><strong>type for component props</strong></p><pre>type Props = {}</pre><p>because unions/intersections are easier.</p><p><strong>Keep reusable types separate</strong></p><pre>type User = {<br>  id: number;<br>  name: string;<br>};</pre><p><strong>Avoid </strong><strong>any</strong></p><pre>props: any</pre><p>This removes TypeScript safety.</p><p><strong>Real-World Example</strong></p><pre>type Todo = {<br>  id: number;<br>  text: string;<br>  completed: boolean;<br>};<br><br>type TodoItemProps = {<br>  todo: Todo;<br>  onToggle: (id: number) =&gt; void;<br>};<br><br>function TodoItem({<br>  todo,<br>  onToggle,<br>}: TodoItemProps) {<br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;checkbox&quot;<br>        checked={todo.completed}<br>        onChange={() =&gt; onToggle(todo.id)}<br>      /&gt;<br>      &lt;span&gt;{todo.text}&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Usage:</p><pre>&lt;TodoItem<br>  todo={{<br>    id: 1,<br>    text: &quot;Learn TS&quot;,<br>    completed: false,<br>  }}<br>  onToggle={(id) =&gt; console.log(id)}<br>/&gt;</pre><h4>Most Common React + TypeScript Prop Types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*CqEV7E8ZjoPbsdmcQWc7NQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c157cb3c886" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React interview questions series #1]]></title>
            <link>https://medium.com/@arati.anand.bhandare/react-interview-questions-series-1-05e6b8375568?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/05e6b8375568</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[concept]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 11:51:47 GMT</pubDate>
            <atom:updated>2026-02-21T11:51:47.957Z</atom:updated>
            <content:encoded><![CDATA[<p>In this series, let’s discuss most frequently asked interview questions for “<strong><em>React developer”</em></strong> role and their answers in most simplified words.</p><p>To begin with let’s start with top 5 questions on<em> </em><strong><em>‘Core Concepts &amp; Fundamentals’</em></strong></p><h3><strong>What is the Virtual DOM and how does React’s reconciliation algorithm work?</strong></h3><ul><li>Virtual DOM is a lightweight copy of real DOM.</li><li>Instead of creating real browser DOM, React creates a virtual representation of UI.</li><li>Compares it with previous version</li><li>Updates only what’s changed</li><li>Suppose your UI is: &lt;h1&gt;Hello&lt;/h1&gt;React creates something like:</li></ul><pre>{<br>  type: &quot;h1&quot;,<br>  props: { children: &quot;Hello&quot; }<br>}</pre><ul><li>That object is part of the <strong>Virtual DOM tree</strong>.</li></ul><p><strong>Advantages of Virtual DOM:</strong></p><ul><li>JS object comparison is fast</li><li>Direct DOM manipulation is slow</li><li>React batches updates</li></ul><p>The process React uses to compare the old Virtual DOM with the new Virtual DOM and determine what to update in the real DOM is called Reconciliation</p><p>React uses a <strong>diffing algorithm</strong> with 2 main assumptions:</p><ul><li>Different element types → Replace completely</li><li>React destroys the old node and creates a new one:<br>&lt;div&gt;Hello&lt;/div&gt;changes to &lt;span&gt;Hello Arati..!&lt;/span&gt;</li><li>Same element type → Update only changed props</li><li>React only updates the class attribute:<br>&lt;h1 className=&quot;red&quot; /&gt;changes to &lt;h1 className=&quot;blue&quot; /&gt;</li></ul><p><strong>Single line summary:</strong></p><blockquote><em>The Virtual DOM is a lightweight JavaScript representation of the real DOM. When state changes, React creates a new Virtual DOM tree and compares it with the previous one using a diffing algorithm called </em><strong>reconciliation</strong><em>. Based on the differences, React updates only the necessary parts of the real DOM, improving performance.</em></blockquote><h3><strong>What is the difference between Controlled and Uncontrolled components?</strong></h3><h4>Controlled component</h4><ul><li>React state controls the form input value</li></ul><pre>import { useState } from &quot;react&quot;;<br><br>function ControlledInput() {<br>  const [name, setName] = useState(&quot;&quot;);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={name}<br>        onChange={(e) =&gt; setName(e.target.value)}<br>      /&gt;<br>      &lt;p&gt;You typed: {name}&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}<br></pre><p><strong>What happens here?</strong></p><ul><li>Input value = React state</li><li>On every keystroke → state updates</li><li>React re-renders</li><li>UI always reflects state</li></ul><blockquote>React is the <strong>single source of truth</strong>.</blockquote><p><strong>Advantages:</strong></p><ul><li>Easy validation</li><li>Real-time form updates</li><li>Predictable behavior</li><li>Easy to reset</li><li>Works well with form libraries</li></ul><p><strong>Use ‘Controlled components’ when?</strong></p><ul><li>You need validation</li><li>Dynamic UI updates</li><li>Complex forms</li><li>Real-time feedback</li><li>While using libraries like Formik / React Hook Form</li></ul><h4>Uncontrolled Component</h4><ul><li>The DOM itself manages the input value</li></ul><pre>import { useRef } from &quot;react&quot;;<br><br>function ControlledInput() {<br>  const inputRef = useRef(null);<br><br>  const handleChange = () =&gt; {<br>    if (inputRef.current) {<br>        inputRef.current.value = &#39;New Updated Value&#39;;<br>    }<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        ref={inputRef}<br>        type=&quot;text&quot;<br>        defaultValue=&quot;Initial value&quot;<br>        onChange={handleChange}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>What happens here?</strong></p><ul><li>React does NOT track input value</li><li>DOM stores it internally</li><li>We access it using ref</li></ul><blockquote>DOM is the <strong>source of truth</strong>.</blockquote><p><strong>Advantages:</strong></p><ul><li>Reduced boilerplate code. Require less code because you don’t need to write state variables and event handlers (onChange) for every input field.</li><li>Better performance: Since React does not re-render the component on every keystroke or input change, uncontrolled components can be more efficient, especially in large forms with many inputs.</li><li>Simplicity for basic use cases: For simple forms where you only need the input values upon submission(e.g., a simple login or newsletter signup), they are straightforward to implement.</li><li>Easier integration with non-React libraries: When integrating with third-party libraries that directly manipulate the DOM, uncontrolled components simplify the process.</li><li>Native browser behavior for specific inputs: Certain input types, like file inputs (&lt;input type=&quot;file&quot;&gt;), are inherently uncontrolled because their value is read-only and managed by the browser.</li></ul><p><strong>Use ‘Uncontrolled components’ when?</strong></p><ul><li>Simple form</li><li>Quick prototype</li><li>Performance critical large forms</li><li>Third-party integrations</li></ul><h3>Explain the React component life-cycle (class vs functional with hooks).</h3><p>In class components, React provides <em>built-in life-cycle methods.</em></p><p>There are 3 phases:</p><h4><strong>Mounting Phase (Component Created)</strong></h4><p>When a component is added to the DOM. Order of execution,</p><pre>constructor()<br>render()<br>componentDidMount()</pre><p><strong>Example:</strong></p><pre>class MyComponent extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    console.log(&quot;Constructor&quot;);<br>  }<br>  componentDidMount() {<br>    console.log(&quot;Mounted&quot;);<br>  }<br>  render() {<br>    console.log(&quot;Render&quot;);<br>    return &lt;div&gt;Hello&lt;/div&gt;;<br>  }<br>}</pre><p><strong><em>componentDidMount()</em></strong> is commonly used for:</p><ul><li>API calls</li><li>Subscriptions</li><li>DOM operations</li></ul><h4><strong>Updating Phase (Re-render)</strong></h4><p>Triggered when:</p><ul><li>props change</li><li>state changes</li><li>forceUpdate()</li></ul><p>Order:</p><pre>render()<br>componentDidUpdate()</pre><p><strong>Example:</strong></p><pre>componentDidUpdate(prevProps, prevState) {<br>  if (prevState.count !== this.state.count) {<br>    console.log(&quot;Count updated&quot;);<br>  }<br>}</pre><h4>Unmounting Phase (Component Removed)</h4><pre>componentWillUnmount()</pre><p>Used for:</p><ul><li>Cleanup</li><li>Remove event listeners</li><li>Clear intervals</li></ul><p>Functional components don’t have lifecycle methods instead they have ‘hooks’.</p><h4>Mounting (like componentDidMount)</h4><pre>useEffect(() =&gt; {<br>  console.log(&quot;Mounted&quot;);<br>}, []);</pre><p>Empty dependency array = run once on mount.</p><h4>Updating (like componentDidUpdate)</h4><pre>useEffect(() =&gt; {<br>  console.log(&quot;Count updated&quot;);<br>}, [count]);</pre><p>Runs whenever count changes.</p><h4>Unmounting (like componentWillUnmount)</h4><pre>useEffect(() =&gt; {<br>  return () =&gt; {<br>    console.log(&quot;Cleanup on unmount&quot;);<br>  };<br>}, []);</pre><p>Return function = cleanup.</p><p>In Class, Lifecycle methods are separated.</p><p>In Functional, <strong><em>useEffect</em></strong> combines:</p><ul><li>mount</li><li>update</li><li>unmount</li></ul><p>React decides when to run effect based on dependency array.</p><p>useEffect is more powerful because you can:</p><ul><li>Separate concerns</li><li>Have multiple effects</li><li>Control dependencies precisely</li><li>In class component, both go inside life-cycle methods and get messy.</li></ul><p>React 18 in Strict Mode development, <strong><em>useEffect</em></strong> runs twice on mount. This is intentional to detect side effects.</p><h4><strong>Class Version</strong></h4><pre>class Counter extends React.Component {<br>  state = { count: 0 };<br>  componentDidMount() {<br>    console.log(&quot;Mounted&quot;);<br>  }<br>  componentDidUpdate() {<br>    console.log(&quot;Updated&quot;);<br>  }<br>  componentWillUnmount() {<br>    console.log(&quot;Unmounted&quot;);<br>  }<br>  render() {<br>    return (<br>      &lt;button onClick={() =&gt; this.setState({ count: this.state.count + 1 })}&gt;<br>        {this.state.count}<br>      &lt;/button&gt;<br>    );<br>  }<br>}</pre><h4>Functional Version</h4><pre>function Counter() {<br>  const [count, setCount] = React.useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&quot;Mounted or Updated&quot;);<br>    return () =&gt; {<br>      console.log(&quot;Cleanup before next effect or unmount&quot;);<br>    };<br>  }, [count]);<br>  <br>return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      {count}<br>    &lt;/button&gt;<br>  );<br>}</pre><blockquote><em>Class components rely on explicit lifecycle methods, while functional components use hooks like useEffect to declaratively manage side effects. Hooks unify mounting, updating, and unmounting logic in a single API, making components more modular and easier to reason about.</em></blockquote><h4>When Would You Still Use Class Components?</h4><p>Almost never in modern apps, because <em>‘Hooks’</em> are:</p><ul><li>Cleaner</li><li>More powerful</li><li>Easier to test</li><li>Less boilerplate</li></ul><h3>What is JSX? How does the browser understand it?</h3><p><strong>JSX (JavaScript XML)</strong> is a syntax extension for JavaScript that lets you write HTML-like code inside JavaScript.</p><pre>const element = &lt;h1&gt;Hello, Arati!&lt;/h1&gt;;</pre><ul><li>It looks like HTML, but it is actually JavaScript.</li><li>Browsers do <strong>NOT</strong> understand JSX directly.</li></ul><p>JSX must be converted into normal JavaScript before the browser can run it.This conversion is done by tools like:</p><ul><li>Babel</li><li>Webpack</li><li>Vite</li><li>Next.js compiler</li></ul><p>This:</p><pre>const element = &lt;h1&gt;Hello&lt;/h1&gt;;</pre><p>Gets converted into:</p><pre>const element = React.createElement(&quot;h1&quot;, null, &quot;Hello&quot;);</pre><p>In newer React versions (17+), it converts into:</p><pre>import { jsx as _jsx } from &quot;react/jsx-runtime&quot;;<br><br>const element = _jsx(&quot;h1&quot;, { children: &quot;Hello&quot; });</pre><p>So JSX → JavaScript → Browser understands it.</p><p>React 17 introduced a new “JSX transform” that improved how Babel handles JSX, but it did not remove the fundamental need for transpilation.</p><p><strong>Step-by-Step Flow:</strong></p><ul><li>You write JSX</li><li>Babel converts JSX → React.createElement</li><li>React creates a Virtual DOM object</li><li>React updates the real DOM efficiently</li></ul><p><strong>Why Do We Use JSX?</strong></p><ul><li>Without JSX: React.createElement(&quot;h1&quot;, null, &quot;Hello&quot;);</li><li>With JSX: &lt;h1&gt;Hello&lt;/h1&gt;</li><li>It is cleaner, easier to read, easier to maintain, feels like writing HTML</li></ul><p><strong>Important JSX Rules:</strong></p><ul><li>Only One Parent Element. <em>(because JSX compiles into a single </em><em>React.createElement() call)</em></li><li>All JavaScript variables, expressions, functions, ternary operators must be placed inside {}</li><li>‘class’ to be written as “className” because class is a reserved JavaScript keyword <em>(used for ES6 classes)</em>.</li><li>We must close all the tags in JSX, because it is closer to XML &amp; not HTML</li><li>JSX uses camelCase for all functions. Event handlers must be strings not functions.</li></ul><pre>❌ Wrong<br><br>&lt;button onclick=&quot;handleClick()&quot;&gt;Click&lt;/button&gt;  <br><br>✅ Correct<br><br>&lt;button onClick={handleClick}&gt;Click&lt;/button&gt;</pre><p><strong>Interview Summary:</strong></p><blockquote><em>JSX is a syntax extension for JavaScript used in React that allows writing HTML-like code inside JavaScript. It gets compiled into </em>React.createElement<em> calls, which browsers can understand as normal JavaScript.</em></blockquote><h4>🤯 <strong>Bonus — Few JSX Gotcha’s:</strong></h4><p><strong>What does this render?</strong></p><pre>const value = 0;<br><br>return &lt;div&gt;{value &amp;&amp; &lt;h1&gt;Hello&lt;/h1&gt;}&lt;/div&gt;;</pre><p>It renders:</p><pre>&lt;div&gt;0&lt;/div&gt;</pre><p>Because:</p><ul><li>0 &amp;&amp; something returns 0</li><li>React renders 0it does NOT treat 0 as false for rendering</li><li>false, null, undefined → React <strong>does NOT</strong> render</li><li>0 → rendered</li></ul><p>We can’t use if directly inside JSX. <em>(It allows </em><strong><em>expressions</em></strong><em>, not statements.</em><em>if is a statement)</em></p><p><strong>What does this render?</strong></p><pre>const arr = [1, 2, 3];<br><br>return &lt;div&gt;{arr}&lt;/div&gt;;</pre><ul><li>It renders, 123 because React <strong>converts</strong> array items into string and renders them.</li></ul><p><strong>What does this render?</strong></p><pre>return &lt;div&gt;{}&lt;/div&gt;;</pre><ul><li>Syntax error, because you cannot leave {} empty in JSX.</li></ul><p><strong>What does this render?</strong></p><pre>const obj = { name: &quot;Arati&quot; };<br><br>return &lt;div&gt;{obj}&lt;/div&gt;;</pre><ul><li>Syntax error, as ‘Objects’ are not valid as a React child.</li><li>React cannot render objects directly. Valid syntax is, <br><strong><em>&lt;div&gt;{obj.name}&lt;/div&gt;</em></strong></li></ul><h3>What are keys in React and why are they important in lists?</h3><ul><li>A <strong>key</strong> is a special string attribute used to uniquely identify elements in a list.</li><li>Keys are crucial for maintaining the identity of components across renders, which allows React’s <strong>reconciliation</strong> algorithm to efficiently determine which items have changed, been added, or removed, and to update the UI correctly.</li></ul><blockquote>The primary role of keys is to provide a stable identity for each list item.</blockquote><p><strong>Advantages:</strong></p><ul><li><strong>Improved Performance</strong>: Keys help React minimize the number of necessary DOM manipulations during updates. Instead of re-rendering the entire list, React can identify precisely which components need to be updated, added, or removed, leading to significant performance enhancements, especially in large, dynamic lists.</li><li><strong>Maintaining Component State</strong>: Keys ensure that the correct component instances and their associated state are preserved across re-renders. Without stable keys, if a list is reordered or filtered, React might reuse a component instance for different data, leading to mismatched UI and unexpected bugs.</li><li><strong>Predictable Behavior</strong>: Proper use of keys helps avoid issues with incorrect state management, animations, and focus management when list items change.</li></ul><pre>const todoItems = todos.map((todo) =&gt;<br>  &lt;li key={todo.id}&gt;<br>    {todo.text}<br>  &lt;/li&gt;<br>);</pre><p><strong>Best Practices for Using Keys:</strong></p><ul><li><strong>Use Unique Identifiers</strong>: Always use a unique and stable identifier from your data as the key, such as a database ID.</li><li><strong>Avoid Using Index as a Key</strong>: Using the array index as a key is highly discouraged for dynamic lists (lists that can be reordered, added to, or removed from) because the index is not a stable identifier and will lead to performance issues and bugs.</li><li><strong>Keep Keys Stable</strong>: Keys should not change over time or between renders. Avoid using dynamic values like Math.random() to generate keys.</li><li><strong>Keys Are Internal to React</strong>: The key prop is used internally by React and is not passed as a prop to your component. If you need the same value within your component, pass it explicitly as a different prop, e.g., <strong><em>&lt;PostComponent key={post.id} id={post.id} /&gt;</em></strong>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05e6b8375568" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Query — Step by step tutorial]]></title>
            <link>https://medium.com/@arati.anand.bhandare/react-query-step-by-step-tutorial-4da1b54ed20e?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/4da1b54ed20e</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 18:29:28 GMT</pubDate>
            <atom:updated>2026-02-18T18:29:28.341Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>React Query</strong>, now known as TanStack Query (or specifically for React applications), is <strong>a powerful open-source library for managing, fetching, caching, and synchronizing asynchronous data (server state) in web applications</strong>. It simplifies the complex tasks associated with managing data from external sources like REST APIs or GraphQL endpoints, significantly reducing boilerplate code and improving performance and user experience.</p><h4><strong>Key Features</strong></h4><ul><li><strong>Simplified Data Fetching:</strong> It provides declarative hooks like for fetching data and for creating, updating, or deleting data on the server. This abstracts away manual state management.</li><li><strong>Automatic Caching:</strong> React Query automatically caches fetched data with a unique query key, which helps speed up the application by preventing unnecessary network requests for the same data.</li><li><strong>Background Synchronization:</strong> It updates stale data in the background (e.g., refetching when the window regains focus, a component mounts, or at specified intervals), ensuring the UI is always in sync with the server’s state.</li><li><strong>Performance Optimization:</strong> Features like request deduplication<em>(Request de-duplication is a technique in distributed systems that ensures a specific operation is executed only once, even if the same request is received multiple times due to network retries, user errors, or system issues. It prevents non-idempotent actions, like duplicate payments, by using unique identifiers to cache responses and return the initial result)</em>, pagination, infinite scrolling support (), and garbage collection for unused cache data help optimize application performance and memory usage.</li><li><strong>Optimistic Updates:</strong> Developers can implement optimistic UI updates, where the UI is updated immediately as if a mutation succeeded, providing instant feedback to the user and then rolling back if the server update fails.</li><li><strong>Devtools:</strong> Built-in React Query Devtools provide valuable insights into query statuses, cache data, and mutations, simplifying debugging.</li></ul><h4>Why Use It?</h4><p>Traditional state management libraries like Redux are designed for synchronous <em>client state</em>. React Query excels specifically at managing the unique challenges of <em>server state</em>, such as asynchronous operations, potential staleness, shared ownership, and remote persistence.</p><h4><strong>Advantages of React Query</strong></h4><ul><li>Remove significant amounts of boilerplate code.</li><li>Make applications feel faster and more responsive to the end-user.</li><li>Improve code maintainability and focus on building features rather than data management logic.</li></ul><blockquote>In short, it provides a robust, opinionated, and highly effective solution for data fetching that is often considered a “missing piece” of the React ecosystem.</blockquote><p>It helps with:</p><ul><li>Data fetching</li><li>Caching</li><li>Background re-fetching</li><li>Loading states</li><li>Error handling</li><li>Pagination</li><li>Optimistic updates</li></ul><h4>Installation Steps</h4><ul><li>In your root directory create 2 folders: client &amp; server</li><li>Inside ‘client’ directory we add simple <em>boilerplate code</em> for React app as below:</li></ul><pre><br>client<br>  public<br>    favicon.ico<br>    index.html<br>    logo.png<br>    manifest.js<br>    robots.txt<br>  src<br>    App.css<br>    App.js<br>    App.test.js<br>    index.css<br>    index.js<br>    logo.svg<br>    reportWebVitals.js<br>    setupTests.js<br>package.json<br>package.lock.json</pre><ul><li>Inside ‘server’ directory we create <em>package.json </em>&amp;<em> index.js</em> files as below</li></ul><pre><br>//index.js - Dummy Express server to fetch &amp; mutate data<br><br>const express = require(&#39;express&#39;)<br>const bodyParser = require(&#39;body-parser&#39;)<br>const cors = require(&#39;cors&#39;)<br>const { v4: uuidv4 } = require(&#39;uuid&#39;)<br><br>const app = express()<br>const PORT = 8000<br><br>const db = new Array()<br><br>// Middlewares<br>app.use(cors())<br>app.use(bodyParser.json())<br><br>// Routes<br>app.get(&#39;/todo&#39;, (req, res) =&gt; {<br>  const items = db<br>  return res.json({ status: &#39;success&#39;, data: items })<br>})<br><br>app.post(&#39;/todo/mark-complete&#39;, (req, res) =&gt; {<br>  const { id } = req.body<br>  const itemIndex = db.findIndex((e) =&gt; e.id === id)<br><br>  if (itemIndex === -1)<br>    return res.json({ status: &#39;error&#39;, error: &#39;Invalid ID&#39; })<br><br>  db[itemIndex].isCompleted = true<br><br>  return res.json({ status: &#39;success&#39; })<br>})<br><br>app.post(&#39;/todo/create&#39;, (req, res) =&gt; {<br>  console.log(`[Server]: Creating new todo!`)<br>  const { title } = req.body<br>  const id = uuidv4()<br>  const item = { id, title, isCompleted: false, createdAt: new Date() }<br>  db.push(item)<br><br>  return res.json({ status: &#39;success&#39;, data: item })<br>})<br><br>app.listen(PORT, () =&gt; console.log(`Server started at PORT:${PORT}`))</pre><pre>{<br>  &quot;//&quot;: [<br>    &quot;This is a top-level comment for human readers.&quot;,<br>    &quot;Below are `package.json` file contents&quot;,<br>  ],<br>  &quot;name&quot;: &quot;react-query-server&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;description&quot;: &quot;&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;concurrently \&quot;node index.js\&quot; \&quot;cd ../client &amp;&amp; npm start\&quot;&quot;<br>  },<br>  &quot;author&quot;: &quot;Miss. Bean&quot;,<br>  &quot;license&quot;: &quot;ISC&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;body-parser&quot;: &quot;^1.20.0&quot;,<br>    &quot;concurrently&quot;: &quot;^7.4.0&quot;,<br>    &quot;cors&quot;: &quot;^2.8.5&quot;,<br>    &quot;express&quot;: &quot;^4.18.1&quot;,<br>    &quot;uuid&quot;: &quot;^9.0.0&quot;<br>  }<br>}</pre><ul><li>Run <em>npm i</em>command in both client &amp; server directory this will create node_modules in both client and server</li><li>Inside ‘server’ folder run command <em>npm start</em></li><li>Your react app should now start working in browser</li><li>In your ‘client’ directory run the below command,</li></ul><pre>npm install @tanstack/react-query</pre><ul><li>Once installation completes, stop &amp; restart server. Remember you need to stop &amp; restart server every time you install a new dependency on client.</li><li>Installation complete, you can now start using React Query in your application.</li></ul><h4>Start building ‘Todo’ app</h4><h4>QueryClientProvider</h4><ul><li>Add below code to <strong>index.js</strong><em> </em>file</li></ul><pre>import React, { useState } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom/client&quot;;<br>import { QueryClient, QueryClientProvider } from &quot;@tanstack/react-query&quot;;<br>import App from &quot;./App&quot;;<br><br>const queryClient = new QueryClient(); // Or use useState for stability in the App component<br><br>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(<br>  &lt;QueryClientProvider client={queryClient}&gt;<br>    &lt;App /&gt;<br>  &lt;/QueryClientProvider&gt;<br>);</pre><ul><li>Include QueryClient &amp; QueryClientProvider from @tanstack/react-query</li><li>Create a ‘<em>client</em>’ which is actually new instance of ‘QueryClient’</li><li>Wrap ‘App’ component inside ‘QueryClientProvider’ component and pass newly created instance ‘queryClient’ as a <em>client</em> prop</li><li>On our Express server we have created 3 routes:<br>1. ‘get’ request to fetching a list of Todo’s<br>2. ‘post’ request to mark Todo completed<br>3. ‘post’ request to create a new Todo task</li></ul><h4>useQuery</h4><ul><li>In App.js now import ‘useQuery’ hook, create a</li><li>useQuery hook — takes 2 arguments dependency list &amp; async callback.</li><li>The 1st parameter, is the query key <em>(dependency list)</em>, which is of string[] data type, used for re-fetching, caching, and sharing data between components.</li><li>The 2nd parameter, is a function typically used to call an API, which returns a promise used to resolve data or throw an error.</li></ul><pre>const { isPending, error, data, isFetching } = useQuery({<br>    queryKey: [&quot;todos&quot;],<br>    queryFn: async () =&gt; {<br>      const response = await fetch(<br>        // Our Express server is running at port 8000 as specified in ../server/index.js<br>        &quot;http://localhost:8000/todo&quot;<br>      );<br>      return await response.json();<br>    },<br>  });</pre><p>We could also write above code in a single line as shown below:</p><pre>const { isPending, error, data, isFetching } = useQuery(<br>    [&quot;todos&quot;],<br>    async () =&gt; await (await fetch(&quot;http://localhost:8000/todo&quot;)).json())<br>  );</pre><p>The useQuery hook returns an object with several useful properties for managing UI states:</p><ul><li><strong>data</strong>: The last successfully resolved data. It is undefined if the query is not in a success state.</li><li><strong>error</strong>: The error object if the query is in an error state.</li><li><strong>status</strong>: A string indicating the query status (&#39;pending&#39;, &#39;error&#39;, or &#39;success&#39;).</li><li><strong>isPending / </strong><strong>isFetching</strong>: Boolean flags to indicate the fetching status. isPending means there is no cached data and the first fetch is running; isFetching is true whenever data is being fetched (including background refetches).</li><li><strong>refetch</strong>: A function to manually trigger a refetch of the query.</li></ul><h4>useMutation</h4><p>Currently there are no todo’s so data is an empty array.</p><ul><li>Create ‘components’ folder in src directory and Form.jsx component to create ‘todo’ tasks</li><li>‘useMutation’ hook is used to create a ‘mutation’ on the server. Here we use it to create ‘<em>new todo task</em>’.</li><li>We pass 2 parameters to ‘useMutation’ hook. First, function to be called for making calls to server &amp; callback functions to handle success &amp; error states.</li></ul><blockquote>Mutation, is a task of creating or updating data on the server.</blockquote><ul><li>Once a todo list is mutated <em>(a new todo is created) </em>we need to fetch todo list again without page refresh.</li><li><strong>queryClient.invalidateQueries</strong> will invalidate old cache and re-run useQuery hook, which will fetch updated ‘todo list’ and display newly Todo task</li></ul><pre><br>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;<br><br>const queryClient = useQueryClient()<br><br>const todoMutation = useMutation(createTodo(text), {<br>    onSuccess: () =&gt; {<br>      console.log(&#39;Success&#39;)<br>      queryClient.invalidateQueries([&#39;todo&#39;])<br>    },<br>    onError: (error) =&gt; {<br>      console.log(&#39;Error&#39;)<br>    },<br>  })</pre><pre>//Function will return a callback function<br>//Which will do a fetch call with &quot;post&quot; method to create a Todo task<br>//We pass form data as a JSON string<br>const createTodo = (text) =&gt; {<br>  return () =&gt;<br>    fetch(&#39;http://localhost:8000/todo/create&#39;, { //Route specified in server/index.js<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      }, <br>      body: JSON.stringify({ title: text }),<br>    })<br>}</pre><h4>Summarize Code</h4><ul><li>Complete <strong>Form.jsx</strong> component code,</li></ul><pre>import React, { useState } from &#39;react&#39;<br>import { useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;<br><br>const createTodo = (text) =&gt; {<br>  return () =&gt;<br>    fetch(&#39;http://localhost:8000/todo/create&#39;, {<br>      method: &#39;POST&#39;,<br>      headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>      },<br>      body: JSON.stringify({ title: text }),<br>    })<br>}<br><br>const Form = () =&gt; {<br>  const [text, setText] = useState(&#39;&#39;)<br>  const queryClient = useQueryClient()<br><br>  const todoMutation = useMutation(createTodo(text), {<br>    onSuccess: () =&gt; {<br>      console.log(&#39;Success&#39;)<br>      //update old cache value &amp; regenerate the Todo list<br>      queryClient.invalidateQueries([&#39;todo&#39;])<br>    },<br>    onError: (error) =&gt; {<br>      console.log(&#39;Error&#39;)<br>    },<br>  })<br><br>  return (<br>    &lt;div&gt;<br><br>      &lt;input<br>        onChange={(e) =&gt; setText(e.target.value)}<br>        value={text}<br>        type=&quot;text&quot;<br>      /&gt;<br>      &lt;button onClick={(e) =&gt; todoMutation.mutate()}&gt;Create&lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default Form</pre><ul><li>Complete <strong>App.js</strong> component</li></ul><pre>import { useQuery } from &#39;@tanstack/react-query&#39;<br>import &#39;./App.css&#39;<br>import Form from &#39;./components/Form&#39;<br><br>function App() {<br>  const { data, status, isFetching } = useQuery(<br>    [&#39;todo&#39;],<br>    async () =&gt; await (await fetch(&#39;http://localhost:8000/todo&#39;)).json()<br>  )<br><br>  console.log(&#39;Data&#39;, data)<br><br>  if (isFetching) {<br>    return &lt;h1&gt;Loading...&lt;/h1&gt;<br>  }<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;Form /&gt;<br>      &lt;p&gt;Status: {status}&lt;/p&gt;<br>      {data &amp;&amp; data.data &amp;&amp; data.data.map((todo) =&gt; &lt;li&gt;{todo.title}&lt;/li&gt;)}<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default App</pre><h4>ReactQueryDevtools</h4><p>The <strong>TanStack Query Devtools</strong> (previously React Query Devtools) provide a visual interface within your browser to inspect and debug the data-fetching layer of applications using TanStack Query. It is a separate package that needs to be installed and integrated into your application.</p><p>To install the package, you need to add the @tanstack/react-query-devtools package to your project using a package manager:</p><pre>npm install @tanstack/react-query-devtools</pre><pre>const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));<br>root.render(<br>  &lt;QueryClientProvider client={queryClient}&gt;<br>    &lt;App /&gt;<br>    &lt;ReactQueryDevtools initialIsOpen /&gt;<br>  &lt;/QueryClientProvider&gt;<br>);</pre><p>The TanStack Query Devtools help you visualize the inner workings of the library and debug issues by providing information on:</p><ul><li><strong>Query and Mutation States</strong>: Monitor the statuses of all queries and mutations (e.g., loading, success, error, idle).</li><li><strong>Cache Contents</strong>: Inspect the cached data for each query, which is useful for checking data freshness and staleness.</li><li><strong>Real-time Monitoring</strong>: Observe how data flows and updates in real time as your application interacts with the server.</li><li><strong>Detailed Information</strong>: View query keys, fetch status, cache time, and the time a query was last fetched.</li><li><strong>Cache Management</strong>: Manually clear the query and mutation caches with dedicated buttons in the UI.</li><li><strong>Network Toggle</strong>: Simulate online/offline modes to test how your application handles network connectivity changes.</li></ul><blockquote>The devtools appear as a floating toggle button in your app’s corner by default, which opens the inspection panel. There is also a standalone browser extension available for Chrome, Firefox, and Edge</blockquote><h4>Bonus</h4><p>CodeSandbox.io working example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fsimple-basic-app-react-query-pvmmtc&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Fsimple-basic-app-react-query-pvmmtc&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fpvmmtc%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/84cf97bd678d65cc29ebbd7669d7003b/href">https://medium.com/media/84cf97bd678d65cc29ebbd7669d7003b/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4da1b54ed20e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Hooks series — useTransition / useDefferedValue]]></title>
            <link>https://medium.com/@arati.anand.bhandare/react-hooks-series-usetransition-usedefferedvalue-58381c725bc7?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/58381c725bc7</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Tue, 10 Feb 2026 13:12:10 GMT</pubDate>
            <atom:updated>2026-02-10T13:12:10.308Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Hooks series — useTransition / useDefferedValue</h3><p>When building interactive user interfaces, performance is a crucial aspect to consider. One way to improve the performance of a React application is by using the useTransition hook. It was introduced in React 18.</p><blockquote>Don’t freeze my UI when something heavy is happening.</blockquote><h4>Advantages:</h4><ul><li><strong>Improved Responsiveness</strong> By deferring non-urgent updates (like rendering large lists, complex charts, or filtering data) to run in the background, it ensures that urgent user interactions (like typing in an input field or button clicks) remain smooth and immediate, preventing the UI from freezing.useTransition gives you control over how React schedules updates. Urgent updates (e.g., controlling an input field) take precedence and can interrupt the non-urgent transition updates. This ensures that the application feels fast and interactive.</li><li><strong>Enhanced User Experience</strong> The hook provides an isPending boolean flag, which becomes true while the low-priority transition is in progress. This allows developers to display a loader, keeping the user informed that an operation is underway without blocking their interaction with the rest of the application.</li><li><strong>Seamless Transitions</strong> It enables smoother visual transitions between different UI states or views, even when the new state requires expensive computations, by allowing the current view to remain responsive until the new one is ready.</li><li><strong>Integration with Concurrent Features</strong> It is a core feature of React’s Concurrent Mode (introduced in React 18), allowing React to leverage its new, efficient, and uninterrupted rendering architecture</li></ul><h4>Why “useTransition”?</h4><p>Imagine:</p><ul><li>User types or clicks something</li><li>React has to do a <strong>heavy state update</strong> (filtering 10,000 items, rendering a big list)</li><li>UI <strong>freezes</strong> for a moment 😬</li></ul><blockquote>Without useTransition, React treats <em>all</em> state updates as equally urgent.</blockquote><p>But in reality:</p><ul><li>Typing / clicking → <strong>urgent</strong></li><li>Rendering filtered results → <strong>not urgent</strong></li></ul><p>That’s where useTransition comes in. useTransition lets you mark some state updates as <strong>low priority (non-urgent)</strong>.</p><p>So React:</p><ul><li>Keeps the <em>UI</em> responsive</li><li>Finishes urgent updates first</li><li>Updates heavy stuff when it gets time</li></ul><pre>const [isPending, startTransition] = useTransition();</pre><ul><li>startTransition(fn) → wrap <strong>non-urgent</strong> updates</li><li>isPending → tells you if transition is still running</li></ul><h4>Without useTransition</h4><pre>import { useState } from &quot;react&quot;;<br><br>export function myfunction () {<br>    let bigList =  [];<br>    <br>    for (i = 0; i&lt;100000; i++){<br>      bigList.push(i)<br>    }<br>    <br>    const [input, setInput] = useState(&quot;&quot;);<br>    const [list, setList] = useState(bigList);<br>    <br>    const handleChange = (e) =&gt; {<br>      setInput(e.target.value);<br>    <br>      // heavy work<br>      const filtered = bigList.filter(item =&gt;<br>        item.includes(e.target.value)<br>      );<br>      setList(filtered);<br>    };<br><br>    return (<br>    &lt;&gt;<br>      &lt;input value={input} onChange={handleChange} /&gt;<br>      &lt;ul&gt;<br>        {list.map(item =&gt; (<br>          &lt;li key={item}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><p>😵 Typing feels laggy if bigList is large.</p><h4>With useTransition</h4><pre>import { useState, useTransition } from &quot;react&quot;;<br><br>export function myfunction () {<br>  let bigList =  [];<br>  <br>  for (i = 0; i&lt;100000; i++){<br>    bigList.push(i)<br>  }<br>  <br>  const [input, setInput] = useState(&quot;&quot;);<br>  const [list, setList] = useState(bigList);<br>  const [isPending, startTransition] = useTransition();<br>  <br>  const handleChange = (e) =&gt; {<br>    <br>    // urgent update<br>    setInput(value);<br><br>    // non-urgent update<br>    startTransition(() =&gt; {<br>      const filtered = bigList.filter(item =&gt;<br>        item.includes(value)<br>      );<br>      setList(filtered);<br>    });<br><br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;input value={input} onChange={handleChange} /&gt;<br><br>      {isPending &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br><br>      &lt;ul&gt;<br>        {list.map(item =&gt; (<br>          &lt;li key={item}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h4>When to use the useTransition hook?</h4><p>Perfect for:</p><ul><li>Filtering large lists</li><li>Search results</li><li>Tabs with heavy content</li><li>Charts / dashboards</li><li>Expensive renders</li></ul><h4>When not to use the useTransition hook?</h4><ul><li>Form inputs themselves</li><li>Small state updates</li><li>API calls (use loading state instead)</li></ul><h4>What “useDeferredValue&quot; does?</h4><ul><li>You update state <strong>normally</strong></li><li>React creates a <strong>delayed version</strong> of that value</li><li>Expensive work uses the <strong>deferred value</strong></li><li>Typing stays fast</li></ul><blockquote>Use the old value for heavy work until React is ready</blockquote><h4>Key differences:</h4><ul><li>Input updates instantly</li><li>Filtering uses <strong>deferred input</strong></li><li>UI stays responsive</li><li>Less code than useTransition</li></ul><h4>Working code “useDefferedValue”</h4><pre>import { useState, useDeferredValue } from &quot;react&quot;;<br><br>// BIG list<br>const bigList = Array.from({ length: 10000 }, (_, i) =&gt; `Item ${i}`);<br><br>export default function App() {<br>  const [query, setQuery] = useState(&quot;&quot;);<br><br>  // React will lag this value slightly if rendering is expensive<br>  const deferredQuery = useDeferredValue(query);<br><br>  // Heavy computation uses deferred value<br>  const results = bigList.filter(item =&gt;<br>    item.toLowerCase().includes(deferredQuery.toLowerCase())<br>  );<br><br>  return (<br>    &lt;div style={{ padding: 20 }}&gt;<br>      &lt;h2&gt;🔍 Search Demo (useDeferredValue)&lt;/h2&gt;<br><br>      &lt;input<br>        value={query}<br>        onChange={(e) =&gt; setQuery(e.target.value)}<br>        placeholder=&quot;Search items...&quot;<br>        style={{<br>          padding: 10,<br>          width: &quot;100%&quot;,<br>          marginBottom: 10,<br>          fontSize: 16<br>        }}<br>      /&gt;<br><br>      {query !== deferredQuery &amp;&amp; &lt;p&gt;Filtering results...&lt;/p&gt;}<br><br>      &lt;ul&gt;<br>        {results.slice(0, 50).map(item =&gt; (<br>          &lt;li key={item}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br><br>      &lt;p&gt;Showing first 50 of {results.length} results&lt;/p&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Key things to notice,</p><ul><li>query → updates immediately (urgent)</li><li>deferredQuery → updates later (non-urgent)</li><li>Filtering uses deferredQuery</li></ul><p>This is <strong>exactly</strong> what we want in search</p><h4>useTransition vs Debounce</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*Qui_9pPoulSpf-t2SOn5Mw.png" /></figure><h4>Best of both the world’s</h4><pre>// debounce API calls<br>const debouncedFetch = debounce(fetchResults, 300);<br><br>const handleChange = (e) =&gt; {<br>  setQuery(e.target.value);<br><br>  startTransition(() =&gt; {<br>    setResults(filterLocalData(e.target.value));<br>  });<br><br>  debouncedFetch(e.target.value);<br>};</pre><ul><li>React handles rendering</li><li>Debounce handles network</li></ul><blockquote>Debounce controls when a function runs, but useTransition controls rendering priority. Debounce is best for API calls, while useTransition keeps the UI responsive during expensive renders.”</blockquote><h3>Interview Questions?</h3><h3>1️⃣ If I use debounce, do I still need useTransition?</h3><p><strong>Answer:</strong><br> Yes, sometimes. Debounce controls <em>when a function runs</em>, but it doesn’t control <em>how React renders</em>. If the UI is slow because of expensive rendering, debounce alone won’t help. useTransition is still useful to mark heavy UI updates as non-urgent so typing stays responsive.</p><h3>2️⃣ Typing feels laggy even though API calls are debounced. What next?</h3><p><strong>Answer:</strong><br> That suggests the bottleneck is rendering, not networking. I’d profile the component and likely wrap the expensive state update or list rendering inside useTransition, or use useDeferredValue for derived data. If needed, I’d also look at memoization or list virtualization.</p><h3>3️⃣ When would you prefer useDeferredValue over useTransition?</h3><p><strong>Answer:</strong><br> I’d use useDeferredValue when the expensive work depends on a single value, like a search query. It’s simpler and lets React decide when to update. I’d prefer useTransition when I need more control over <em>which</em> state updates are low priority or when multiple states are involved.</p><h3>4️⃣ Can useTransition cancel a render?</h3><p><strong>Answer:</strong><br> Yes. If a transition is in progress and a new urgent update comes in — like the user typing again — React can interrupt or discard the ongoing render and restart with the latest state. That’s why the UI stays responsive.</p><h3>5️⃣ Would you wrap an API call inside startTransition?</h3><p><strong>Answer:</strong><br> No. useTransition is for state updates that affect rendering, not side effects. API calls should be handled separately, often with debounce or loading state. I might wrap the state update that <em>renders</em> the API response in a transition, but not the fetch itself.</p><h3>6️⃣ You used useTransition, but the UI is still slow. Why?</h3><p><strong>Answer:</strong><br> Two common reasons:</p><ol><li>The slow part isn’t the state update but something else — like heavy calculations outside React or blocking synchronous code.</li><li>The component tree is too large or not optimized, so even low-priority renders are expensive. In that case I’d look at memoization, splitting components, or virtualization.</li></ol><h3>7️⃣ How does useTransition relate to Concurrent Mode?</h3><p><strong>Answer:</strong><br> useTransition is built on top of React’s concurrent rendering capabilities. In modern React, concurrency is enabled by default in createRoot, so there’s nothing extra to turn on. Using useTransition just tells React how to prioritize updates.</p><h3>8️⃣ Is useTransition a replacement for useMemo?</h3><p><strong>Answer:</strong><br> No. They solve different problems. useMemo prevents unnecessary recalculations, while useTransition controls <em>when</em> updates are rendered. In fact, they’re often complementary—useMemo reduces work, and useTransition ensures that remaining heavy work doesn’t block the UI.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58381c725bc7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redux-toolkit crash course]]></title>
            <link>https://medium.com/@arati.anand.bhandare/redux-toolkit-crash-course-8ddbd698a97d?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ddbd698a97d</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-redux]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 10:28:33 GMT</pubDate>
            <atom:updated>2026-02-05T10:28:33.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQmGvDN_cZw3kW_jvCjPkQ.png" /></figure><h3>Installation Steps</h3><p>Create a react app</p><pre>npm create vite@latest</pre><p>Install <em>redux-toolkit, redux-react</em></p><pre><br>npm install @reduxjs/toolkit<br><br>npm install react-redux<br></pre><h3>Redux Toolkit includes these APIs:</h3><ul><li><a href="https://redux-toolkit.js.org/api/configureStore">configureStore()</a>: wraps createStore to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, adds whatever Redux middleware you supply, includes redux-thunk by default, and enables use of the Redux DevTools Extension.</li><li><a href="https://redux-toolkit.js.org/api/createReducer">createReducer()</a>: that lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the <a href="https://github.com/immerjs/immer">immer library</a> to let you write simpler immutable updates with normal mutative code, like state.todos[3].completed = true.</li><li><a href="https://redux-toolkit.js.org/api/createAction">createAction()</a>: generates an action creator function for the given action type string.</li><li><a href="https://redux-toolkit.js.org/api/createSlice">createSlice()</a>: accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.</li><li><a href="https://redux-toolkit.js.org/api/combineSlices">combineSlices()</a>: combines multiple slices into a single reducer, and allows &quot;lazy loading&quot; of slices after initialisation.</li><li><a href="https://redux-toolkit.js.org/api/createAsyncThunk">createAsyncThunk</a>: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches pending/fulfilled/rejected action types based on that promise</li><li><a href="https://redux-toolkit.js.org/api/createEntityAdapter">createEntityAdapter</a>: generates a set of reusable reducers and selectors to manage normalized data in the store</li><li>The <a href="https://redux-toolkit.js.org/api/createSelector">createSelector utility</a> from the <a href="https://github.com/reduxjs/reselect">Reselect</a> library, re-exported for ease of use.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*fW9GHsEnVooUy1sgnkX3NQ.png" /><figcaption><strong>Data Flow in Redux ToolKit</strong></figcaption></figure><h3>Steps to create “boilerplate” code for Redux-toolkit</h3><h4>configureStore</h4><p>Create ‘store.js’ file. Which can be added directly to ‘src’ folder or we can create an ‘app’ / ‘store’ directory</p><blockquote>React app should have exactly <strong>one</strong> “store” which acts as a single source of truth</blockquote><pre>import { configureStore } from @reduxjs/toolkit<br><br>export const store = configureStore({})</pre><p>Create a folder ‘features’ in ‘src’ folder and create sub-folder ‘todo’ inside it.</p><p>Now inside ‘todoSlice.js’ file</p><pre>import { createSlice, nanoid } from @reduxjs/toolkit </pre><blockquote>nanoid — Function that creates unique id’s for each todo list item.</blockquote><p>Create ‘initialState’ object</p><pre>const initialState = {<br>  todoList: [{ Id: 1, title: &quot;Learn Redux toolkit&quot;, completed: false }],<br>}</pre><p>Now we create a ‘slice’ and also add create a ‘reducers’ object within slice.</p><pre>export const todoListSlice = createSlice({<br>  name: &quot;todoList&quot;, //this is the name that shows in Redux toolkit chrome extension<br>  initialState,<br>  reducers: {<br>      addTodo: (state, action) =&gt; {},<br>      deleteTodo: (state, action) =&gt; {},<br>      updateTodo: (state, action) =&gt; {},<br>      completeTodo: (state, action) =&gt; {}<br>  }<br><br>})</pre><h4>Reducers</h4><p>‘Reducers’ contain property &amp; functions. Here ‘addTodo’ is a property &amp; it has a linked function which is either directly defined right next to property or is attached via function reference which is defined outside of ‘slice’ variable.</p><p>Reducer functions will have access to state <em>(this parameter gives value of the state in current situation)</em> &amp; action<em>(this parameter contains ‘values’ that function needs for execution for example, ‘Id’ value is needed to identify which particular ‘todo’ is to be deleted on click on delete button)</em></p><pre>addTodo: (state, action) =&gt; {<br>  const todo: { Id: nanoid(), title: action.payload, completed: false }<br>  state.todoList.push(todo)<br>}</pre><blockquote>we can get ‘unique Id’ for each todo by using ‘nanoid’ function. <br>value of todo ‘title’ can be fetched from action.payload.title (since name is same we drop word tittle)<br>We finally update state as per current situation by pushing newly created ‘todo’ to our ‘todoList’ array which we had created in initialState.</blockquote><p>Similarly we filter out the todoList array where the ‘Id’ matches with the ‘Id’ value specified in payload to delete a todo task.</p><pre>deleteTodo : (state, action) =&gt; {<br>  state.todoList = state.todoList.filter(todo =&gt; todo.id !== action.payload)<br>}</pre><pre>updateTodo: (state, action) =&gt; {<br>      state.todoList = state.todoList.map((todo) =&gt;<br>        todo.id === action.payload.id<br>          ? { ...todo, tittle: action.payload.tittle }<br>          : todo<br>      );<br> }</pre><pre>completeTodo: (state, action) =&gt; {<br>      state.todoList = state.todoList.map((todo) =&gt;<br>        todo.id === action.payload.id<br>          ? { ...todo, completed: action.payload.completed }<br>          : todo<br>      );<br>}</pre><p>To update, todo task details in todoList, we can pass the updated todo ‘tittle’ &amp; todo ID to “updateTodo” reducer and make changes to tittle of Todo task where Id matches. We can also toggle “completion” status of task by passing the completed flag value &amp; task Id to “completeTodo” reducer.</p><p>Now we must export all ‘reducer’ functions from actions and use them individually in components as per need.</p><pre>export const { addTodo, deleteTodo, updateTodo, completeTodo } = todoSlice.actions</pre><p>Store should be aware of reducer functions. So we need to register reducers into the store by exporting all reducer functions.</p><pre>export default todoSlice.reducer</pre><p>To summarize entire code of todoSlice.js</p><pre>import { createSlice, nanoid } from @reduxjs/toolkit<br><br>const initialState = {<br>  todoList: [{ Id: 1, title: &quot;Learn Redux toolkit&quot;, completed: false }],<br>}<br><br>const todoSlice = createSlice({<br>                  name: &quot;todo&quot;,<br>                  initialState,<br>                  reducers: {<br>                              addTodo: (state, action)=&gt;{<br>                                const todo: {<br>                                      Id: nanoid();<br>                                      title: &quot;Learn Redux Toolkit&quot;,<br>                                      completed: false<br>                                }<br>                                state.todoList.push(todo)<br>                              },<br>                              deleteTodo: (state, action)=&gt;{<br>                                 state.todoList = state.todoList.filter( todo =&gt; todo.Id !== action.payload )<br>                              },<br>                              updateTodo: (state, action) =&gt; {<br>                                state.todoList = state.todoList.map((todo) =&gt;<br>                                  todo.id === action.payload.id<br>                                    ? { ...todo, tittle: action.payload.tittle }<br>                                    : todo<br>                                );<br>                              },<br>                              completeTodo: (state, action) =&gt; {<br>                                state.todoList = state.todoList.map((todo) =&gt;<br>                                  todo.id === action.payload.id<br>                                    ? { ...todo, completed: action.payload.completed }<br>                                    : todo<br>                                );<br>                              },<br><br>})<br><br>export const { addTodo, deleteTodo, updateTodo, completeTodo } = todoSlice.actions;<br><br>export default todoSlice.reducer<br></pre><p>Now import all the created reducers in ‘store.js’ file as pass them as key-value pair to ‘store’ variable.</p><pre>import { configureStore } from @reduxjs/toolkit<br><br>import todoReducer from &#39;../features/todo/todoSlice&#39;;<br><br>export const store = configureStore({<br>    reducer: todoReducer<br>})</pre><p>Once our ‘store’ setup is completed, we need to create components to add, display, update, delete &amp; complete ‘todos’</p><p>Create ‘components’ directory in ‘src’ folder <br>Add ‘AddTodo.jsx’ component with below code.</p><pre>import React, {useState} from &#39;react&#39;<br>import {useDispatch} from &#39;react-redux&#39;<br>import {addTodo} from &#39;../features/todo/todoSlice&#39; <br><br>function AddTodo() {<br><br>    const [input, setInput] = useState(&#39;&#39;)<br>    const dispatch = useDispatch()<br><br>    const addTodoHandler = (e) =&gt; {<br>        e.preventDefault()<br>        dispatch(addTodo(input))<br>        setInput(&#39;&#39;)<br>    }<br><br>  return (<br>    &lt;form onSubmit={addTodoHandler} className=&quot;space-x-3 mt-12&quot;&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        className=&quot;bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out&quot;<br>        placeholder=&quot;Enter a Todo...&quot;<br>        value={input}<br>        onChange={(e) =&gt; setInput(e.target.value)}<br>      /&gt;<br>      &lt;button<br>        type=&quot;submit&quot;<br>        className=&quot;text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded text-lg&quot;<br>      &gt;<br>        Add Todo<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  )<br>}<br><br>export default AddTodo</pre><p>It allows users to dispatch (add) todo’s to the list. Here we use useDispatch hook from react-redux.</p><pre>import { useDispatch } from &#39;react-redux&#39;<br><br>//We import reducer addTodo from todoSlice file<br>import {addTodo} from &#39;../features/todo/todoSlice&#39;<br><br>//We create a dispatch variable<br>const dispatch = useDispatch()</pre><blockquote>On form submit, ‘dispatch’ uses a ‘reducer’ to makes changes to ‘store’.</blockquote><pre>const addTodoHandler = (e) =&gt; {<br><br>  //prevents default form submit action<br>  e.preventDefault()<br><br>  //Here &quot;addTodo&quot; is a reducer used by &quot;dispatch&quot; to add todo data in &quot;store&quot;<br>  //We pass input as &quot;action.payload&quot; value to reducer<br>  dispatch(addTodo(input))<br><br>  //Make input blank again for new entry - It&#39;s best practise to cleanup<br>  setInput(&#39;&#39;)<br>}</pre><p>Now once the list of ‘todo’ is created, we need to display the list as well to do so we create “Todos.jsx” component</p><pre>import React from &#39;react&#39;<br><br>//useSelector - required to get todoList from store<br>//useDispatch - required to dispatch delete, update or complete actions<br>import { useSelector, useDispatch } from &#39;react-redux&#39;<br><br>//Reducer to remove particular todo from todoList<br>import { removeTodo } from &#39;../features/todo/todoSlice&#39;<br><br>function Todos() {<br><br>    //useSelector method gives us access to &quot;state&quot; in a callback<br>    //todoList is the array of &quot;todo&quot; objects which we declared in initialState in todoSlice.js file<br>    const todos = useSelector(state =&gt; state.todoList)<br>    const dispatch = useDispatch()<br><br>  return (<br>    &lt;&gt;<br>    &lt;div&gt;Todos&lt;/div&gt;<br>    &lt;ul className=&quot;list-none&quot;&gt;<br>        {todos.map((todo) =&gt; (<br>          &lt;li<br>            className=&quot;mt-4 flex justify-between items-center bg-zinc-800 px-4 py-2 rounded&quot;<br>            key={todo.id}<br>          &gt;<br>            &lt;div className=&#39;text-white&#39;&gt;{todo.text}&lt;/div&gt;<br>            &lt;button<br>             onClick={() =&gt; dispatch(removeTodo(todo.id))}<br>              className=&quot;text-white bg-red-500 border-0 py-1 px-4 focus:outline-none hover:bg-red-600 rounded text-md&quot;<br>            &gt;<br>              &lt;svg<br>                xmlns=&quot;http://www.w3.org/2000/svg&quot;<br>                fill=&quot;none&quot;<br>                viewBox=&quot;0 0 24 24&quot;<br>                strokeWidth={1.5}<br>                stroke=&quot;currentColor&quot;<br>                className=&quot;w-6 h-6&quot;<br>              &gt;<br>                &lt;path<br>                  strokeLinecap=&quot;round&quot;<br>                  strokeLinejoin=&quot;round&quot;<br>                  d=&quot;M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0&quot;<br>                /&gt;<br>              &lt;/svg&gt;<br>            &lt;/button&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default Todos</pre><blockquote>We need to use a “callback” function for calling “dispatch”. <br>As in react we only need to pass a reference to a function that is to be executed onClick else it will be executed immediately &amp; not wait for click.</blockquote><p>We include all the above created components (AddTodo, Todos) in App.jsx</p><pre><br>import &#39;./App.css&#39;<br>import AddTodo from &#39;./components/AddTodo&#39;<br>import Todos from &#39;./components/Todos&#39;<br><br>function App() {<br>  <br>  return (<br>    &lt;&gt;<br>      &lt;h1&gt;Learn about redux toolkit&lt;/h1&gt;<br>      &lt;AddTodo /&gt;<br>      &lt;Todos /&gt;<br>    &lt;/&gt;<br>  )<br>}<br><br>export default App</pre><p>Finally, inside “main.jsx” component we wrap App component inside Provider and pass “store&quot; as value something similar to what we do in context API.</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import App from &#39;./App.jsx&#39;<br>import &#39;./index.css&#39;<br>import { Provider } from &#39;react-redux&#39;<br>import {store} from &#39;./app/store&#39;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;,<br>)</pre><p>CodeSandBox.io demo of above “Redux-toolkit” application:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkjmr3x%3Ffile%3D%252Fsrc%252Fcomponents%252FTodos.jsx%253A40%252C8&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fp%2Fsandbox%2Fkjmr3x%3Ffile%3D%252Fsrc%252Fcomponents%252FTodos.jsx%253A40%252C8&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkjmr3x%2Fscreenshot.png&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/067e388c089a2f72ae866316a43ec8ea/href">https://medium.com/media/067e388c089a2f72ae866316a43ec8ea/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ddbd698a97d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Loop in JavaScript]]></title>
            <link>https://medium.com/@arati.anand.bhandare/event-loop-in-javascript-4aaacd8cd902?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/4aaacd8cd902</guid>
            <category><![CDATA[events]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[callback]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Mon, 26 Jan 2026 11:17:30 GMT</pubDate>
            <atom:updated>2026-01-26T11:17:30.267Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>The Event Loop is a mechanism that allows JavaScript, which is single-threaded, to handle non-blocking asynchronous tasks by executing them when the call stack is empty, using task queues like the microtask and macrotask queues.</em></blockquote><p>👉 In simple words:<br> <strong>It decides <em>when</em> and <em>what</em> code should run next.</strong></p><h3>Why Do We Need the Event Loop?</h3><p>JavaScript can execute <strong>only one thing at a time</strong>.</p><p>Without the Event Loop:</p><ul><li>setTimeout</li><li>API calls</li><li>Promises would <strong>block</strong> the whole app ❌</li></ul><p>Event Loop makes JS <strong>fast and responsive</strong> ✅</p><h3>Key Parts Involved</h3><h3>1. Call Stack</h3><p>📚 Executes synchronous code.</p><pre>console.log(&quot;A&quot;);</pre><p>Runs immediately.</p><h3>2. Web APIs (Browser / Node APIs)</h3><p>🌐 Handles async tasks like:</p><ul><li>setTimeout</li><li>fetch</li><li>DOM events</li></ul><pre>setTimeout(() =&gt; console.log(&quot;B&quot;), 1000);</pre><p>Timer runs here, <strong>not in JS engine</strong>.</p><h3>3. Callback Queue (Macro-task Queue)</h3><p>📦 Holds:</p><ul><li>setTimeout</li><li>setInterval</li><li>DOM events</li></ul><h3>4. Microtask Queue</h3><p>⚡ Higher priority queue:</p><ul><li>Promise.then</li><li>catch</li><li>finally</li><li>queueMicrotask</li></ul><h3>5. Event Loop</h3><p>🔁 Constantly checks:</p><ol><li>Is Call Stack empty?</li><li>Run <strong>all microtasks</strong></li><li>Run <strong>one macrotask</strong></li><li>Repeat</li></ol><h3>Priority Order</h3><pre>1. Call Stack (sync code)<br>2. Microtasks (Promises)<br>3. Macrotasks (setTimeout, events)</pre><h3>Some examples</h3><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Promise&quot;);<br>});<br><br>console.log(&quot;End&quot;);</pre><p>Output: Start-&gt;End-&gt;Promise-&gt;Timeout</p><h3>Why?</h3><ol><li>Start → sync → Call Stack</li><li>End → sync → Call Stack</li><li>Promise.then → Microtask Queue</li><li>setTimeout → Macrotask Queue</li><li>Event Loop runs microtasks first</li></ol><pre>Call Stack empty<br>   ↓<br>Run all Microtasks<br>   ↓<br>Run 1 Macrotask<br>   ↓<br>Repeat 🔁</pre><h3>Summary</h3><blockquote><em>The Event Loop allows JavaScript to handle asynchronous tasks by continuously checking the call stack and executing microtasks first, then macrotasks, ensuring non-blocking behavior.</em></blockquote><h3>Tricky Interview Questions</h3><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;B&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;C&quot;);<br>});<br><br>console.log(&quot;D&quot;);</pre><p><strong>Output:</strong> ADCB</p><p><strong>Explanation:</strong><br>Sync first → A, D<br>Promise → <strong>microtask<br></strong>setTimeout → <strong>macrotask</strong></p><pre>console.log(&quot;start&quot;);<br><br>Promise.resolve().then(() =&gt; console.log(&quot;p1&quot;));<br>Promise.resolve().then(() =&gt; console.log(&quot;p2&quot;));<br><br>console.log(&quot;end&quot;);</pre><p><strong>Output: </strong>start end p1 p2<br><strong>Explanation:<br></strong>All microtasks run <strong>before</strong> any macrotask<br>Executed in <strong>order of creation</strong></p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;timeout&quot;);<br>  <br>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;promise&quot;);<br>  });<br>}, 0);</pre><p><strong>Output: </strong>timeout promise<br><strong>Explanation: </strong><br>setTimeout callback runs first<br>Promise inside it → microtask → runs immediately after</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;promise&quot;);<br>  <br>  setTimeout(() =&gt; {<br>    console.log(&quot;timeout&quot;);<br>  }, 0);<br>});</pre><p><strong>Output: </strong>promise timeout<br><strong>Explanation:<br></strong>Promise runs first<br>setTimeout goes to macrotask queue later</p><pre>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;p1&quot;);<br>  <br>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;p2&quot;);<br>  });<br>});</pre><p><strong>Output:</strong> p1 p2<br><strong>Explanation:<br></strong>Microtasks added during microtask execution<br>Event loop drains entire microtask queue</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;timeout&quot;);<br>}, 0);<br><br>setImmediate(() =&gt; {<br>  console.log(&quot;immediate&quot;);<br>});</pre><p><strong>Output: </strong>Not guaranteed<br><strong>Explanation:<br></strong><strong>setImmediate()</strong> runs in the <strong>check phase</strong> (after the poll phase).<br><strong>setTimeout(..., 0)</strong> runs in the <strong>timers phase</strong> (before the poll phase in the next iteration.</p><pre>async function test() {<br>  console.log(&quot;A&quot;);<br>  await Promise.resolve();<br>  console.log(&quot;B&quot;);<br>}<br><br>console.log(&quot;C&quot;);<br>test();<br>console.log(&quot;D&quot;);</pre><p><strong>Output:</strong> CADB<br><strong>Explanation:<br></strong>await pauses function<br>Rest runs as <strong>microtask</strong></p><pre>async function foo() {<br>  console.log(&quot;1&quot;);<br>  setTimeout(() =&gt; console.log(&quot;2&quot;), 0);<br>  await Promise.resolve();<br>  console.log(&quot;3&quot;);<br>}<br><br>foo();<br>console.log(&quot;4&quot;);</pre><p><strong>Output:</strong> 4132<br><strong>Explanation:</strong><br>await → microtask<br>setTimeout → macrotask</p><pre>function loop() {<br>  Promise.resolve().then(loop);<br>}<br><br>loop();<br>setTimeout(() =&gt; {<br>  console.log(&quot;timeout&quot;);<br>}, 0);</pre><p><strong>Output:</strong> timeout never runs<br><strong>Explanation:</strong><br>Infinite microtasks<br>Event loop never reaches macrotask queue</p><pre>console.log(&quot;start&quot;);<br><br>setTimeout(() =&gt; console.log(&quot;timeout&quot;), 0);<br><br>Promise.resolve()<br>  .then(() =&gt; console.log(&quot;promise1&quot;))<br>  .then(() =&gt; console.log(&quot;promise2&quot;));<br><br>console.log(&quot;end&quot;);</pre><p><strong>Output:</strong> start end promise1 promise2 timeout<br><strong>Explanation:</strong><br>Promise chaining stays in microtask queue<br>Macrotask waits</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4aaacd8cd902" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Engine]]></title>
            <link>https://medium.com/@arati.anand.bhandare/javascript-engine-a7742e70cc65?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7742e70cc65</guid>
            <category><![CDATA[v8]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 13:34:25 GMT</pubDate>
            <atom:updated>2026-01-25T13:34:25.964Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>JavaScript Engine</strong> is a program that <strong>reads, interprets, and executes JavaScript code</strong>.</p><p>Popular examples:</p><ul><li><strong>V8</strong> → Chrome, Node.js</li><li><strong>SpiderMonkey</strong> → Firefox</li><li><strong>JavaScriptCore</strong> → Safari</li></ul><h3>1. Parser</h3><p>📖 <em>Reads your JavaScript code</em></p><p><strong>What it does:</strong></p><ul><li>Checks syntax (grammar)</li><li>Converts code into an internal structure called <strong>AST (Abstract Syntax Tree)</strong></li></ul><p><strong>Example:</strong></p><pre>let x = 10;</pre><p>Parser turns this into a tree-like structure the engine can understand.</p><p>👉 If there’s a syntax error, execution stops here.</p><h3>2. Interpreter</h3><p>🎤 <em>Starts executing the code</em></p><p><strong>What it does:</strong></p><ul><li>Converts AST into <strong>bytecode</strong></li><li>Executes code line by line</li></ul><p><strong>Why needed?</strong></p><ul><li>Gives <strong>fast startup</strong></li><li>Doesn’t wait for full optimization</li></ul><p>👉 Earlier engines only had interpreters → slower performance.</p><h3>3. Compiler (JIT — Just In Time Compiler)</h3><p>⚡ <em>Makes code faster</em></p><p><strong>What it does:</strong></p><ul><li>Finds frequently used code (hot code)</li><li>Converts it into <strong>optimized machine code</strong></li><li>Skips slow interpretation</li></ul><p><strong>Example:</strong></p><pre>function add(a, b) {<br>  return a + b;<br>}</pre><p>If add() is called thousands of times ➜ compiler optimizes it.</p><p>👉 Modern engines like <strong>V8</strong> use <strong>JIT compilation</strong>.</p><h3>4. Optimizer</h3><p>🚀 <em>Improves performance further</em></p><p><strong>What it does:</strong></p><ul><li>Removes unnecessary checks</li><li>Inline functions</li><li>Makes assumptions for speed</li></ul><p>If assumptions break → engine <strong>deoptimizes</strong> and reverts safely.</p><h3>5. Memory Heap</h3><p>🧠 <em>Stores objects &amp; variables</em></p><p><strong>What goes here?</strong></p><ul><li>Objects</li><li>Functions</li><li>Arrays</li></ul><p><strong>Example:</strong></p><pre>let user = { name: &quot;Arati&quot; };</pre><p>Stored in the <strong>heap</strong>.</p><h3>6. Call Stack</h3><p>📚 <em>Keeps track of function calls</em></p><p><strong>What it does:</strong></p><ul><li>Executes functions in order</li><li>Uses <strong>LIFO</strong> (Last In, First Out)</li></ul><p><strong>Example:</strong></p><pre>function a() {<br>  b();<br>}<br>function b() {<br>  console.log(&quot;Hello&quot;);<br>}<br>a();</pre><p>Call Stack:</p><pre>a()<br>  → b()</pre><h3>7. Garbage Collector</h3><p>🧹 <em>Cleans unused memory</em></p><p><strong>What it does:</strong></p><ul><li>Removes objects no longer referenced</li><li>Prevents memory leaks</li></ul><p><strong>Example:</strong></p><pre>let obj = { data: 123 };<br>obj = null; // eligible for garbage collection</pre><p>Summary:<br><em>A JavaScript engine consists of a </em><strong><em>parser</em></strong><em>, </em><strong><em>interpreter</em></strong><em>, </em><strong><em>JIT compiler</em></strong><em>, </em><strong><em>optimizer</em></strong><em>, </em><strong><em>memory heap</em></strong><em>, </em><strong><em>call stack</em></strong><em>, and </em><strong><em>garbage collector</em></strong><em> that together parse, optimize, execute code, and manage memory efficiently.</em></p><pre>JS Code<br> ↓<br>Parser → AST<br> ↓<br>Interpreter → Bytecode<br> ↓<br>Compiler/Optimizer → Machine Code<br> ↓<br>Execution (Call Stack + Heap)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7742e70cc65" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reconciliation in React js]]></title>
            <link>https://medium.com/@arati.anand.bhandare/reconciliation-in-react-js-e793b6832e5d?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/e793b6832e5d</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Sun, 25 Jan 2026 10:14:40 GMT</pubDate>
            <atom:updated>2026-01-25T10:14:40.593Z</atom:updated>
            <content:encoded><![CDATA[<p>How does React’s reconciliation algorithm (Fiber) improve rendering performance?</p><p>Updating the <strong>real DOM</strong> is slow.</p><p>So React:</p><p>Keeps a <strong>virtual DOM</strong> (a lightweight copy in memory)</p><p>Figures out <strong>what actually changed</strong></p><p>Updates <strong>only those parts</strong> in the real DOM</p><p>That “figuring out what changed and how to update it” is called <strong>reconciliation</strong>.</p><h3>Before Fiber (old React)</h3><p>Earlier React did this:</p><p>When state changes → React re-renders the whole component tree</p><p>It compares old Virtual DOM vs new Virtual DOM</p><p><strong>One big, blocking task</strong></p><p>Browser can’t respond until React finishes</p><p>👉 Problem:<br> If the UI is large, the app felt <strong>laggy or frozen</strong>.</p><p>React began using the <strong>Fiber</strong> architecture with the release of <strong>React 16</strong> in <strong>September 2017</strong>.</p><p>Think of Fiber as:</p><blockquote><em>“Breaking big rendering work into small chunks and doing them smartly”</em></blockquote><p>Instead of doing everything at once, React:</p><p>Splits work into <strong>small units</strong></p><p>Can <strong>pause</strong>, <strong>resume</strong>, or <strong>skip</strong> work</p><p>Prioritizes <strong>important updates first</strong></p><h3>Real-life analogy 🧠</h3><h3>Without Fiber:</h3><p>You’re cleaning the entire house in one go.</p><p>Phone rings ❌ → ignore<br>Doorbell rings ❌ → ignore<br>Finish cleaning first</p><h3>With Fiber:</h3><p>You clean room by room.</p><p>Phone rings ✅ → answer<br>Urgent guest arrives ✅ → pause cleaning<br>Resume later</p><p>👉 Fiber makes React <strong>uninterruptible</strong></p><h3>Example scenario:</h3><p>You have:</p><p>A <strong>text input, and </strong>A <strong>huge list (1000 items)</strong></p><pre>function App() {<br>  const [text, setText] = React.useState(&quot;&quot;);<br>  return (<br>    &lt;&gt;<br>      &lt;input<br>        value={text}<br>        onChange={(e) =&gt; setText(e.target.value)}<br>      /&gt;<br>      &lt;BigList /&gt;<br>    &lt;/&gt;<br>  );<br>}</pre><h3>WITHOUT Fiber?</h3><p>You type a letter<br>React re-renders App<br>React also re-renders BigList<br>Browser freezes slightly ⏳<br>Typing feels laggy</p><h3>WITH Fiber?</h3><p>You type a letter<br>React marks input update as <strong>high priority<br></strong>React updates input immediately ✅<br>Delays BigList update ⏸️<br>UI stays smooth ✨</p><p>👉 <strong>User interactions never feel slow</strong></p><h3>Key Improvements Fiber Brings 🚀</h3><ol><li>Work can be split — Rendering work is divided into <strong>small pieces</strong> instead of one big task.</li><li>Work can be paused &amp; resumed — React can stop rendering if, User clicks/types/scrolls. Then continue later.</li></ol><p>Not all updates are equal.</p><p>Typing, clicking🔥 High<br>Animations🔶 Medium<br>Background data🔵 Low</p><p>Fiber lets React <strong>choose what matters now</strong>.</p><p>Fiber enables:<br>useTransition<br>Concurrent rendering<br>Suspense<br>Streaming UI</p><p>Please note: Fiber is an internal change in React.<br> Developers benefit automatically, but advanced APIs like useTransition allow better control</p><p>Code example</p><pre>import { useState, useTransition } from &#39;react&#39;;<br><br>function FilterableList({ items }) {<br>  const [inputValue, setInputValue] = useState(&#39;&#39;);<br>  const [filteredItems, setFilteredItems] = useState(items);<br>  // Initialize the useTransition hook<br>  const [isPending, startTransition] = useTransition();<br><br>  const handleChange = (e) =&gt; {<br>    const value = e.target.value;<br>    // Urgent update: keep the input field responsive<br>    setInputValue(value);<br><br>    // Non-urgent update: wrap the potentially slow filtering logic in a transition<br>    startTransition(() =&gt; {<br>      const newFilteredItems = items.filter(item =&gt; <br>        item.name.includes(value)<br>      );<br>      setFilteredItems(newFilteredItems);<br>    });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input type=&quot;text&quot; value={inputValue} onChange={handleChange} /&gt;<br>      {/* Show a loading indicator while the transition is pending */}<br>      {isPending ? (<br>        &lt;div&gt;Loading...&lt;/div&gt;<br>      ) : (<br>        &lt;ul&gt;<br>          {filteredItems.map(item =&gt; (<br>            &lt;li key={item.id}&gt;{item.name}&lt;/li&gt;<br>          ))}<br>        &lt;/ul&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e793b6832e5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 “simple” ways to handle API response — React]]></title>
            <link>https://medium.com/@arati.anand.bhandare/5-simple-ways-to-handle-api-response-react-90d356483a77?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/90d356483a77</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Mon, 10 Apr 2023 15:36:44 GMT</pubDate>
            <atom:updated>2023-04-10T15:36:44.312Z</atom:updated>
            <content:encoded><![CDATA[<h3>5 “simple” ways to handle API response — React</h3><p>Working with backend services such as a <em>REST API</em> is one of the most common tasks for a “frontend developer”.</p><p>No matter what React app you’re building, at some point, you’ll need to make a request to a database server or an <em>endpoint</em> and grab some data to display to the user.</p><p>In this article, I’ll guide you through <strong><em>5 simple ways</em></strong> you can use to call an API and fetch/display its response in your React app.</p><h3>Fetch</h3><ul><li>The “<a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch"><strong><em>fetch</em></strong></a>” function from JavaScript’s built-in methods allows you to send HTTP requests to a server and receive responses.</li><li>It is used to fetch data asynchronously from a server and update the state of a React component based on that data.</li></ul><p>Here’s an code example of how to use the fetch method in React to retrieve data from an API endpoint</p><pre>import React from &#39;react&#39;<br><br>function GetTodoList(){<br>  <br>  /**<br>   * We are using &quot;useState&quot; React Hook <br>   * We initially set value of api response variable as an empty array<br>  **/<br>  <br>  const [todoData, setTodoData] = useState([])<br>  <br>  /**<br>   * We use &quot;useEffect&quot; React Hook we make an API call<br>   * We pass empty array variable as 2nd parameter to useEffect hook<br>   * We now set value of &quot;todoData&quot; variable, <br>   * Using setTodoData,inside fetch json response<br>  **/<br><br>  useEffect(() =&gt; {<br>    fetch(&#39;https://jsonplaceholder.typicode.com/todos&#39;)<br>      .then(response =&gt; response.json())<br>      .then(jsonResponse =&gt; setTodoData(jsonResponse))<br>  }, [])<br><br>  /**<br>   * We return list of <br>   * todo task ID, <br>   * todo title, <br>   * tasks completion status as boolean<br>  **/<br><br>  return(<br>    &lt;div&gt;<br>      {<br>        todoData.map((data) =&gt; {<br>            &lt;div key={data.id}&gt;<br>              &lt;h2&gt;{data.title}&lt;/h2&gt;<br>              &lt;p&gt;{data.completed}&lt;/p&gt;<br>            &lt;/div&gt;<br>        })<br>      }<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Axios</h3><ul><li>Axios is a JS library that allows developers to make HTTP requests from the browser or <a href="https://nodejs.org/en"><strong><em>node.js</em></strong></a></li><li>It provides a simple and easy-to-use API that can be used in a variety of ways, including making GET and POST requests, handling authentication, and more.</li><li>In React it is commonly used to <em>retrieve, update or delete</em> data from the server. It is often used in together with React’s useEffect hook to fetch data from a server when a component is mounted or updated.</li></ul><pre>import React from &#39;react&#39;<br>import axios from &#39;axios&#39;<br><br>function GetTodoList(){<br>  <br>  /**<br>   * We are using &quot;useState&quot; React Hook <br>   * We initially set value of api response variable as an empty array<br>  **/<br>  <br>  const [todoData, setTodoData] = useState([])<br>  <br>  /**<br>   * We use &quot;useEffect&quot; React Hook we make an API call<br>   * We pass empty array variable as 2nd parameter to useEffect hook<br>   * We now set value of &quot;todoData&quot; variable, <br>   * Using setTodoData,inside fetch json response<br>   * Axios library returns a data object that has already been parsed to JSON <br>  **/<br><br>  useEffect(() =&gt; {<br>    axios.get(&#39;https://jsonplaceholder.typicode.com/todos&#39;)<br>      .then(response =&gt; setTodoData(response.data))<br>      .catch(error =&gt; console.log(error))<br>  }, [])<br><br>  /**<br>   * We return list of <br>   * todo task ID, <br>   * todo title, <br>   * tasks completion status as boolean<br>  **/<br><br>  return(<br>    &lt;div&gt;<br>      {<br>        todoData.map((data) =&gt; {<br>            &lt;div key={data.id}&gt;<br>              &lt;h2&gt;{data.title}&lt;/h2&gt;<br>              &lt;p&gt;{data.completed}&lt;/p&gt;<br>            &lt;/div&gt;<br>        })<br>      }<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>Async / Await</h3><p>Async/await is a syntax feature in JavaScript that simplifies asynchronous programming.</p><p>It allows developers to write asynchronous code that looks and behaves like synchronous code.</p><p>In React, async/await can be used with functions that return Promises, such as the built-in fetch function used to make HTTP requests.</p><p>By using async/await, developers can write code that waits for the result of an asynchronous operation to complete before proceeding with the next line of code.</p><h4>Benefits of using async / await</h4><ul><li>Increase the performance and <strong>responsiveness</strong> of your app, if you have long-running operations that do not require to block the execution. In that case, you can perform other work while waiting for the result from the long running task.</li><li>Organise your code in a neat and readable way significantly better than boilerplate code of the traditional thread creation and handling with async / await , you write less code and your code will be more maintainable than using the previous asynchronous programming methods such as using plain tasks.</li><li>async / await is the newer replacement to BackgroundWorker, which has been used on windows forms desktop applications.</li></ul><pre>import React from &#39;react&#39;<br>import axios from &#39;axios&#39;<br><br>function GetTodoList(){<br>  <br>  /**<br>   * We are using &quot;useState&quot; React Hook <br>   * We initially set value of api response variable as an empty array<br>  **/<br>  <br>  const [todoData, setTodoData] = useState([])<br><br>  /**<br>   * We use &quot;useEffect&quot; React Hook we make an API call<br>   * We pass empty array variable as 2nd parameter to useEffect hook<br>   * We now set value of &quot;todoData&quot; variable, <br>   * Using setTodoData,inside fetch json response<br>   * Axios library returns a data object that has already been parsed to JSON <br>  **/<br><br>   useEffect(()=&gt;{<br>      async function asyncTodoData(){<br>        try{<br>          const response = axios.get(&#39;https://jsonplaceholder.typicode.com/todos&#39;)<br>          setTodoData(response.data)<br>        }<br>        catch(e){<br>            console.log(e)<br>        }<br>      }<br>      asyncTodoData();     <br>     } <br>  }, [])<br><br>  /**<br>   * We return list of <br>   * todo task ID, <br>   * todo title, <br>   * tasks completion status as boolean<br>  **/<br><br>  return(<br>    &lt;div&gt;<br>      {<br>        todoData.map((data) =&gt; {<br>            &lt;div key={data.id}&gt;<br>              &lt;h2&gt;{data.title}&lt;/h2&gt;<br>              &lt;p&gt;{data.completed}&lt;/p&gt;<br>            &lt;/div&gt;<br>        })<br>      }<br>    &lt;/div&gt;<br>  )<br>}</pre><h3>React Query Library</h3><p><a href="https://tanstack.com/query/v3/docs/react/overview"><strong><em>React Query</em></strong></a> is a popular library in React that provides a simple and efficient way to manage and cache remote data in a React application.</p><p>It allows developers to easily fetch, cache, and update data from remote sources such as REST APIs, GraphQL endpoints, and more.</p><h4>Benefits of using React Query Library</h4><ol><li>Caching</li><li>Identifies and updates stale data in the background</li><li>Memory management and garbage collection</li><li>Deduping multiple requests for the same data, saves bandwidth and improves the user’s experience.</li><li>Performance optimisations pagination, lazy loading, etc., to improve your application’s performance.</li></ol><blockquote>more on React Query Library in separate article soon…</blockquote><pre>import React from &#39;react&#39;;<br>import {useQuery} from &#39;react-query&#39;;<br><br>const GetTodoList = async () =&gt; {<br>  const response = await fetch(&#39;https://jsonplaceholder.typicode.com/todos&#39;)<br>  return response.json();<br>}<br><br>const todoList = () =&gt; {<br>  const { todoData, loading, error } = useQuery(&#39;todos&#39;, GetTodoList);<br>  if(loading){<br>    return &lt;div&gt;Loading...&lt;/div&gt;;<br>  }<br>  if(error){<br>    return &lt;div&gt;Error fetching data&lt;/div&gt;;<br>  }<br>  /**<br>   * We return list of <br>   * todo task ID, <br>   * todo title, <br>   * tasks completion status as boolean<br>  **/<br><br>  return(<br>    &lt;div&gt;<br>      {<br>        todoData.map((data) =&gt; {<br>            &lt;div key={data.id}&gt;<br>              &lt;h2&gt;{data.title}&lt;/h2&gt;<br>              &lt;p&gt;{data.completed}&lt;/p&gt;<br>            &lt;/div&gt;<br>        })<br>      }<br>    &lt;/div&gt;<br>  )<br>}<br><br>export default todoList;</pre><h3>Custom Hook</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wuUY6dECa6gGq1qt63Etww.png" /><figcaption><strong>Create your own custom React hook, to fetch API response</strong></figcaption></figure><p>Custom hook is a JS function that uses built-in React hooks to encapsulate reusable logic.</p><p>Custom hooks allow you to extract common logic from your components and reuse it across your application. They can use any of the existing hooks, such as useState, useEffect, or useContext, to create new hooks with a specific behaviour.</p><blockquote>It follows the naming convention of starting with word “use”, which is general requisite for all hooks in React.</blockquote><pre>const useFetchData = (method, url, body) =&gt; {<br><br>  /**<br>  * isLoading: Checks if the API is still fetching or has fetched the data.<br>  * apiData: On fetching successfully, data is stored in apiData variable.<br>  * serverError: Error in fetching the data it will be stored in this variable.<br>  **/<br><br>  const [isDataLoading, setIsDataLoading] = useState(false)<br>  const [apiResponse, setApiResponse] = useState(null)<br>  const [responseError, setResponseError] = useState(null)<br><br>  useEffect(()=&gt;{<br>    //Set loading to true, to display loader<br>    setIsDataLoading(true);<br>    const fetchAPIData = async () =&gt; {<br>        try{<br>            const response = await axios({<br>              method: method,<br>              url: url,<br>              data: body<br>            });<br>            const data = await response?.data;<br>            setApiResponse(data)<br>            setIsDataLoading(false)<br>        }<br>        catch(error){<br>           setResponseError(error)<br>           setIsDataLoading(false)<br>        }<br>    };<br>    fetchAPIData()<br>    <br>  }, [url,method,body])<br>  return {isDataLoading, apiResponse, responseError}<br>}</pre><p>Usage of ‘<strong><em>useFetchData</em></strong>’ hook can be done as follows:</p><pre>import { StrictMode } from &quot;react&quot;;<br>import ReactDOM from &quot;react-dom&quot;;<br>import useFetch from &quot;./useFetchData&quot;;<br><br>const App = () =&gt; {<br>  const { isDataLoading, responseError, apiResponse } = useFetch(<br>    &quot;https://jsonplaceholder.typicode.com/todos&quot;<br>  );<br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;API data&lt;/h2&gt;<br>      {isDataLoading &amp;&amp; &lt;div&gt;Loading.....&lt;/div&gt;}<br>      {!isDataLoading &amp;&amp; responseError ? (<br>        &lt;div&gt;Error in fetching data ...&lt;/div&gt;<br>      ) : (<br>            // We return list of todo task ID, title &amp; completion status            <br>            &lt;div&gt;<br>              {<br>                apiResponse.map((data) =&gt; {<br>                    &lt;div key={data.id}&gt;<br>                      &lt;h2&gt;{data.title}&lt;/h2&gt;<br>                      &lt;p&gt;{data.completed}&lt;/p&gt;<br>                    &lt;/div&gt;<br>                })<br>              }<br>          &lt;/div&gt;)<br>      }<br>    &lt;/div&gt;<br>  );<br>};<br><br>const rootElement = document.getElementById(&quot;root&quot;);<br><br>ReactDOM.render(<br>  &lt;StrictMode&gt;<br>    &lt;App /&gt;<br>  &lt;/StrictMode&gt;,<br>  rootElement<br>);</pre><p>You can also integrate redux into your hook, to add your API response to your global state.</p><p>fetchApiData, fetchApiSuccess, and fetchApiFailure are thunks which call the specific redux actions along with storing the data into the redux global state.</p><pre>const useFetchData = (url) =&gt; {<br>  const [isDataLoading, setIsDataLoading] = useState(false)<br>  const [apiResponse, setApiResponse] = useState(null)<br>  const [responseError, setResponseError] = useState(null)<br>  const dispatch = useDispatch();<br><br>  useEffect(() =&gt; {<br>    setIsDataLoading(true);<br>    <br>    const fetchData = async () =&gt; {<br>          try {<br>            dispatch(fetchApiData());            <br>            const resp = await axios.get(url);<br>            const data = await resp?.data;<br>            dispatch(fetchApiSuccess(data));<br>            setApiData(data);<br>            setIsDataLoading(false);<br>          } <br>          catch (error) {<br>            setResponseError(error);<br>            dispatch(fetchApiFailure());<br>            setIsDataLoading(false);<br>          }<br>        };    <br>        fetchData();<br>      }, [dispatch, url]);<br>    <br>      return { isDataLoading, apiResponse, responseError };<br>   };<br>}</pre><blockquote>P.S: Our useFetch is currently performing only GET request. But we can have our useFetch to perform all types of request such as POST, PUT etc by generalising our Axios call</blockquote><h3>Conclusion</h3><p>In this blog, we have covered different approaches to fetch &amp; process API responses. In our upcoming blog, we will try to learn about React Hooks, Building Custom Hooks, Code Splitting, Context API, Redux/Reducers, Lazy Loading, GraphQL and much more! 🤓👍🏻</p><p>#HappyCoding</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90d356483a77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Craft an “AI” Empowered Code]]></title>
            <link>https://medium.com/@arati.anand.bhandare/how-to-setup-an-ai-powered-code-editor-c899ab8a3312?source=rss-2f8bd7c43f76------2</link>
            <guid isPermaLink="false">https://medium.com/p/c899ab8a3312</guid>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Arati AK Bhandare]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 11:58:39 GMT</pubDate>
            <atom:updated>2023-03-26T06:48:24.130Z</atom:updated>
            <content:encoded><![CDATA[<p>As our technology advances, we find more ways to interface with it and collaborate with it.</p><p>In particular, having the ability to use <strong><em>Artificial Intelligence, </em></strong>AI for short in programming has gained popularity among coders in recent years.</p><p>AI is a powerful tool. It can be a great coding partner that helps you write the simple and easy code of a program.</p><p>It can also speed up your development cycle, help you code faster and skilfully, and even make your team more productive. 🤓👍🏻</p><p>Any efficiently working piece of software requires several rounds of testing and enhancement before it is released.</p><p>Crafting this fabulous piece of software can be tedious, costly, and time-consuming. It can be frustrating for humans. Programmers certainly need help, and then like superhero enters “AI”.</p><p>Artificial Intelligence can be,</p><ul><li><strong><em>Program Assistant </em></strong>— AI allows programmers to determine errors on the fly code as they are written. Commit Assistant, checks for incorrect codes using a software library of usual coding errors encountered in previous projects. It thus prevents programmers from making the same mistakes again, consequently saving them time and effort correcting errors later on in the process.</li><li>AI and machine learning (ML) algorithms can configure computers to analyse programs for errors and fix them accordingly before they go to market.</li><li>Software development projects hardly ever meet timelines and budgets that are set for them before they even begin.But, with AI’s help, using historical data from previous projects it enable programmers to provide management more accurate schedules and funding requirements, while considering all possible scenarios and potential challenges.</li></ul><p>To begin with our “AI” journey let’s start small and take a look at some of the really cool AI powered tools that you can add to your regular code editor in just few clicks which will make your life as a programmer pretty easy!</p><blockquote>Let’s spice up your “Code” with some cool AI powered IDE extensions and write code like never before!</blockquote><h3>Mintlify — Doc Writer</h3><p>Documentation is an essential requirement for quality and process control. We need to have some level of cohesion when writing documents, so that we don’t look sloppy or uninformed.</p><p>Documentation also encourages knowledge sharing, which in turn empowers a team to understand how processes work and what finished projects typically should look like and how it is expected to work. 🤩</p><p>But unfortunately passionate programmers who love to write code many times suck at writing documents (<em>as most of them are lazy fellows </em>😂<em>)</em>.</p><p>It takes a hell lot of time to create nice and easy to understand “document ” for the code that we write isn’t it? 😰</p><p>But now with the help of an AI powered tool called <strong><em>“Mintlify”</em></strong>, which can write <strong><em>documents automatically.</em></strong> 💡</p><p>We can have a systematic knowledge base and also save on time for create it. This extension is indeed a blessing for lazy programmers like me 🙈</p><ul><li>Mintlify<strong><em> </em></strong>analyses the code and extracts information about variables, functions, and classes, and then using this information to generate a human-readable documentation. ✅</li><li>It supports all popular programming languages like: Python, JavaScript, TypeScript, C++, PHP, Java, C#, Ruby etc</li><li>This extension is available for free download <a href="https://marketplace.visualstudio.com/items?itemName=mintlify.document"><strong>here</strong></a></li></ul><h3>Readable — Comments Generator</h3><ul><li>Readable is a VS Code extension that generates comments using GPT-3. It’s fast, reliable, consistent, and saves you loads of time. ℹ️</li></ul><blockquote>GPT-3 : Generative Pre-trained Transformer 3 is an autoregressive language model released in 2020 that uses deep learning to produce human-like text. Given an initial text as prompt, it will produce text that continues the prompt</blockquote><ul><li>Using this extension you can instantly generate detailed comments for your code powered by AI.✌🏻</li><li>It supports all popular programming languages like: Javascript, TypeScript, Python, JSX/TSX, C, C#, C++, Java, and PHP.</li><li>To generate DocString press ctrl’ or cmd’ while your cursor is in any function OR if the function is highlighted.</li><li>To generate an inline comment type “//” for C-Style languages. ❗️</li><li>For Python style comments type, “#”. #️⃣</li><li>After hitting space, press the tab to generate an inline comment. *️⃣</li><li>Optionally, type a few words after // to generate a more specific comment.</li><li>This extension is available for free download <a href="https://marketplace.visualstudio.com/items?itemName=pcsoftware.readable"><strong>here</strong></a><strong> 🆕 🆓 🆒</strong></li></ul><h3>Denigma — Code Tutor</h3><ul><li>Denigma is an awesome AI tool that helps you understand code by explaining it in general conversational English. ✌🏻</li><li>It is basically AI powered tool that reads and explains complex code naturally, like a human it explains code in conversational English. 🔤</li><li>It is powered by machine learning.👀</li><li>You can use it to generate an explanation of a certain block of code or of a whole file in just 2 clicks.👩🏻‍🏫</li><li>It claims to generate results really fast(under 2 seconds) with 75% to 95% accuracy in explanation depending upon the code. 💯</li><li>It has been installed more than 22,800 times in VS Code as of February 2023.🆘</li><li>This extension is available for free download <a href="https://marketplace.visualstudio.com/items?itemName=denigmaapp.denigma"><strong>here</strong></a></li></ul><h3>Dependency Analytics — Code Quality Analyzer</h3><ul><li>Developed by <strong><em>Red Hat</em></strong>, it is a free tool that provides, insights about your application dependencies: Security &amp; License compatibility 🆗</li><li>It also provides, AI based guidance to choose appropriate dependencies for your application. 🆙</li><li>It uses the open source vulnerability database, <a href="https://snyk.io/product/vulnerability-database/"><strong><em>Snyk Intel Vulnerability DB</em></strong></a> to generate a “Dependency Analytics Report” that provides application dependency insights, with listed features including:<br>- Flags a security vulnerability(CVE) and suggests a remedial version 🧰<br>- Shows Github popularity metrics along with latest version 📈<br>- Suggests a project level license. 🆑<br>- Checks for conflicts between dependency licences 👊🏻<br>- AI based guidance for additional, alternative dependencies 🆚</li><li>Currently it only supports Maven, Python, Go and npm (Node ecosystem) projects. Support for other languages is currently work in progress.🔜</li></ul><blockquote>P.S: If you want to make your applications PCI compliant <em>(PCI Compliance means that your systems are secure, and your customers can trust you with their sensitive payment card information)</em> this tool can come in handy and be very useful to detect and resolve vulnerabilities in your code.🚧</blockquote><ul><li>This extension is available for free download <a href="https://marketplace.visualstudio.com/items?itemName=redhat.fabric8-analytics"><strong>here</strong></a></li></ul><h3>GitHub Copilot and more…</h3><ul><li>It provides code-completion functionality.</li><li>It can convert comments to code, create unit tests, create SQL queries and more.</li><li>It works with all popular languages like: Java, PHP, Python, JavaScript, Ruby, Go, C# and C++.</li><li>However, it’s not free, though it comes with a free trial.</li><li>It became generally available in June 2022 at $10 per month for individuals. <em>Full pricing details for individual and business plans are </em><a href="https://github.com/features/copilot/#pricing"><strong><em>here</em></strong></a><em>.</em></li><li>Some of the Tech <a href="https://visualstudiomagazine.com/articles/2023/02/15/copilot-upgrade.aspx"><strong><em>improvements announced last month</em></strong></a> include:<br>- A more powerful client-side AI model with algorithms that improve the quality of code suggestions by 44 percent<br>- Simple self-serve purchasing, where businesses can sign up for Copilot themselves and immediately assign seats — even if they don’t use the GitHub platform<br>- AI-based security vulnerability filtering to target common issues.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFi3AJZZregI&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFi3AJZZregI&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FFi3AJZZregI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f421f63e11b733bea6c2eda57524eb/href">https://medium.com/media/c1f421f63e11b733bea6c2eda57524eb/href</a></iframe><p>If you are someone like me, I am sure you would be looking for free alternatives for GitHub Copilot, 🤓👍🏻💡</p><p>There indeed is a, <a href="https://marketplace.visualstudio.com/items?itemName=GitHub.copilot-labs"><strong><em>GitHub Copilot Labs</em></strong></a> VSCode extension with more advanced features.</p><h4><strong><em>Custom Brushe</em>s </strong>🎨</h4><p>This allows user to select a text, you can give a custom <em>(created by you)</em> command to Copilot, and watch it modify the selected code as per your command in just a second.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fe3v6j11iYOw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3De3v6j11iYOw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fe3v6j11iYOw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a1efbef0168e649ae7eaccd4df8001c/href">https://medium.com/media/6a1efbef0168e649ae7eaccd4df8001c/href</a></iframe><h4><strong><em>Custom Keybindings </em></strong>🔑</h4><p>All VSCode features can be assigned to a custom keybinding.</p><ul><li>We can assign the <em>Custom Brushes</em> feature above to a “keybinding”, and have access to it without needing to click so multiple times.</li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FGLj4fQ0s7JM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DGLj4fQ0s7JM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FGLj4fQ0s7JM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/3995a4f0249c6986d354b6aa7e6a4445/href">https://medium.com/media/3995a4f0249c6986d354b6aa7e6a4445/href</a></iframe><h4>Your “Quick Help” — Buddy❓</h4><p>You can ask questions by simply writing a comment that starts with q:, and starting the next line with a:.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FFHuAekIvQJc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DFHuAekIvQJc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FFHuAekIvQJc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/93fe673fe499439cdc061f5191f38923/href">https://medium.com/media/93fe673fe499439cdc061f5191f38923/href</a></iframe><p>You can also have a complete conversation with Copilot by following up the first answer with another command, like “show me docs”, and it will provide URLs that justify the answer it gave you! 😃</p><h3>Bonus:Interesting things you can do with VS code 💡</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptKgOKog8skO1oyzMd9QxQ.jpeg" /><figcaption>You can search for <strong>Keyboard Shortcuts</strong> in your command palette</figcaption></figure><p>Whenever you find yourself clicking around too much to get something done, search the Keyboard Shortcuts list, and you’ll likely find something you can bind. 😃</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xyc1Yb58HklUZTsEGZ2Hsg.jpeg" /><figcaption>You can also search for a custom <strong><em>Copilot Brush</em></strong><em>, that you just created</em></figcaption></figure><p>Simply click on the <strong>Use Brush on selected text</strong> command and assign it your favourite keybinding.</p><p>You can also use the JSON view (Open Keyboard Shortcuts (JSON) in the command palette) and just copy and paste settings you want, for example to open the copilot brushes prompt as shown above:</p><pre>[<br>  {<br>    &quot;key&quot;: &quot;shift+cmd+a&quot;,<br>    &quot;command&quot;: &quot;copilot-labs.use-brush-picker&quot;,<br>    &quot;when&quot;: &quot;editorTextFocus&quot;<br>  }<br>]</pre><p><strong>Build a Code tree on the fly!</strong></p><p>In VS code, If you name a file src/myfile.ts, and the src folder does not exist, VSCode will create it for you! This works with:</p><ul><li>new files</li><li>when you rename a file</li><li>nested directories</li></ul><h3>Conclusion</h3><p>The age of AI has just begun and in the future, there will be more and more developer tools and extensions that are powered by Artificial Intelligence to enhance developer productivity.</p><p>As for today, this is the end of the article.</p><p>I hope you got to know some new VS Code AI extensions to play with when you are coding next time.</p><p>Let me know if you are aware of any other VS Code AI extension that could be a great addition to the above list.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c899ab8a3312" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>