<?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"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://abvs.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Wed, 09 Sep 2026 09:38:37 GMT</lastBuildDate><atom:link href="https://abvs.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[useEffect Hook: The What, When, and Where of Side-Effects & Cleanup]]></title><description><![CDATA[When you're building a React application, you often need to perform tasks that don't directly involve rendering the UI. These tasks, such as fetching data from an API, setting up a subscription, or manually changing the DOM, are called side effects. ...]]></description><link>https://abvs.hashnode.dev/useeffect-hook-the-what-when-and-where-of-side-effects-and-cleanup</link><guid isPermaLink="true">https://abvs.hashnode.dev/useeffect-hook-the-what-when-and-where-of-side-effects-and-cleanup</guid><category><![CDATA[React]]></category><category><![CDATA[useEffect]]></category><category><![CDATA[useEffect hook]]></category><category><![CDATA[react hooks]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Abhishek Kumar]]></dc:creator><pubDate>Sat, 13 Sep 2025 18:31:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1757787472300/87be7067-dbc8-4ef3-9503-78816eee1240.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When you're building a React application, you often need to perform tasks that don't directly involve rendering the UI. These tasks, such as fetching data from an API, setting up a subscription, or manually changing the DOM, are called <strong>side effects</strong>. The <code>useEffect</code> hook is a powerful tool in React that allows you to manage these side effects in function components.</p>
<h2 id="heading-what-is-useeffect-hook">What is useEffect hook?</h2>
<p><code>useEffect</code> is a built-in React hook that lets you "hook into" the component lifecycle. It's a way to tell React to run a function after every render, or after a specific state or prop has changed. Think of it as a function that performs actions that are "outside" the normal flow of rendering a component.</p>
<p>It takes two arguments:</p>
<ul>
<li><p>a function containing the side effect code and</p>
</li>
<li><p>an optional <strong>dependency array</strong>.</p>
</li>
</ul>
<p>The basic syntax looks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// Your side effect code goes here</span>
}, [dependencyArray]);
</code></pre>
<p>By employing useEffect you are signaling to React that your component needs to execute specific actions after rendering. React keeps track of the function you supply (our effects) and runs it following the DOM updates.</p>
<p>This feature allows you to execute various operations such as updating the document title, fetching data, or making API calls.</p>
<h3 id="heading-when-and-where-to-use-it">When and Where to Use It</h3>
<p>The <code>useEffect</code> hook is used for any kind of side effect. Common use cases include:</p>
<ul>
<li><p><strong>Data Fetching:</strong> Making an API call to get data and then storing it in state.</p>
</li>
<li><p><strong>Subscriptions:</strong> Setting up a subscription to an external service, like a WebSocket.</p>
</li>
<li><p><strong>Manually Interacting with the DOM:</strong> Directly manipulating the document, for example, to set the title of the page.</p>
</li>
<li><p><strong>Timers:</strong> Setting up and clearing timers, such as <code>setTimeout</code> or <code>setInterval</code>.</p>
</li>
</ul>
<h3 id="heading-the-dependency-array-controlling-the-effects-behavior">The Dependency Array: Controlling the Effect's Behavior</h3>
<p>The second argument to <code>useEffect</code>, the <strong>dependency array</strong>, is crucial for controlling when your effect runs. The effect will re-run only when a value in this array changes. This prevents the effect from running on every single render, which can lead to performance issues or infinite loops.</p>
<h4 id="heading-1-no-dependency-array">1. No Dependency Array</h4>
<p>If you omit the dependency array, the effect will run after every single render of the component.</p>
<pre><code class="lang-javascript">useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// This will run after every render</span>
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Component rendered or state updated'</span>);
});
</code></pre>
<p>This is generally not recommended for performance-sensitive operations like data fetching, as it will cause a new request on every render.</p>
<h4 id="heading-2-empty-dependency-array">2. Empty Dependency Array (<code>[]</code>)</h4>
<p>An empty dependency array tells React that the effect should only run <strong>once</strong>, after the initial render of the component. This is the ideal use case for one-time setup effects, like an initial API call.</p>
<pre><code class="lang-javascript">useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// This will only run once, on component mount</span>
  fetch(<span class="hljs-string">'https://api.example.com/data'</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
}, []);
</code></pre>
<h4 id="heading-3-populated-dependency-array-prop1-state1">3. Populated Dependency Array (<code>[prop1, state1]</code>)</h4>
<p>When you include variables (props or state) in the dependency array, the effect will re-run whenever any of those variables change. This is perfect for effects that depend on specific values.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [userId, setUserId] = useState(<span class="hljs-number">1</span>);
<span class="hljs-keyword">const</span> [userData, setUserData] = useState(<span class="hljs-literal">null</span>);

