<?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 Abhinav Singh on Medium]]></title>
        <description><![CDATA[Stories by Abhinav Singh on Medium]]></description>
        <link>https://medium.com/@abhisingh622000?source=rss-c9c73c4b566d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*fA3q5Spcp0BDUmFm</url>
            <title>Stories by Abhinav Singh on Medium</title>
            <link>https://medium.com/@abhisingh622000?source=rss-c9c73c4b566d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 11:38:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhisingh622000/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[A Deep Dive into Recoil: From Basics to Advanced]]></title>
            <link>https://medium.com/@abhisingh622000/a-deep-dive-into-recoil-from-basics-to-advanced-e3cb61e9cb2a?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3cb61e9cb2a</guid>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 15:19:30 GMT</pubDate>
            <atom:updated>2025-02-04T15:19:30.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lFHZCO-sF6veJZ0rweXO_A.jpeg" /></figure><p>State management can quickly become one of the trickiest parts of building robust React applications. If you’re like me, you’ve probably wrestled with Redux or Context API in the past. Enter <strong>Recoil</strong> — a modern state management library for React that aims to simplify state sharing and derivation without the overhead of boilerplate code. This post will walk through Recoil from the ground up, exploring everything from the fundamentals to more advanced patterns. Let’s get started!</p><h3>What Is Recoil?</h3><p>Recoil introduces a fresh approach to managing state in React applications by using <strong>atoms</strong> and <strong>selectors</strong>:</p><ul><li><strong>Atoms</strong> are the smallest units of state. Think of them as the “source of truth” that any component can subscribe to.</li><li><strong>Selectors</strong> allow you to derive and transform state. They can compute new values based on atoms (or even other selectors) and even handle asynchronous operations.</li></ul><p>This model makes your state much more modular and easier to reason about.</p><h3>Setting Up Recoil</h3><p>Before diving into atoms and selectors, you need to add Recoil to your project. Simply install it using npm or yarn:</p><pre>npm install recoil<br># or<br>yarn add recoil</pre><p>Next, wrap your application in a &lt;RecoilRoot&gt;. This ensures that Recoil’s state is accessible throughout your component tree.</p><pre>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom&#39;;<br>import { RecoilRoot } from &#39;recoil&#39;;<br>import App from &#39;./App&#39;;<br><br>ReactDOM.render(<br>  &lt;RecoilRoot&gt;<br>    &lt;App /&gt;<br>  &lt;/RecoilRoot&gt;,<br>  document.getElementById(&#39;root&#39;)<br>);</pre><h3>Your First Atom</h3><p>Let’s kick things off by creating a simple atom. In Recoil, atoms are created with a unique key and a default value. For example, here’s how you might create a counter state:</p><pre>// atoms.js<br>import { atom } from &#39;recoil&#39;;<br><br>export const counterState = atom({<br>  key: &#39;counterState&#39;, // Unique ID<br>  default: 0,          // Initial value<br>});</pre><p>This atom now serves as a single source of truth for the counter value.</p><h3>Using Atoms in Components</h3><p>To access the state stored in an atom, Recoil provides hooks that are similar to React’s useState. The useRecoilState hook is particularly handy:</p><pre>// Counter.js<br>import React from &#39;react&#39;;<br>import { useRecoilState } from &#39;recoil&#39;;<br>import { counterState } from &#39;./atoms&#39;;<br><br>function Counter() {<br>  const [count, setCount] = useRecoilState(counterState);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Count: {count}&lt;/h2&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCount(count - 1)}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p>Every time the counter changes, any component using counterState will automatically re-render, keeping your UI in sync with your data.</p><h3>Deriving State with Selectors</h3><p>One of the most powerful features of Recoil is the ability to derive new state from existing atoms. For example, you might want to display double the current counter value. This is where selectors come into play:</p><pre>// selectors.js<br>import { selector } from &#39;recoil&#39;;<br>import { counterState } from &#39;./atoms&#39;;<br><br>export const doubledCountState = selector({<br>  key: &#39;doubledCountState&#39;,<br>  get: ({ get }) =&gt; {<br>    const count = get(counterState);<br>    return count * 2;<br>  },<br>});</pre><p>Then, in your component:</p><pre>// DoubledCount.js<br>import React from &#39;react&#39;;<br>import { useRecoilValue } from &#39;recoil&#39;;<br>import { doubledCountState } from &#39;./selectors&#39;;<br><br>function DoubledCount() {<br>  const doubledCount = useRecoilValue(doubledCountState);<br>  <br>  return &lt;h3&gt;Doubled Count: {doubledCount}&lt;/h3&gt;;<br>}<br><br>export default DoubledCount;</pre><p>The beauty of selectors is that they only recalculate when their dependencies change, which keeps your app performant.</p><h3>Advanced: Handling Asynchronous Data</h3><p>Recoil selectors aren’t limited to synchronous operations — they can also manage asynchronous data fetching. This makes them a great tool for integrating API calls directly into your state management.</p><pre>// asyncSelectors.js<br>import { selector } from &#39;recoil&#39;;<br><br>export const userDataSelector = selector({<br>  key: &#39;userDataSelector&#39;,<br>  get: async () =&gt; {<br>    const response = await fetch(&#39;https://jsonplaceholder.typicode.com/users/1&#39;);<br>    if (!response.ok) {<br>      throw new Error(&#39;Error fetching user data&#39;);<br>    }<br>    return response.json();<br>  },<br>});</pre><p>You can then use this asynchronous selector in a component with the useRecoilValueLoadable hook, which gives you access to the loading, error, and value states:</p><pre>// UserProfile.js<br>import React from &#39;react&#39;;<br>import { useRecoilValueLoadable } from &#39;recoil&#39;;<br>import { userDataSelector } from &#39;./asyncSelectors&#39;;<br><br>function UserProfile() {<br>  const userLoadable = useRecoilValueLoadable(userDataSelector);<br><br>  switch (userLoadable.state) {<br>    case &#39;loading&#39;:<br>      return &lt;p&gt;Loading user data...&lt;/p&gt;;<br>    case &#39;hasError&#39;:<br>      return &lt;p&gt;Error loading user data.&lt;/p&gt;;<br>    case &#39;hasValue&#39;:<br>      return (<br>        &lt;div&gt;<br>          &lt;h2&gt;{userLoadable.contents.name}&lt;/h2&gt;<br>          &lt;p&gt;{userLoadable.contents.email}&lt;/p&gt;<br>        &lt;/div&gt;<br>      );<br>    default:<br>      return null;<br>  }<br>}<br><br>export default UserProfile;</pre><p>This pattern makes it straightforward to incorporate asynchronous data into your UI without resorting to additional state variables or complex logic.</p><h3>Final Thoughts</h3><p>Recoil brings a fresh perspective to state management in React by reducing boilerplate and providing an intuitive API for both shared and derived state. Whether you’re just starting out or looking to integrate more advanced features like asynchronous selectors, Recoil offers a flexible and efficient solution.</p><p>I hope this guide gives you a clear understanding of how to leverage Recoil — from basic atoms and selectors to advanced asynchronous patterns. If you’ve already used Recoil in your projects or have any tips to share, I’d love to hear about your experiences in the comments below!</p><p>Happy coding, and enjoy the journey toward cleaner, more maintainable state management in your React apps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3cb61e9cb2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Class-Based Components in React]]></title>
            <link>https://medium.com/@abhisingh622000/understanding-class-based-components-in-react-81f606700f17?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/81f606700f17</guid>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Thu, 30 Jan 2025 22:32:03 GMT</pubDate>
            <atom:updated>2025-01-30T22:32:03.981Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*FLH_rN41EscJJFLB5YB9jw.png" /></figure><p>When React was first introduced, class-based components were the primary way to build UI components. While functional components with hooks have become standard, understanding class-based components is still essential — especially if you’re working on older codebases or preparing for job interviews.</p><p>In this blog, we’ll explore what class-based components are, how they work, and when you might still need them.</p><h3>What Are Class-Based Components?</h3><p>A <strong>class-based component</strong> is a JavaScript class that extends React.Component. It has a render() method that returns JSX and can manage <strong>state</strong> and <strong>lifecycle methods</strong>.</p><h4>Basic Example</h4><pre>import React, { Component } from &#39;react&#39;;<br><br>class Greeting extends Component {<br>  render() {<br>    return &lt;h1&gt;Hello, {this.props.name}!&lt;/h1&gt;;<br>  }<br>}<br><br>export default Greeting;</pre><ul><li>The Greeting class extendsReact.Component, making it a React component.</li><li>The render() method returns JSX that will be displayed on the screen.</li><li>We use this.props.name to access the name prop passed to the component.</li></ul><h3>Managing State in Class Components</h3><p>Unlike functional components that use the useState hook, class components store state in this.state and update it using this.setState().</p><h4>Example: Counter Component</h4><pre>import React, { Component } from &#39;react&#39;;<br><br>class Counter extends Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = { count: 0 };<br>  }<br><br>  increment = () =&gt; {<br>    this.setState({ count: this.state.count + 1 });<br>  };<br><br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;p&gt;Count: {this.state.count}&lt;/p&gt;<br>        &lt;button onClick={this.increment}&gt;Increment&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default Counter;</pre><ul><li>The state is <strong>initialized in the constructor</strong> using this.state.</li><li>The increment() method <strong>updates the state</strong> using this.setState().</li><li>Clicking the button <strong>triggers a re-render</strong> with the updated count.</li></ul><h3>Understanding Lifecycle Methods</h3><p>One of the key advantages of class components is the ability to use <strong>lifecycle methods</strong>. These methods allow you to execute code at different stages of a component’s life.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*8XslxHGIuWZQgLJndiPT9A.png" /></figure><p>Example: Timer Component Using Lifecycle Methods</p><pre>import React, { Component } from &#39;react&#39;;<br><br>class Timer extends Component {<br>  constructor() {<br>    super();<br>    this.state = { seconds: 0 };<br>  }<br><br>  componentDidMount() {<br>    this.interval = setInterval(() =&gt; {<br>      this.setState({ seconds: this.state.seconds + 1 });<br>    }, 1000);<br>  }<br><br>  componentWillUnmount() {<br>    clearInterval(this.interval);<br>  }<br><br>  render() {<br>    return &lt;h1&gt;Timer: {this.state.seconds}s&lt;/h1&gt;;<br>  }<br>}<br><br>export default Timer;</pre><ol><li><strong>componentDidMount()</strong> → Starts a timer when the component loads.</li><li><strong>componentWillUnmount()</strong> → Clears the timer when the component is removed.</li></ol><h3>Class Components vs Functional Components</h3><p>With the introduction of hooks, many developers have switched to <strong>functional components</strong>. Here’s how they compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*dTlZo6_TiRX2wyecWavPqA.png" /></figure><h3>Should You Still Use Class Components?</h3><p>Although functional components are now the preferred approach, class components are still useful when:<br>✅ <strong>Working on older React projects</strong> that don’t use hooks.<br>✅ <strong>Maintaining legacy applications</strong> built before hooks were introduced.<br>✅ <strong>Preparing for job interviews</strong>, as many companies still ask about class-based components.</p><p>If you’re starting a new project, it’s better to use functional components with hooks. But understanding class components will make you a well-rounded React developer!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81f606700f17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering useReducer in React: A Comprehensive Guide]]></title>
            <link>https://medium.com/@abhisingh622000/mastering-usereducer-in-react-a-comprehensive-guide-dbb02db3fced?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbb02db3fced</guid>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 18:20:31 GMT</pubDate>
            <atom:updated>2025-01-14T18:20:31.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cy7xv_o07yw1tHsBqSboBg.jpeg" /></figure><p>React’s useReducer hook is a powerful tool for managing complex state logic in functional components. Whether you’re building a counter or managing intricate forms, useReducer provides a predictable way to handle state updates.</p><h3>What is useReducer?</h3><p>useReducer is a React Hook that works similarly to Redux for managing state. Instead of using multiple useState hooks, useReducer centralizes state management into a single reducer function.</p><p>Syntax of useReducer</p><pre>const [state, dispatch] = useReducer(reducer, initialState);</pre><ul><li><strong>reducer</strong>: A function that determines how the state changes based on the action.</li><li><strong>initialState</strong>: The starting value of your state.</li><li><strong>dispatch</strong>: A function to trigger actions.</li></ul><h3>When to Use useReducer?</h3><ul><li>When state logic is complex and involves multiple sub-values.</li><li>When the next state depends on the previous state.</li><li>When state updates involve several conditions or actions.</li></ul><h3>Simple Example: Counter with useReducer</h3><p><strong>Step 1</strong>: Define the Reducer Function</p><pre>function counterReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;decrement&#39;:<br>      return { count: state.count - 1 };<br>    case &#39;reset&#39;:<br>      return { count: 0 };<br>    default:<br>      throw new Error(&#39;Unknown action type&#39;);<br>  }<br>}</pre><p><strong>Step 2</strong>: Implement the Counter Component</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>function Counter() {<br>  const initialState = { count: 0 };<br>  const [state, dispatch] = useReducer(counterReducer, initialState);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {state.count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39; })}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;-&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;reset&#39; })}&gt;Reset&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><h3>Advanced Use Case: Managing a Form with useReducer</h3><p><strong>Step 1</strong>: Define the Reducer</p><pre>function formReducer(state, action) {<br>  switch (action.type) {<br>    case &#39;updateField&#39;:<br>      return { ...state, [action.field]: action.value };<br>    case &#39;reset&#39;:<br>      return { name: &#39;&#39;, email: &#39;&#39; };<br>    default:<br>      throw new Error(&#39;Unknown action type&#39;);<br>  }<br>}</pre><p><strong>Step 2</strong>: Implement the Form Component</p><pre>import React, { useReducer } from &#39;react&#39;;<br><br>function Form() {<br>  const initialState = { name: &#39;&#39;, email: &#39;&#39; };<br>  const [state, dispatch] = useReducer(formReducer, initialState);<br><br>  const handleChange = (e) =&gt; {<br>    dispatch({<br>      type: &#39;updateField&#39;,<br>      field: e.target.name,<br>      value: e.target.value,<br>    });<br>  };<br><br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    console.log(&#39;Form submitted:&#39;, state);<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;input<br>        name=&quot;name&quot;<br>        value={state.name}<br>        onChange={handleChange}<br>        placeholder=&quot;Name&quot;<br>      /&gt;<br>      &lt;input<br>        name=&quot;email&quot;<br>        value={state.email}<br>        onChange={handleChange}<br>        placeholder=&quot;Email&quot;<br>      /&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>      &lt;button type=&quot;button&quot; onClick={() =&gt; dispatch({ type: &#39;reset&#39; })}&gt;<br>        Reset<br>      &lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}<br><br>export default Form;</pre><h3>Advantages of useReducer Over useState</h3><ul><li><strong>Better State Management</strong>: Centralizes state updates for complex scenarios.</li><li><strong>Predictable Updates</strong>: Reducer functions make state transitions clear and predictable.</li><li><strong>Code Organization</strong>: Keeps logic clean and easier to test.</li></ul><h3>Best Practices for Using useReducer</h3><ol><li><strong>Use it for complex logic</strong>: This is preferred useReducer when managing intricate or interdependent state logic.</li><li><strong>Combine with Context</strong>: Pair useReducer with the Context API for global state management.</li><li><strong>Keep Reducers Simple</strong>: Reducer functions should focus solely on updating state, avoiding side effects.</li></ol><h3>Conclusion</h3><p>The useReducer hook is a versatile and efficient tool for managing state in React applications. By adopting it, you can simplify complex logic, maintain a clean codebase, and make your applications more scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbb02db3fced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comparing Fetch and Axios: Which Should You Use in React?]]></title>
            <link>https://medium.com/@abhisingh622000/comparing-fetch-and-axios-which-should-you-use-in-react-ee19675f4e09?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee19675f4e09</guid>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 18:50:45 GMT</pubDate>
            <atom:updated>2025-01-13T18:50:45.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7p5FFV7qkv6-lmS-nfDA3w.jpeg" /></figure><p>When working with APIs in React, two popular tools often come up: the built-in fetch API and the third-party library axios. In this blog, we&#39;ll explore both, compare their features, and guide you on when to use each.</p><h4>1. Understanding the Fetch API</h4><p>The fetch API is a native browser API that makes HTTP requests.</p><p><strong>Basic Example</strong>:</p><pre>fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>  .then((response) =&gt; response.json())<br>  .then((data) =&gt; console.log(data))<br>  .catch((error) =&gt; console.error(&#39;Error:&#39;, error));</pre><p><strong>Pros of Fetch</strong>:</p><ul><li>Built into modern browsers;<strong> no installation required</strong>.</li><li><strong>Lightweight and straightforward</strong> for simple use cases.</li></ul><p><strong>Cons of Fetch</strong>:</p><ul><li><strong>Doesn’t handle timeouts</strong> natively.</li><li>Requires <strong>additional steps for error handling</strong>.</li></ul><h4>2. Getting Started with Axios</h4><p>Axios is a popular HTTP client library that simplifies API requests.</p><p><strong>Basic Example</strong>:</p><pre>import axios from &#39;axios&#39;;<br><br>axios.get(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>  .then((response) =&gt; console.log(response.data))<br>  .catch((error) =&gt; console.error(&#39;Error:&#39;, error));</pre><p><strong>Pros of Axios</strong>:</p><ul><li><strong>Built-in support for timeouts and interceptors</strong>.</li><li><strong>Automatically parses</strong> JSON responses.</li><li>More <strong>concise syntax for complex requests</strong>.</li></ul><p><strong>Cons of Axios</strong>:</p><ul><li><strong>Requires installation </strong>(npm install axios).</li><li>Slightly <strong>larger bundle size</strong> compared to Fetch.</li></ul><h4>3. Feature Comparison: Fetch vs Axios</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*bF1X7g4lVuAT8h47bSKBNg.png" /></figure><h4>4. Advanced Use Cases</h4><p><strong>Error Handling with Fetch</strong>:</p><pre>fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>  .then((response) =&gt; {<br>    if (!response.ok) {<br>      throw new Error(&#39;Network response was not ok&#39;);<br>    }<br>    return response.json();<br>  })<br>  .then((data) =&gt; console.log(data))<br>  .catch((error) =&gt; console.error(&#39;Error:&#39;, error));</pre><p><strong>Using Axios Interceptors</strong>:</p><pre>axios.interceptors.request.use(<br>  (config) =&gt; {<br>    console.log(&#39;Request Sent:&#39;, config);<br>    return config;<br>  },<br>  (error) =&gt; Promise.reject(error)<br>);</pre><h4>5. When to Use Fetch vs Axios</h4><p>Use <strong>Fetch</strong> if:</p><ul><li>You prefer a lightweight, native solution.</li><li>Your use case is simple and doesn’t need advanced features.</li></ul><p>Use <strong>Axios</strong> if:</p><ul><li>You need robust error handling, interceptors, or timeout support.</li><li>Your project involves complex API integrations.</li></ul><h4>Conclusion</h4><p>Both Fetch and Axios are excellent tools for API requests. Choosing between them depends on your project requirements and preferences. By understanding their differences, you can make an informed decision for your React application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee19675f4e09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Loading State in React: A Complete Guide]]></title>
            <link>https://medium.com/@abhisingh622000/managing-loading-state-in-react-a-complete-guide-20e8a5370435?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/20e8a5370435</guid>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 17:04:16 GMT</pubDate>
            <atom:updated>2025-01-13T17:04:16.188Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1RvuCKFrY-z2UWPfsG2Jg.jpeg" /></figure><p>Handling loading states is an essential part of building user-friendly React applications. It ensures users stay informed while waiting for operations like data fetching, form submissions, or lazy loading components. In this blog, we’ll explore various ways to effectively manage loading states in React.</p><h4>Why Manage Loading States?</h4><p>Loading states improve the user experience by:</p><ul><li>Providing feedback during asynchronous operations.</li><li>Avoiding confusion when a UI seems unresponsive.</li><li>Keeping users engaged with visual cues (like spinners or progress bars).</li></ul><h3>Approaches to Managing Loading States in React</h3><h4>1. Using useState For basic Loading States</h4><p>In simple cases, the useState hook is the go-to solution.</p><p><strong>Example: Loading State for Data Fetching</strong></p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function DataFetcher() {<br>  const [loading, setLoading] = useState(false);<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    setLoading(true);<br>    fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>      .then((response) =&gt; response.json())<br>      .then((data) =&gt; {<br>        setData(data);<br>        setLoading(false);<br>      });<br>  }, []);<br><br>  if (loading) return &lt;p&gt;Loading...&lt;/p&gt;;<br>  if (!data) return &lt;p&gt;No data available&lt;/p&gt;;<br><br>  return (<br>    &lt;ul&gt;<br>      {data.map((item) =&gt; (<br>        &lt;li key={item.id}&gt;{item.title}&lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>}<br><br>export default DataFetcher;</pre><h4>2. Using Custom Hooks for Reusable Logic</h4><p>When multiple components need similar loading logic, custom hooks simplify the process.</p><p><strong>Example: </strong><strong>useLoading Hook</strong></p><pre>import { useState } from &#39;react&#39;;<br><br>function useLoading(asyncFunction) {<br>  const [loading, setLoading] = useState(false);<br><br>  const execute = async (...args) =&gt; {<br>    setLoading(true);<br>    await asyncFunction(...args);<br>    setLoading(false);<br>  };<br><br>  return [loading, execute];<br>}<br><br>// Usage<br>import React from &#39;react&#39;;<br>import useLoading from &#39;./useLoading&#39;;<br><br>function SubmitForm() {<br>  const [loading, submit] = useLoading(async () =&gt; {<br>    await new Promise((resolve) =&gt; setTimeout(resolve, 2000));<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={submit} disabled={loading}&gt;<br>        {loading ? &#39;Submitting...&#39; : &#39;Submit&#39;}<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>3. Global Loading State with Context API</h4><p>For applications where multiple components share loading states, the Context API is useful.</p><p><strong>Example: Global Loading Context</strong></p><pre>import React, { createContext, useContext, useState } from &#39;react&#39;;<br><br>const LoadingContext = createContext();<br><br>export function LoadingProvider({ children }) {<br>  const [loading, setLoading] = useState(false);<br><br>  return (<br>    &lt;LoadingContext.Provider value={{ loading, setLoading }}&gt;<br>      {children}<br>    &lt;/LoadingContext.Provider&gt;<br>  );<br>}<br><br>export function useLoadingContext() {<br>  return useContext(LoadingContext);<br>}<br><br>// Usage<br>function App() {<br>  return (<br>    &lt;LoadingProvider&gt;<br>      &lt;ComponentA /&gt;<br>      &lt;ComponentB /&gt;<br>    &lt;/LoadingProvider&gt;<br>  );<br>}<br><br>function ComponentA() {<br>  const { loading, setLoading } = useLoadingContext();<br><br>  const handleClick = () =&gt; {<br>    setLoading(true);<br>    setTimeout(() =&gt; setLoading(false), 2000);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={handleClick}&gt;Start Loading&lt;/button&gt;<br>      {loading &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>4. Suspense and Concurrent Rendering</h4><p>React’s Suspense API simplifies loading state management for asynchronous rendering, especially with lazy-loaded components.</p><p><strong>Example: Lazy Loading Components</strong></p><pre>import React, { Suspense } from &#39;react&#39;;<br><br>const LazyComponent = React.lazy(() =&gt; import(&#39;./LazyComponent&#39;));<br><br>function App() {<br>  return (<br>    &lt;Suspense fallback={&lt;p&gt;Loading component...&lt;/p&gt;}&gt;<br>      &lt;LazyComponent /&gt;<br>    &lt;/Suspense&gt;<br>  );<br>}</pre><h3>Best Practices for Managing Loading States</h3><ol><li><strong>Always Provide Feedback</strong>: Users should always know when something is loading.</li><li><strong>Avoid Blocking UI</strong>: Use techniques like useTransition to prioritize updates.</li><li><strong>Handle Errors Gracefully</strong>: Combine loading states with error handling for a seamless user experience.</li><li><strong>Optimize for Performance</strong>: Use lightweight loaders and defer unnecessary updates.</li></ol><h3>Conclusion</h3><p>Managing loading states effectively can make a big difference in how users perceive your application. Whether building small projects or large-scale apps, these techniques will ensure your UI is responsive and user-friendly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20e8a5370435" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the useTransition Hook in React: A Beginner-Friendly Guide]]></title>
            <link>https://medium.com/@abhisingh622000/exploring-the-usetransition-hook-in-react-a-beginner-friendly-guide-293a04648c1b?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/293a04648c1b</guid>
            <category><![CDATA[react-usetransition]]></category>
            <category><![CDATA[say-goodbye-to-laggy-uis]]></category>
            <category><![CDATA[all-about-usetransition]]></category>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 05:54:40 GMT</pubDate>
            <atom:updated>2024-12-31T05:54:40.147Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*QkOo_1xhQj-xRnjcU3i0Iw.png" /></figure><p>React introduced the useTransition hook to provide developers with more control over how updates are prioritized. This hook is part of React&#39;s concurrent rendering capabilities, allowing you to create smoother, more responsive user interfaces by marking certain updates as low-priority or &quot;transitions.&quot;</p><p>In this blog, we’ll dive deep into how the useTransition hook works, its benefits, and how you can use it to improve user experience.</p><h4>What is the useTransition Hook?</h4><p>The useTransition hook allows you to manage transitions in React applications. Transitions are updates that don’t need to be immediate, such as navigating between pages, rendering a large list, or processing heavy computations in the background.</p><p>Using useTransition, you can:</p><ul><li>Mark an update as a non-urgent “transition.”</li><li>Provide feedback to users while the transition is in progress (e.g., showing a loading spinner).</li></ul><h4>Why Use useTransition?</h4><p>By default, React prioritizes all updates equally, which can lead to performance issues in complex applications. For instance:</p><ul><li>A user clicks a button to filter a large list.</li><li>The UI freezes momentarily because React processes the filtering synchronously.</li></ul><p>With useTransition, you can separate urgent updates (like button clicks) from non-urgent ones (like filtering), ensuring the UI remains responsive.</p><h4>Syntax of useTransition</h4><p>The useTransition hook provides two values:</p><ol><li>isPending: A boolean indicating if the transition is ongoing.</li><li>startTransition: A function to start the transition.</li></ol><p>Here’s the basic syntax:</p><pre>const [isPending, startTransition] = useTransition();</pre><h4>Example: Filtering a Large List with useTransition</h4><p>Let’s see how useTransition can improve performance when filtering a large list.</p><pre>import React, { useState, useTransition } from &#39;react&#39;;<br><br>function App() {<br>  const [filter, setFilter] = useState(&#39;&#39;);<br>  const [items, setItems] = useState(Array.from({ length: 10000 },<br>   (_, i) =&gt; `Item ${i}`));<br>  const [filteredItems, setFilteredItems] = useState(items);<br><br>  const [isPending, startTransition] = useTransition();<br><br>  const handleFilterChange = (event) =&gt; {<br>    const value = event.target.value;<br>    setFilter(value);<br><br>    startTransition(() =&gt; {<br>      setFilteredItems(items.filter((item) =&gt; item.includes(value)));<br>    });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;text&quot;<br>        value={filter}<br>        onChange={handleFilterChange}<br>        placeholder=&quot;Filter items&quot;<br>      /&gt;<br>      {isPending &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br>      &lt;ul&gt;<br>        {filteredItems.map((item, index) =&gt; (<br>          &lt;li key={index}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h4>Explanation</h4><ol><li><strong>State Separation</strong>: The filter and filteredItems states are managed independently.</li><li><strong>startTransition Usage</strong>: The startTransition function is used to update the filteredItems state asynchronously, ensuring the UI remains responsive.</li><li><strong>Loading Feedback</strong>: While the transition is pending, the isPending flag is true, allowing you to show a loading message.</li></ol><h4>When Should You Use useTransition?</h4><p>The useTransition hook is ideal for scenarios where:</p><ul><li><strong>Non-Urgent Updates</strong>: You want to deprioritize updates that don’t need to happen immediately, such as animations, data filtering, or rendering large lists.</li><li><strong>User Feedback</strong>: Providing feedback (like a spinner or message) during long-running tasks improves the user experience.</li></ul><h4>Common Mistakes to Avoid</h4><ol><li><strong>Overusing </strong><strong>useTransition</strong>: Not all updates need to be transitions. Use it only for updates that impact performance or responsiveness.</li><li><strong>Not Handling Pending State</strong>: Always use the isPending flag to provide feedback during transitions, ensuring users know that something is happening.</li></ol><h4>Benefits of Using useTransition</h4><ul><li><strong>Improved Performance</strong>: By deprioritizing non-urgent updates, the UI remains fast and responsive.</li><li><strong>Better User Experience</strong>: Users see immediate feedback for actions, reducing the perception of delays.</li><li><strong>Easier State Management</strong>: Separating urgent and non-urgent updates simplifies component logic.</li></ul><h4>Best Practices for useTransition</h4><ol><li><strong>Use </strong><strong>useTransition Sparingly</strong>: Focus on high-impact areas where responsiveness matters most.</li><li><strong>Provide Clear Feedback</strong>: Always show loading indicators or messages when transitions are pending.</li><li><strong>Combine with Suspense</strong>: For data fetching scenarios, combine useTransition with React’s Suspense to manage loading states seamlessly.</li></ol><h4>Advanced Usage: Navigating Between Pages</h4><p>Here’s how useTransition can be used in a multi-page application:</p><pre>import React, { useState, useTransition } from &#39;react&#39;;<br><br>function App() {<br>  const [page, setPage] = useState(&#39;Home&#39;);<br>  const [isPending, startTransition] = useTransition();<br><br>  const navigate = (nextPage) =&gt; {<br>    startTransition(() =&gt; {<br>      setPage(nextPage);<br>    });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; navigate(&#39;Home&#39;)}&gt;Home&lt;/button&gt;<br>      &lt;button onClick={() =&gt; navigate(&#39;About&#39;)}&gt;About&lt;/button&gt;<br><br>      {isPending &amp;&amp; &lt;p&gt;Loading...&lt;/p&gt;}<br><br>      &lt;div&gt;<br>        {page === &#39;Home&#39; &amp;&amp; &lt;h1&gt;Welcome to the Home Page&lt;/h1&gt;}<br>        {page === &#39;About&#39; &amp;&amp; &lt;h1&gt;About Us&lt;/h1&gt;}<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><h4>Conclusion</h4><p>The useTransition hook is a powerful tool for managing non-urgent updates in React applications. By leveraging concurrent rendering, you can ensure your UI remains smooth and responsive, even during intensive operations. Use useTransition wisely, provide clear feedback, and combine it with other React features to create a seamless user experience.</p><p>Feel free to share your thoughts or questions about this blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=293a04648c1b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Zero to Hero: A Beginner’s Journey with Docker]]></title>
            <link>https://medium.com/@abhisingh622000/from-zero-to-hero-a-beginners-journey-with-docker-41beebe885d9?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/41beebe885d9</guid>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Wed, 04 Dec 2024 13:43:59 GMT</pubDate>
            <atom:updated>2024-12-04T13:43:59.264Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_-jPNR1L9-n7g3-wgdXVQ.png" /></figure><h3>What is Docker?</h3><p>At its core, Docker is a platform that helps you package your applications and their dependencies into <strong>containers</strong>. Think of a container as a lightweight, portable box that contains everything your app needs to run — code, libraries, tools, and settings.</p><p><strong>Why use Docker?</strong></p><ul><li><strong>Consistency:</strong> Runs the same code in any environment.</li><li><strong>Efficiency:</strong> Uses fewer resources compared to virtual machines.</li><li><strong>Portability:</strong> Works on your laptop, server, or cloud.</li></ul><h3>How Docker Works</h3><p>Docker works with three main components:</p><ol><li><strong>Images:</strong> A template that contains your app and its dependencies.</li><li><strong>Containers:</strong> A running instance of an image.</li><li><strong>Docker Engine:</strong> The software that runs and manages containers.</li></ol><h3>Getting Started with Docker</h3><h4>1. Install Docker</h4><p>Visit the <a href="https://www.docker.com/">Docker website</a> and download Docker Desktop for your system (Windows, macOS, or Linux).</p><h4>2. Docker Basics</h4><p>Once installed, open a terminal and check if Docker is working:</p><pre>docker --version</pre><h4>3. Pull an Image</h4><p>Docker Hub is like an app store for Docker images. Let’s pull an image:</p><pre>docker pull hello-world</pre><h4>4. Run a Container</h4><p>Now, run the image as a container:</p><pre>docker run hello-world</pre><h3>Building Your Own Docker Image</h3><p>Let’s create an image for a simple Node.js app.</p><h4>Step 1: Create a Node.js App</h4><p>Create a file app.js:</p><pre>const http = require(&#39;http&#39;);<br>const PORT = 3000;<br><br>const server = http.createServer((req, res) =&gt; {<br>  res.end(&#39;Hello, Docker!&#39;);<br>});<br><br>server.listen(PORT, () =&gt; {<br>  console.log(`Server is running on port ${PORT}`);<br>});</pre><h4>Step 2: Create a Dockerfile</h4><p>A Dockerfile is a recipe for building your image.</p><pre># Use a base image<br>FROM node:14<br><br># Set the working directory<br>WORKDIR /app<br><br># Copy the app files<br>COPY . .<br><br># Install dependencies<br>RUN npm install<br><br># Expose the app port<br>EXPOSE 3000<br><br># Command to run the app<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><h4>Step 3: Build the Image</h4><p>Run the following command in the terminal:</p><pre>docker build -t my-node-app .</pre><h4>Step 4: Run the Container</h4><p>Run your app in a container:</p><pre>docker run -p 3000:3000 my-node-app</pre><p>Visit http://localhost:3000 in your browser—you’ll see &quot;Hello, Docker!&quot;.</p><h3>Working with Docker Compose</h3><p>Docker Compose helps manage multi-container applications.</p><h4>Example: A Node.js App with a Database</h4><ol><li><strong>Create a </strong><strong>docker-compose.yml file:</strong></li></ol><pre>version: &#39;3.8&#39;<br>services:<br>  app:<br>    build: .<br>    ports:<br>      - &quot;3000:3000&quot;<br>    depends_on:<br>      - db<br>  db:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_USER: user<br>      POSTGRES_PASSWORD: password</pre><p>2. Run the app:</p><pre>docker-compose up</pre><h3>Advanced Docker Concepts</h3><h4>1. Volumes</h4><p>To persist data, use Docker Volumes.</p><pre>docker run -v /mydata:/data alpine</pre><h4>2. Networking</h4><p>Docker allows containers to communicate via networks.</p><pre>docker network create my-network</pre><h4>3. Docker Swarm</h4><p>For scaling applications, use Docker Swarm for container orchestration.</p><h3>Best Practices for Using Docker</h3><ol><li>Keep your images lightweight by using minimal base images like alpine.</li><li>Use .dockerignore to avoid copying unnecessary files into your image.</li><li>Regularly clean up unused images and containers with</li></ol><pre>docker system prune</pre><h3>Conclusion</h3><p>Docker simplifies application development and deployment, making your projects consistent and portable. Whether you’re a beginner or a pro, Docker has something to offer. Start experimenting today, and soon you’ll be deploying apps with ease!</p><p>Does this guide feel clear? Let me know if you’d like any section elaborated! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41beebe885d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the useContext Hook in React: A Comprehensive Guide]]></title>
            <link>https://medium.com/@abhisingh622000/understanding-the-usecontext-hook-in-react-a-comprehensive-guide-909069bdf7ee?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/909069bdf7ee</guid>
            <category><![CDATA[best-practices-usecontext]]></category>
            <category><![CDATA[when-to-use-usecontext]]></category>
            <category><![CDATA[what-is-usecontext]]></category>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Mon, 14 Oct 2024 20:37:50 GMT</pubDate>
            <atom:updated>2024-10-14T20:37:50.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Em3HOZw7aaTDHB-s22zAXA.jpeg" /></figure><p>In React, managing state and passing data between components can sometimes feel like a challenge, especially when dealing with deeply nested components. This is where the useContext hook comes into play. It provides a more straightforward way to share state across components without manually passing props at every level. In this blog, we’ll break down how useContext works and show you how to use it effectively with easy examples.</p><h4>What is useContext?</h4><p>useContext is a hook that allows you to consume context in functional components. Context provides a way to share values like state or functions between components without having to explicitly pass props down every level of the tree.</p><h4>Why Use useContext?</h4><p>React’s context is particularly useful when:</p><ul><li>You have global data or functions (like theme, authentication status, or user data) that many components need access to.</li><li>Passing props through multiple layers (prop drilling) becomes cumbersome or redundant.</li></ul><p>The useContext hook simplifies accessing context values directly, eliminating the need to wrap components with the context consumer.</p><h4>How useContext Works</h4><p>To understand useContext, you first need to understand the <strong>Context API</strong> in React. The Context API is made up of two key parts:</p><ul><li><strong>Context Provider</strong>: Holds the values to be shared with child components.</li><li><strong>Context Consumer</strong>: Reads the values from the provider.</li></ul><p>With the useContext hook, you don’t need to use the consumer component explicitly—you can access context values directly in your functional components.</p><h4>Basic Example of useContext</h4><p>Let’s go through a simple example to see how useContext works in a React application.</p><p>Step 1: Create a Context</p><pre>import React, { useContext, useState } from &#39;react&#39;;<br><br>// Create a context<br>const UserContext = React.createContext();<br><br>function App() {<br>  const [user, setUser] = useState({ name: &#39;John Doe&#39;, loggedIn: true });<br><br>  return (<br>    // Provide the context value to child components<br>    &lt;UserContext.Provider value={user}&gt;<br>      &lt;Navbar /&gt;<br>    &lt;/UserContext.Provider&gt;<br>  );<br>}<br><br>function Navbar() {<br>  return (<br>    &lt;nav&gt;<br>      &lt;h1&gt;My Application&lt;/h1&gt;<br>      &lt;UserInfo /&gt;<br>    &lt;/nav&gt;<br>  );<br>}<br><br>function UserInfo() {<br>  // Use the useContext hook to consume the context<br>  const user = useContext(UserContext);<br><br>  return (<br>    &lt;div&gt;<br>      {user.loggedIn ? (<br>        &lt;p&gt;Welcome, {user.name}!&lt;/p&gt;<br>      ) : (<br>        &lt;p&gt;Please log in.&lt;/p&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Explanation:</strong></p><ol><li>We create a context using React.createContext(), which is used to share data across components.</li><li>In the App component, we provide the user data ({ name: &#39;John Doe&#39;, loggedIn: true }) to the rest of the application using the UserContext.Provider.</li><li>The useContext hook is used inside UserInfo to access the user context and display relevant information based on whether the user is logged in.</li></ol><h4>When Should You Use useContext?</h4><p>useContext is best used when:</p><ul><li>You have global data that multiple components need to access, like user information, themes, or preferences.</li><li>Prop drilling becomes too complex or difficult to maintain.</li><li>You want to decouple components from passing data through intermediate components that don’t need the data themselves.</li></ul><h4>Avoiding Prop Drilling with useContext</h4><p>Without useContext, you would need to pass the user prop through every intermediate component, even if they don’t use it directly:</p><pre>function App() {<br>  const [user, setUser] = useState({ name: &#39;John Doe&#39;, loggedIn: true });<br><br>  return &lt;Navbar user={user} /&gt;;<br>}<br><br>function Navbar({ user }) {<br>  return (<br>    &lt;nav&gt;<br>      &lt;h1&gt;My Application&lt;/h1&gt;<br>      &lt;UserInfo user={user} /&gt;<br>    &lt;/nav&gt;<br>  );<br>}<br><br>function UserInfo({ user }) {<br>  return (<br>    &lt;div&gt;<br>      {user.loggedIn ? &lt;p&gt;Welcome, {user.name}!&lt;/p&gt; : &lt;p&gt;Please log in.&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This method is fine for smaller applications but quickly becomes hard to manage as your application grows. useContext solves this by eliminating the need to pass props through intermediary components.</p><h4>Combining useContext with useReducer</h4><p>A common pattern is to combine useContext with useReducer for state management. This pattern is especially useful in larger applications where you need a global state management system.</p><p>Here’s how you can use them together:</p><p>Example: Using useReducer with useContext</p><pre>import React, { useReducer, useContext } from &#39;react&#39;;<br><br>// Create a context for the counter<br>const CounterContext = React.createContext();<br><br>const initialState = { count: 0 };<br><br>function reducer(state, action) {<br>  switch (action.type) {<br>    case &#39;increment&#39;:<br>      return { count: state.count + 1 };<br>    case &#39;decrement&#39;:<br>      return { count: state.count - 1 };<br>    default:<br>      throw new Error();<br>  }<br>}<br><br>function App() {<br>  const [state, dispatch] = useReducer(reducer, initialState);<br><br>  return (<br>    &lt;CounterContext.Provider value={{ state, dispatch }}&gt;<br>      &lt;Counter /&gt;<br>    &lt;/CounterContext.Provider&gt;<br>  );<br>}<br><br>function Counter() {<br>  const { state, dispatch } = useContext(CounterContext);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;Count: {state.count}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;increment&#39; })}&gt;+&lt;/button&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: &#39;decrement&#39; })}&gt;-&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p><strong>Explanation:</strong></p><ol><li>We create a context (CounterContext) and set up the state management using useReducer.</li><li>The CounterContext.Provider makes the state and the dispatch function available to the entire component tree.</li><li>The useContext hook is used in the Counter component to access the state and dispatch actions.</li></ol><p>This pattern provides a clean and scalable way to manage global state across components, similar to how Redux works, but with less boilerplate.</p><h4>Best Practices for Using useContext</h4><p>Here are a few best practices to keep in mind when using useContext in your applications:</p><ol><li><strong>Use context sparingly</strong>: Don’t overuse context. Not all state needs to be shared globally. If a piece of state is only used by a few components, consider lifting state up instead of using context.</li><li><strong>Use separate contexts</strong>: It’s a good idea to separate your concerns by creating different contexts for different pieces of data (e.g., user context, theme context, etc.). This helps keep your context structure manageable.</li><li><strong>Optimize performance</strong>: Avoid re-renders in deeply nested components by ensuring the context value doesn’t change unnecessarily. Memoizing context values or splitting context can help.</li></ol><h4>Debugging Tips for useContext</h4><p>Sometimes, context issues can be tricky to debug. Here are some tips to help you out:</p><ul><li><strong>Check the Provider</strong>: Make sure that the context provider is wrapping the components that need access to the context.</li><li><strong>Check Value Updates</strong>: If the value passed to the provider changes, ensure that it triggers a re-render in the consumers. Use console.log or React DevTools to monitor changes.</li><li><strong>Memoize Context Values</strong>: To prevent unnecessary re-renders, memoize complex context values using useMemo.</li></ul><h4>Conclusion</h4><p>The useContext hook simplifies state sharing between components in React. It allows you to avoid prop drilling, making your component hierarchy cleaner and easier to maintain. By following best practices, using useContext in combination with other hooks (like useReducer), and being mindful of performance, you can build more efficient, scalable React applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=909069bdf7ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the useEffect Hook in React: A Complete Guide]]></title>
            <link>https://medium.com/@abhisingh622000/understanding-the-useeffect-hook-in-react-a-complete-guide-e22cc37cac6f?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e22cc37cac6f</guid>
            <category><![CDATA[when-to-use-useeffect]]></category>
            <category><![CDATA[what-is-a-side-effect]]></category>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 15:23:28 GMT</pubDate>
            <atom:updated>2024-10-13T15:27:31.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K-8x2Jb6pke8jkYy1o-zaA.jpeg" /></figure><p>In React, the useEffect hook is one of the most commonly used hooks. It helps manage <strong>side effects</strong> in functional components, such as fetching data, directly manipulating the DOM, or setting up event listeners. In this blog, we&#39;ll dive deep into how useEffect works, and how to use it effectively with easy-to-understand code snippets.</p><h4>What is the useEffect Hook?</h4><p>The useEffect hook lets you perform side effects in your functional components. Before hooks, side effects were handled in lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount in class components. Now, useEffect combines these functionalities into one API, making it easier to manage in functional components.</p><h4>Why Use useEffect?</h4><p>A <strong>side effect</strong> in React refers to anything that affects something outside the scope of your component’s logic, such as:</p><ul><li>Fetching data from an API.</li><li>Directly manipulating the DOM.</li><li>Setting up subscriptions or timers.</li></ul><p>The useEffect hook ensures these operations are performed at the right time—after rendering. By default, React executes useEffect after every render, but you can control when and how often it runs.</p><h4>Syntax of useEffect</h4><pre>useEffect(() =&gt; {<br>  // Your side effect code here<br>}, [dependencies]);</pre><ul><li><strong>Effect Function</strong>: The first argument is a function where you write your side effect logic.</li><li><strong>Dependencies Array</strong>: The second argument is an optional array of values that the effect depends on. React will only re-run the effect if one of these values changes.</li></ul><h4>Basic Example: Logging to the Console</h4><p>Here’s a simple example that logs a message to the console whenever the component renders:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function LoggerComponent() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;Component has rendered!&#39;);<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase Count&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default LoggerComponent;</pre><p><strong>Explanation:</strong></p><ul><li>useEffect runs after every render of the component.</li><li>The message &quot;Component has rendered!&quot; will be logged to the console every time the count state is updated and the component re-renders.</li></ul><h4>Controlling useEffect with Dependencies</h4><p>Sometimes, you only want your effect to run when specific values change. This is where the <strong>dependencies array</strong> comes into play.</p><p>Example: Fetching Data Only Once</p><p>Let’s say you want to fetch data from an API only when the component mounts (renders for the first time). You can achieve this by passing an empty dependencies array [] to useEffect. This tells React to run the effect only once.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function DataFetcher() {<br>  const [data, setData] = useState([]);<br><br>  useEffect(() =&gt; {<br>    // Fetch data from an API<br>    fetch(&#39;https://jsonplaceholder.typicode.com/posts&#39;)<br>      .then(response =&gt; response.json())<br>      .then(data =&gt; setData(data));<br>  }, []); // Empty array means this effect runs only once <br>          // after the first render<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Posts&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {data.map(post =&gt; (<br>          &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default DataFetcher;</pre><h4>Cleaning Up with useEffect</h4><p>Some side effects require cleanup, such as setting up timers, event listeners, or subscriptions. When the component unmounts or the effect is re-run, you need to clean up these effects to prevent memory leaks.</p><p>Example: Cleaning Up a Timer</p><p>In this example, we’ll set up a timer that increments a counter every second and clean it up when the component unmounts.</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function Timer() {<br>  const [seconds, setSeconds] = useState(0);<br><br>  useEffect(() =&gt; {<br>    const interval = setInterval(() =&gt; {<br>      setSeconds(prevSeconds =&gt; prevSeconds + 1);<br>    }, 1000);<br><br>    // Cleanup function to clear the timer<br>    return () =&gt; {<br>      clearInterval(interval);<br>    };<br>  }, []); // Empty array means this effect runs only once<br><br>  return &lt;h1&gt;Seconds: {seconds}&lt;/h1&gt;;<br>}<br><br>export default Timer;</pre><p><strong>Explanation:</strong></p><ul><li>We set up a timer using setInterval to increment the seconds state every second.</li><li>The cleanup function inside useEffect (returned function) clears the timer when the component unmounts or when the effect needs to be re-run. This prevents memory leaks by ensuring the timer doesn’t continue running in the background after the component is destroyed.</li></ul><h4>Running useEffect Conditionally</h4><p>You can conditionally run effects by passing specific dependencies to the dependencies array. This tells React to only re-run the effect when one of the specified dependencies changes.</p><p>Example: Updating Document Title Based on State</p><p>Here’s an example where the document title updates whenever the count changes:</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function TitleUpdater() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    document.title = `Count: ${count}`;<br>  }, [count]); // The effect runs only when &#39;count&#39; changes<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase Count&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default TitleUpdater;</pre><p><strong>Explanation:</strong></p><ul><li>The useEffect hook updates the document title only when the count changes.</li><li>By adding [count] as a dependency, we ensure the effect is re-run only when count is updated, not on every render.</li></ul><h4>Multiple Effects in One Component</h4><p>You can use multiple useEffect hooks within the same component. Each useEffect can handle a different side effect.</p><p>Example: Combining Different Side Effects</p><pre>import React, { useState, useEffect } from &#39;react&#39;;<br><br>function MultiEffectComponent() {<br>  const [count, setCount] = useState(0);<br>  const [message, setMessage] = useState(&#39;&#39;);<br><br>  // Effect 1: Update document title based on count<br>  useEffect(() =&gt; {<br>    document.title = `Count: ${count}`;<br>  }, [count]);<br><br>  // Effect 2: Log a message when message state changes<br>  useEffect(() =&gt; {<br>    console.log(&#39;Message changed:&#39;, message);<br>  }, [message]);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase Count&lt;/button&gt;<br><br>      &lt;input<br>        type=&quot;text&quot;<br>        value={message}<br>        onChange={e =&gt; setMessage(e.target.value)}<br>        placeholder=&quot;Type a message&quot;<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default MultiEffectComponent;</pre><p><strong>Explanation:</strong></p><ul><li>We have two effects: one for updating the document title when count changes, and another for logging a message to the console when message changes.</li><li>These effects work independently of each other, but within the same component.</li></ul><h4>Key Takeaways</h4><ul><li>useEffect is essential for managing side effects in functional components.</li><li>It runs after the component renders and can be controlled with the dependencies array to decide when and how often to run.</li><li>Cleanup functions help prevent memory leaks by handling side effects that need to be cleared when the component unmounts.</li><li>You can have multiple useEffect hooks in a single component to handle different side effects separately.</li></ul><h4>Conclusion</h4><p>The useEffect hook is a powerful tool that simplifies managing side effects in React functional components. Understanding how to control when and how your effects run is key to writing efficient and bug-free code.</p><p>Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e22cc37cac6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the useState hook in React: A Beginner-Friendly Guide]]></title>
            <link>https://medium.com/@abhisingh622000/understanding-the-usestate-hook-in-react-a-beginner-friendly-guide-1522badb9c64?source=rss-c9c73c4b566d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1522badb9c64</guid>
            <category><![CDATA[usestate-hook]]></category>
            <category><![CDATA[what-is-usestate-in-react]]></category>
            <category><![CDATA[how-usestate-works]]></category>
            <dc:creator><![CDATA[Abhinav Singh]]></dc:creator>
            <pubDate>Sun, 13 Oct 2024 06:50:56 GMT</pubDate>
            <atom:updated>2024-10-13T06:50:56.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dTWlMHKBcrcUFm7gjYyTw.jpeg" /></figure><p>React is known for its ability to create dynamic and interactive user interfaces. One of the essential tools for managing state in <em>React functional components</em> is the useState hook. This blog will explore the useState hook in-depth, with simple explanations and code snippets to help you get started.</p><h4>What is the useState Hook?</h4><p>useState is a hook in React that allows you to add and manage the state of functional components. Before hooks, state management was only possible in class components. But with hooks like useState, you can now manage state in functional components, making them more powerful and concise.</p><h4>Why Do We Need State?</h4><p>In React, <strong>state</strong> refers to data that can change over time. For example, you might have a button that toggles between two modes, a list of items that grows or shrinks, or a form that updates as users type. State allows your component to “<em>remember</em>” values between renders and respond to user input or other events.</p><h4>Syntax of useState</h4><p>The useState hook is straightforward. Here&#39;s the syntax:</p><pre>const [state, setState] = useState(initialState);</pre><ul><li><strong>state</strong>: This is the current state value.</li><li><strong>setState</strong>: A function that updates the state.</li><li><strong>initialState</strong>: The initial value for your state (this can be a number, string, boolean, array, object, etc.).</li></ul><h4>Example: Counter App</h4><p>Let’s see a basic example where we use the useState hook to create a simple counter application.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Counter() {<br>  // Declare a state variable &#39;count&#39; with initial value 0<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Counter: {count}&lt;/h1&gt;<br>      {/* Button to increase the count */}<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;Increase&lt;/button&gt;<br>      {/* Button to decrease the count */}<br>      &lt;button onClick={() =&gt; setCount(count - 1)}&gt;Decrease&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default Counter;</pre><p><strong>Explanation:</strong></p><ul><li>We first import useState from React.</li><li>Inside the Counter component, we declare a state variable count and set its initial value to 0.</li><li>We then provide two buttons, one to increase the count and one to decrease it. Each button calls setCount to update the state based on the current value.</li></ul><h4>How useState Works</h4><ol><li>When the component renders for the first time, useState(0) initializes the state variable count with 0.</li><li>When the user clicks the “Increase” button, setCount(count + 1) updates the state, causing the component to re-render with the new value of count.</li><li>Similarly, clicking the “Decrease” button reduces the value by 1.</li></ol><p>React automatically keeps track of the state between renders and ensures the component updates whenever the state changes.</p><h4>Updating State Based on Previous State</h4><p>Sometimes, you must update the state based on the previous state value. In the counter example above, we could have written the setCount function as:</p><pre>&lt;button onClick={() =&gt; setCount(prevCount =&gt; prevCount + 1)}&gt;Increase&lt;/button&gt;</pre><p>Here, prevCount represents the previous state value. This approach is more reliable when multiple state updates happen asynchronously, as React batches updates to state.</p><h4>State and Objects</h4><p>The useState hook can also manage more complex data types like objects. Let&#39;s say we have a user object with a name and age:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function UserInfo() {<br>  const [user, setUser] = useState({ name: &#39;Abhinav&#39;, age: 23 });<br><br>  const changeName = () =&gt; {<br>    setUser({ ...user, name: &#39;Krishna&#39; });<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Name: {user.name}&lt;/h1&gt;<br>      &lt;h2&gt;Age: {user.age}&lt;/h2&gt;<br>      &lt;button onClick={changeName}&gt;Change Name&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UserInfo;</pre><p><strong>Explanation:</strong></p><ul><li>We initialize the user object in the state with a name and age.</li><li>The changeName function updates only the name while preserving the age using the spread operator (...user).</li></ul><h4>State and Arrays</h4><p>You can also use useState to manage arrays. For example, let&#39;s add and remove items from a list.</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function ItemList() {<br>  const [items, setItems] = useState([]);<br><br>  const addItem = () =&gt; {<br>    setItems([...items, `Item ${items.length + 1}`]);<br>  };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={addItem}&gt;Add Item&lt;/button&gt;<br>      &lt;ul&gt;<br>        {items.map((item, index) =&gt; (<br>          &lt;li key={index}&gt;{item}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ItemList;</pre><p><strong>Explanation:</strong></p><ul><li>The state variable items starts as an empty array.</li><li>Whenever we click “Add Item”, a new item is added to the list. We use the spread operator (...items) to copy the existing items and append the new ones.</li><li>The list is displayed using the map() function.</li></ul><h4>Key Points to Remember</h4><ul><li><strong>State is preserved between renders</strong>: The value you set in useState persists across multiple renders of the component.</li><li><strong>Re-rendering</strong>: When you update the state using setState, React re-renders the component to reflect the changes.</li><li><strong>Initial State</strong>: The initial state is set the first time the component renders. If it’s a complex calculation, you can pass a function to useState to set the initial state lazily.</li></ul><pre>const [state, setState] = useState(() =&gt; calculateInitialState());</pre><h4>Conclusion</h4><p>The useState hook is a powerful and easy-to-use feature of React that lets you manage state in functional components. Whether you&#39;re working with simple numbers, strings, or more complex data structures like objects and arrays, useState is your go-to tool. Mastering it is a key step in building dynamic and interactive applications in React.</p><h4>What’s Next?</h4><p>Once you’re comfortable with useState, you can explore other hooks like useEffect for side effects, or useReducer for more complex state logic.</p><p>Happy coding!</p><p>By- Abhinav Singh</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1522badb9c64" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>