<?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 Sushil Kumar on Medium]]></title>
        <description><![CDATA[Stories by Sushil Kumar on Medium]]></description>
        <link>https://medium.com/@sushilkumar_34124?source=rss-6b0c481e2ba8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Nnb_ijPanL1u5XaQ.</url>
            <title>Stories by Sushil Kumar on Medium</title>
            <link>https://medium.com/@sushilkumar_34124?source=rss-6b0c481e2ba8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:28:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sushilkumar_34124/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[useState Hook in React]]></title>
            <link>https://medium.com/@sushilkumar_34124/usestate-hook-in-react-49f2decffbbe?source=rss-6b0c481e2ba8------2</link>
            <guid isPermaLink="false">https://medium.com/p/49f2decffbbe</guid>
            <dc:creator><![CDATA[Sushil Kumar]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 07:33:49 GMT</pubDate>
            <atom:updated>2024-07-24T07:41:23.814Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>React provides various hooks that are used to manage a component’s state and lifecycle in your application effectively. The useState hook is one of the most frequently used hooks in React. This hook brings in state functionality in functional components, allowing you to manage and update the state within the component.</p><h3>Initializing State</h3><p>The useState hook takes an initial state as its argument and returns a pair—an array with two elements. The first element is the current state value, and the second is a function that lets you update it. Here&#39;s an example of how to use useState:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Click me<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default Counter;</pre><p>In this example, the useState hook is called with the initial state of 0. The return value of useState is count (the current state) and setCount (the function to update the state).</p><h3>Updating State</h3><p>The function returned by useState (in our case, setCount) is used to update the state whenever necessary.</p><p>Unlike this.setState in class components, the state update function from useState doesn’t merge the old and new state together. Therefore, it replaces the old state with the new one entirely.</p><pre>const [user, setUser] = useState({ name: &#39;John&#39;, age: 30 });<br>setUser({ name: &#39;Kate&#39; });</pre><p>In the code above, setUser doesn&#39;t merge the old and new states together. So, the user&#39;s age is lost and is not a part of the new state. To fix this, you&#39;d have to spread over the previous state while updating:</p><pre>setUser(prevState =&gt; ({ ...prevState, name: &#39;Kate&#39; }));</pre><h3>Async State Updates</h3><p>State updates may not immediately reflect due to their async nature. Given the following:</p><pre>const [count, setCount] = useState(0);<br>for (let i = 0; i &lt; 5; i++) {<br>  setCount(count =&gt; count + 1);<br>}</pre><p>You’re anticipating the count to be incremented 5 times, but due to async nature, all updates may consolidate into a single render with the value of count being incremented once.</p><h3>Using useState with Complex Objects and Arrays</h3><p>When using useState with an array or an object, the set function will replace the entire object or array. This behaviour can lead to unexpected results that can be avoided by creating a new array or object that includes all the previous elements and the new ones.</p><p>Let’s take an array example:</p><pre>const [items, setItems] = useState([&#39;Apple&#39;, &#39;Orange&#39;, &#39;Mango&#39;]);<br>const addItem = (item) =&gt; {<br>  setItems([...items, item]);<br>}</pre><p>Here, we essentially created a new array that includes all the previous items and the new item.</p><h3>Lazy Initialization</h3><p>If the initial state is the result of an expensive computation, you can provide a function to useState that returns the initial state value. This function will only run on the initial render, which can be beneficial for performance.</p><pre>const [value, setValue] = useState(() =&gt; {<br>  const expensiveValue = computeExpensiveValue();<br>  return expensiveValue;<br>});</pre><h3>Component Re-render</h3><p>Finally, re-rendering does not occur when calling a setState function if the new state value is the same as the current one.</p><pre>const [count, setCount] = useState(0);<br>setCount(0);</pre><p>In this case, the component doesn’t re-render since the new state value (0) is the same as the current one.</p><h3>Conclusion</h3><p>Understanding these nuances of the useState hook will help you write efficient and cleaner code in your React applications. While it’s easy to use and simplifies the state management process, knowing how useState handles merging of states and asynchronous state updates is vital in avoiding any surprises in your functional components. By mastering these nuances and effectively using the useState hook, you can undoubtedly write more efficient and cleaner code in your React applications, enhancing your application’s overall performance and user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49f2decffbbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>