useEffect(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-comment">// This will re-run whenever userId changes</span>
  fetch(<span class="hljs-string">`https://api.example.com/users/<span class="hljs-subst">${userId}</span>`</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> setUserData(data));
}, [userId]);
</code></pre>
<p>In this example, the effect will fetch new user data only when the <code>userId</code> state variable is updated, not on every render.</p>
<h3 id="heading-the-cleanup-function">The Cleanup Function</h3>
<p>Some side effects, like subscriptions or timers, need to be "cleaned up" to prevent memory leaks. The <code>useEffect</code> hook provides a way to do this by allowing you to return a function from your effect callback. This returned function is the <strong>cleanup function</strong>.</p>
<p>React will run the cleanup function in two scenarios:</p>
<ol>
<li><p>Just before the effect re-runs due to a dependency change.</p>
</li>
<li><p>When the component is unmounted (removed from the DOM).</p>
</li>
</ol>
<p>Here's an example of using a cleanup function to unsubscribe from a service.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useEffect } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;
<span class="hljs-keyword">import</span> ChatAPI <span class="hljs-keyword">from</span> <span class="hljs-string">'./ChatAPI'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">ChatRoom</span>(<span class="hljs-params">{ roomId }</span>) </span>{
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-comment">// This function sets up the subscription</span>
    ChatAPI.subscribeToChat(roomId);

    <span class="hljs-comment">// This function is the cleanup function</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> {
      ChatAPI.unsubscribeFromChat(roomId);
    };
  }, [roomId]); <span class="hljs-comment">// Re-subscribe if the roomId changes</span>

  <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Welcome to the chat room!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
}
</code></pre>
<p>In this code, the <code>ChatAPI.subscribeToChat</code> function is called when the component mounts and whenever the <code>roomId</code> prop changes. The function returned from <code>useEffect</code> will then unsubscribe from the previous chat before the new subscription is set up, and also when the <code>ChatRoom</code> component unmounts. This is a crucial pattern for managing external resources in your React components.</p>
<p>Points to Remember:</p>
<ul>
<li><p>Use the cleanup function to free up the resources and for cleanups related to the effects.</p>
</li>
<li><p>The cleanup function runs before the component unmounts and before the effect re-run due to dependency change.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>The useEffect hook in React is powerful feature for managing the side effects in functional components. It’s ability to handle post render actions, combined with a customizable dependency array and cleanup mechanism, make it an essential for efficient and effective React development.</p>
<p>Thankyou for reading! Connect with me on <a target="_blank" href="https://x.com/abhishekkr_ssh"><strong>X/Twitter</strong></a> <em>or</em> <a target="_blank" href="https://linkedin.com/in/abhishekkr-dev"><strong>Linkedin</strong></a> 🙌</p>
]]></content:encoded></item><item><title><![CDATA[React’s useState Hook: The What, When, and Where of State Management]]></title><description><![CDATA[The UseState hook in React is fundamental tool that allows you to add state to functional components. It enables components to manage and update state in response to user input, events, or other interactions.
What is useState Hook?
The useState hook ...]]></description><link>https://abvs.hashnode.dev/reacts-usestate-hook-the-what-when-and-where-of-state-management</link><guid isPermaLink="true">https://abvs.hashnode.dev/reacts-usestate-hook-the-what-when-and-where-of-state-management</guid><category><![CDATA[React]]></category><category><![CDATA[useState]]></category><category><![CDATA[hooks]]></category><category><![CDATA[js]]></category><category><![CDATA[State Management ]]></category><category><![CDATA[react hooks]]></category><dc:creator><![CDATA[Abhishek Kumar]]></dc:creator><pubDate>Mon, 21 Oct 2024 10:11:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1729506083785/8edbdb43-b64f-4743-abb0-1de4e105d858.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The UseState hook in React is fundamental tool that allows you to add state to functional components. It enables components to manage and update state in response to user input, events, or other interactions.</p>
<h3 id="heading-what-is-usestate-hook">What is useState Hook?</h3>
<p>The <code>useState</code> hook provides a way to manage local state in functional component. It returns two values:</p>
<ul>
<li><p>The current state and a function that updates the state.</p>
</li>
<li><p>The State can be of any type, such as numbers, strings, arrays, or objects.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [state, setState] = useState(initialValue);
</code></pre>
<ul>
<li><p>state: the current state value</p>
</li>
<li><p><code>setState</code>: A function that updates the state.</p>
</li>
<li><p>initialValue: The initial value of the state ( can be any data type).</p>
</li>
<li><p>Example:</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Counter</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>); <span class="hljs-comment">// count starts at 0</span>

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Current Count: {count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>In the above example, the <code>count</code> variable holds the current state, and setCount is used to update the state when the button is clicked.</p>
<h3 id="heading-when-to-use-usestate">When to Use useState?</h3>
<p>You should use <code>useState</code> when you need to :</p>
<ol>
<li><p><strong>Track Local State</strong>: If your component needs to manage a piece of state that is independent of the rest of the application, such as form inputs, toggles, counter, etc.</p>
</li>
<li><p><strong>Handle User Interactions</strong>: When you need to update the UI based on user interactions (e.g., button clicks, types, etc.). It allows you to store the user’s input or response and reflect those changes in the component.</p>
</li>
<li><p><strong>Simple State Management</strong>: For small, self-contained state logic that doesn’t need to be shared across multiple components. For example, handling the visibility of a modal, toggling a dropdown, or switching between themes.</p>
</li>
<li><p><strong>Component-specific state</strong>: When the state only concerns a single component and is not required globally or across multiple components.</p>
</li>
</ol>
<p>Here comes the best part, we should always be careful and known about when should we avoid the use of <code>useState</code>.</p>
<h3 id="heading-where-to-avoid-using-usestate"><strong>Where to Avoid using</strong> <code>useState</code>?</h3>
<p>While useState is powerful, there are cases where you should avoid using it:</p>
<ol>
<li><p>Complex or Shared State:</p>
<p> <strong>When state needs to be shared across multiple components</strong>: If your application has a state that needs to be accessed or modified by multiple components (e.g., <em>user authentication state or theme settings</em>), using useState in each component can lead to redundant or difficult-to-manage state. In such cases, consider using context (<code>useContext</code>) or a state management solution like Redux.</p>
<p> <strong>For deeply nested state</strong>: If the state becomes complex, such as managing an object with many nested properties, managing updates with <code>useState</code> can become cumbersome. Using <code>useReducer</code> might be a better alternative in such cases.</p>
<p> Example with <code>useReducer</code> :</p>
</li>
</ol>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> initialState = { <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> };

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">reducer</span>(<span class="hljs-params">state, action</span>) </span>{
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> <span class="hljs-string">'increment'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count + <span class="hljs-number">1</span> };
    <span class="hljs-keyword">case</span> <span class="hljs-string">'decrement'</span>:
      <span class="hljs-keyword">return</span> { <span class="hljs-attr">count</span>: state.count - <span class="hljs-number">1</span> };
    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">return</span> state;
  }
}

<span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, initialState);
</code></pre>
<ol start="2">
<li><p><strong>Global State Management</strong>:</p>
<p> If you have data that needs to accessed throughout your application(e.g., <em>user authentication status, theme, language preferences</em>), it’s better to avoid useState in individual components and instead use global state solutions like <strong>Context API</strong> or external libraries like Redux and Zustand.</p>
</li>
<li><p><strong>Side Effects or Asynchronous Logic</strong>:</p>
<p> If your state management involves side effects like fetching data from an API or interacting with external systems, it’s better to use <code>useEffect</code> in combination with <code>useState</code> rather than relying on <code>useState</code> alone.</p>
</li>
<li><p><strong>Performance concerns with Frequent Updates</strong>:</p>
<p> If you have frequent updates (such as animations or real-time data), using useState might cause unnecessary re-renders and impact performance. In such cases, tools like Ref (<code>useRef</code>) can be more effiecient as it doesn’t trigger re-renders.</p>
</li>
</ol>
<h3 id="heading-best-practices-with-usestate">Best Practices with <code>useState</code></h3>
<ul>
<li><p><strong>Avoid Excessive Re-renders:</strong> Each time setState is called, the component re-renders. Try to minimize state changes to only what’s necessary.</p>
</li>
<li><p><strong>Batch Updates</strong>: React batches updates made in event handlers. So, multiple setState calls within the same handler will trigger only one re-render.</p>
</li>
<li><p>Functional Updates: If you state update depends on the previous state, it’s better to use the functional form of <code>setState</code>.</p>
</li>
</ul>
<pre><code class="lang-javascript">setCount(<span class="hljs-function"><span class="hljs-params">prevCount</span> =&gt;</span> prevCount + <span class="hljs-number">1</span>);
</code></pre>
<hr />
<h3 id="heading-summary">Summary</h3>
<p><strong>When to use</strong> <code>useState</code>:</p>
<ul>
<li><p>Managing local state in functional components.</p>
</li>
<li><p>Handling user input and UI interactions.</p>
</li>
<li><p>Managing simple state logic within a single component.</p>
</li>
</ul>
<p><strong>When to avoid using</strong> <code>useState</code></p>
<ul>
<li><p>When dealing with global state or shared data across multiple components.</p>
</li>
<li><p>When the state logic becomes too complex or deeply nested.</p>
</li>
<li><p>When performance might be affected by frequent re-renders (e.g., real-time updates).</p>
</li>
<li><p>When handling asynchronous or side effects alone ( should be paired with <code>useEffect</code>).</p>
</li>
</ul>
<p>Thankyou for reading! connect with me on <a target="_blank" href="https://x.com/abhissh_">X/Twitter</a> 🙌</p>
]]></content:encoded></item></channel></rss>