<?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 Kiran Ahir on Medium]]></title>
        <description><![CDATA[Stories by Kiran Ahir on Medium]]></description>
        <link>https://medium.com/@kiranahir?source=rss-fdfc3eef0309------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*s-tOszooEk5kVl_g.png</url>
            <title>Stories by Kiran Ahir on Medium</title>
            <link>https://medium.com/@kiranahir?source=rss-fdfc3eef0309------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 19 May 2026 13:10:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kiranahir/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[Throttling in Javascript]]></title>
            <link>https://medium.com/@kiranahir/throttling-in-javascript-64e03bf3a6f8?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e03bf3a6f8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[throttling]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Fri, 30 Dec 2022 08:13:11 GMT</pubDate>
            <atom:updated>2022-12-30T08:13:11.173Z</atom:updated>
            <content:encoded><![CDATA[<p>In JavaScript, throttling is a technique for limiting the rate at which a function is called or executed. It is often used to limit the number of times an event handler is called in response to a user action, such as a mouse click or key press, in order to prevent the function from being called too frequently and potentially causing performance issues or other problems.</p><p>To implement throttling, you can use a timer or counter to track the number of times the function has been called within a certain period of time, and only allow the function to be called if a certain amount of time has passed since the last call. This can be done using the setTimeout or setInterval functions in JavaScript, or by using a library or utility function that provides throttling functionality.</p><p>Here is an example of how you might use the setTimeout function to throttle a function in JavaScript:</p><pre>function throttle(callback, limit) {<br>  let wait = false;<br>  return function() {<br>    if (!wait) {<br>      callback.apply(null, arguments);<br>      wait = true;<br>      setTimeout(function() {<br>        wait = false;<br>      }, limit);<br>    }<br>  }<br>}<br><br>const throttledFunction = throttle(function() {<br>  console.log(&#39;This function is being throttled.&#39;);<br>}, 1000);<br><br>// The function will only be called once per second at most.<br>throttledFunction();<br>throttledFunction();<br>throttledFunction();</pre><p>In this example, the throttle function takes a callback function and a limit (in milliseconds) as arguments, and returns a new function that will only allow the callback to be called once every limit milliseconds. When the throttled function is called, it checks a flag called wait to see if the callback has already been called within the specified time limit. If the callback has not been called, it is executed and the wait flag is set to true. If the callback has already been called within the time limit, it is not executed and the wait flag remains true. The wait flag is reset to false after the time limit has passed, allowing the callback to be called again.</p><p>Here are a few examples of how throttling might be used in a real-life JavaScript application:</p><ol><li>Limiting the rate at which an AJAX request is sent to a server in response to a user action, such as typing in a search field or scrolling through a page. This can help prevent the server from being overloaded with too many requests in a short period of time.</li><li>Throttling the rate at which a scroll event handler is called when the user scrolls through a page. This can help improve the performance of the page by limiting the number of times the event handler is called, which can be particularly important for pages with complex layouts or large amounts of data.</li><li>Throttling the rate at which a function is called when the user resizes their browser window. This can help prevent the function from being called too frequently, which can cause performance issues or other problems.</li><li>Throttling the rate at which a function is called when the user mouses over a series of elements on a page. This can help prevent the function from being called too frequently, which can cause performance issues or other problems.</li><li>Throttling the rate at which a function is called when the user interacts with a form or other input element on a page. This can help prevent the function from being called too frequently, which can cause performance issues or other problems.</li></ol><p>Happy programming! Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e03bf3a6f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Debouncing? Explained using Javascript]]></title>
            <link>https://medium.com/@kiranahir/what-is-debouncing-explained-using-javascript-3b9f1438832c?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b9f1438832c</guid>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 15:29:37 GMT</pubDate>
            <atom:updated>2022-12-29T15:29:37.519Z</atom:updated>
            <content:encoded><![CDATA[<p>Debouncing is a technique used to limit the rate at which a function gets executed. It is often used to improve the performance and user experience of a web application by reducing the number of times a particular function gets called.</p><p>Here is an example of how debouncing could be implemented in JavaScript:</p><pre>function debounce(func, delay) {<br>  let timeout;<br><br>  return function() {<br>    const context = this;<br>    const args = arguments;<br><br>    clearTimeout(timeout);<br><br>    timeout = setTimeout(() =&gt; {<br>      func.apply(context, args);<br>    }, delay);<br>  };<br>}</pre><p>To use the debounce function, you would pass in the function you want to debounce as the first argument, and the delay (in milliseconds) as the second argument. The debounce function returns a new function that can be called instead of the original function. When the new function is called, it will delay the execution of the original function by the specified delay. If the new function is called again before the delay has passed, the timer is reset, and the delay starts over.</p><p>Here is an example of how the debounce function could be used to debounce a search function:</p><pre>const searchInput = document.getElementById(&#39;search-input&#39;);<br><br>const debouncedSearch = debounce(search, 500);<br><br>searchInput.addEventListener(&#39;input&#39;, debouncedSearch);</pre><p>In this example, the debouncedSearch function will be called every time the user types a character into the search input. However, the search function will only be executed after the user has stopped typing for 500 milliseconds. This can help to reduce the number of search requests that are sent to the server and improve the performance of the application.</p><p>Here are a few examples of how debouncing can be used in real-life applications:</p><ol><li>Search functionality: As mentioned in the previous example, debouncing can be used to improve the performance of a search function by limiting the number of requests that are sent to the server. This can be especially helpful if the search function is being called on every keystroke, as it can prevent the server from being overloaded with requests.</li><li>Autosave functionality: Debouncing can be used to limit the rate at which an autosave function gets executed. For example, if an autosave function is triggered every time the user makes a change to a document, debouncing can be used to ensure that the function is only executed once the user has stopped making changes for a certain period of time. This can help to reduce the number of writes to the database and improve the performance of the application.</li><li>Scroll event handling: Debouncing can be used to improve the performance of an application that uses the scroll event to trigger some kind of action, such as loading new content or tracking the user’s scroll position. Without debouncing, the scroll event can be triggered hundreds of times per second, which can cause performance issues. By debouncing the scroll event, the function that is triggered by the event will only be executed once the user has stopped scrolling for a certain period of time.</li><li>Resizing event handling: Similar to the scroll event, the resize event can also be debounced to improve the performance of an application. For example, if an application has to adjust the layout of elements on the page when the window is resized, debouncing the resize event can prevent the layout from being recalculated hundreds of times per second, which can cause performance issues.</li></ol><p>Let me know if you find any other real life use cases.</p><p>Please follow/like/share if you liked the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b9f1438832c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Specificity in CSS]]></title>
            <link>https://medium.com/@kiranahir/specificity-in-css-a30fa6f2d00b?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/a30fa6f2d00b</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css3]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 11:02:06 GMT</pubDate>
            <atom:updated>2022-12-29T11:02:06.288Z</atom:updated>
            <content:encoded><![CDATA[<p>In CSS, specificity refers to the rules that determine which style declarations should be applied to an element. When there are multiple style declarations that apply to the same element, the browser must decide which declarations to follow.</p><p>Specificity is calculated based on the number of each type of selector used in the rule. There are three types of selectors:</p><ol><li>Inline styles (e.g. style=&quot;&quot;) have the highest specificity and will always be applied, unless overruled by important rules.</li><li>IDs have a higher specificity than classes, attributes, and pseudo-classes, but lower than inline styles.</li><li>Classes, attributes, and pseudo-classes (e.g. :hover) have a lower specificity than IDs, but higher than elements.</li></ol><p>For example, consider the following CSS rule:</p><pre>#header .nav li a {<br>  color: red;<br>}</pre><p>This rule has a specificity of 0,1,1,1 because it uses one ID, one class, and two elements.</p><p>If there is a conflict between two rules, the rule with the higher specificity will be applied. If the specificity is the same, the rule that appears later in the stylesheet will be applied.</p><p>You can use the !important keyword to override the specificity of a rule and force it to be applied. However, it is generally considered a best practice to avoid using !important wherever possible, as it can make your stylesheets difficult to maintain.</p><p>Here are a few more advanced examples of CSS rules and their specificity:</p><p>To style all p elements that are descendants of a div with the class .container:</p><pre>div.container p {<br>  font-size: 18px;<br>}</pre><p>This rule has a specificity of 0,1,0,1 because it uses one class and one element.</p><p>To style all a elements that are descendants of li elements, which are themselves descendants of a ul element:</p><pre>ul li a {<br>  color: blue;<br>}</pre><p>This rule has a specificity of 0,0,2,0 because it uses two elements.</p><p>To style all a elements with the attribute [href=&quot;#&quot;]:</p><pre>a[href=&quot;#&quot;] {<br>  text-decoration: none;<br>}</pre><p>This rule has a specificity of 0,0,1,0 because it uses one attribute.</p><p>To style all p elements with the class .warning that are inside a div element with the ID #important:</p><pre>div#important p.warning {<br>  color: red;<br>}</pre><p>This rule has a specificity of 0,2,0,1 because it uses one ID and one class.</p><p>To style all a elements that are being hovered over:</p><pre>a:hover {<br>  color: green;<br>}</pre><p>This rule has a specificity of 0,0,1,0 because it uses one pseudo-class.</p><p>In summary, specificity in CSS determines which style declarations should be applied to an element when there are multiple conflicting declarations. Specificity is calculated based on the number of each type of selector used in a rule, with inline styles having the highest specificity and elements having the lowest. If there is a conflict between two rules, the one with the higher specificity will be applied. If the specificity is the same, the rule that appears later in the stylesheet will be applied. You can use the !important keyword to override the specificity of a rule and force it to be applied, but it is generally considered a best practice to avoid using !important whenever possible.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a30fa6f2d00b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[async await explained — Javascript]]></title>
            <link>https://medium.com/@kiranahir/async-await-explained-javascript-3e96a9d568ae?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e96a9d568ae</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[advanced-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 10:00:33 GMT</pubDate>
            <atom:updated>2022-12-29T10:00:33.739Z</atom:updated>
            <content:encoded><![CDATA[<h3>async await explained — Javascript</h3><p>In JavaScript, async and await are two keywords that can be used in combination to perform asynchronous operations.</p><p>The async keyword is used to declare an asynchronous function, which is a function that returns a Promise and can be used with the await keyword inside.</p><p>Here’s an example of an asynchronous function:</p><pre>async function getData() {<br>  try {<br>    const response = await fetch(&#39;https://api.example.com/data&#39;);<br>    const data = await response.json();<br>    return data;<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}</pre><p>In this example, the getData function uses the fetch function to make a request to an API and retrieve some data. The await keyword is used to wait for the response to be received before processing the data.</p><p>The await keyword can only be used inside an async function. It causes the JavaScript runtime to pause execution of the async function until the awaited Promise is resolved.</p><p>Once the Promise is resolved, the async function continues execution and returns the resolved value. If the Promise is rejected, the async function throws an error.</p><p>Here’s an example of how you can use the getData function:</p><pre>getData()<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>The async and await keywords make it easier to work with asynchronous code in JavaScript, by allowing you to write code that looks and behaves like synchronous code. This can make your code easier to read and understand.</p><p>Here are a few more examples of using async and await in JavaScript:</p><p>Example 1:</p><pre>async function getUser() {<br>  const response = await fetch(&#39;https://api.example.com/users/123&#39;);<br>  const user = await response.json();<br>  return user;<br>}<br><br>getUser()<br>  .then(user =&gt; console.log(user))<br>  .catch(error =&gt; console.error(error));</pre><p>In this example, the getUser function makes a request to an API to retrieve a user with a specific ID, and then returns the user data as a JavaScript object.</p><p>Example 2:</p><pre>async function login(email, password) {<br>  const response = await fetch(&#39;https://api.example.com/login&#39;, {<br>    method: &#39;POST&#39;,<br>    body: JSON.stringify({ email, password }),<br>    headers: { &#39;Content-Type&#39;: &#39;application/json&#39; },<br>  });<br>  const data = await response.json();<br>  if (data.error) {<br>    throw new Error(data.error);<br>  }<br>  return data;<br>}<br><br>login(&#39;user@example.com&#39;, &#39;password&#39;)<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>In this example, the login function sends a POST request to an API with a user&#39;s email and password, and then returns the API&#39;s response. If the response includes an error, the function throws an error.</p><p>Example 3:</p><pre>async function getUsers() {<br>  const response = await fetch(&#39;https://api.example.com/users&#39;);<br>  const users = await response.json();<br>  return users;<br>}<br><br>async function main() {<br>  try {<br>    const users = await getUsers();<br>    console.log(users);<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>main();</pre><p>In this example, the getUsers function makes a request to an API to retrieve a list of users, and then returns the list of users. The main function calls the getUsers function and logs the returned list of users to the console. If the getUsers function throws an error, it is caught by the catch block in the main function.</p><p>There are a few things to keep in mind when using async and await in JavaScript:</p><ol><li>await can only be used inside an async function. If you try to use it outside of an async function, you&#39;ll get a syntax error.</li><li>The value returned by an async function is always a Promise, even if you use the return keyword to return a value. This means that you&#39;ll need to use the then method to access the resolved value of the Promise.</li><li>If an async function throws an error, the Promise returned by the function will be rejected. You&#39;ll need to use the catch method to handle the rejected Promise.</li><li>await blocks the execution of the async function until the awaited Promise is resolved. This means that if you have multiple await statements in a row, each one will be executed in sequence, and the async function will not continue until all of the Promises have been resolved.</li><li>If you need to perform multiple asynchronous operations in parallel, you can use the Promise.all function to wait for all of the Promises to be resolved before continuing.</li></ol><p>You might want to use async and await instead of Promises in JavaScript if you want to write asynchronous code that is easier to read and understand.</p><p>Promises are a powerful tool for handling asynchronous operations in JavaScript, but they can be a bit difficult to work with at times, especially if you have a lot of nested Promises or complex error handling logic.</p><p>async and await provide a way to write asynchronous code that looks and behaves more like synchronous code. This can make your code easier to read and understand, especially if you&#39;re new to asynchronous programming.</p><p>For example, consider the following code that uses Promises:</p><pre>function getData() {<br>  return fetch(&#39;https://api.example.com/data&#39;)<br>    .then(response =&gt; response.json())<br>    .catch(error =&gt; console.error(error));<br>}<br><br>getData()<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>Here’s the same code written using async and await:</p><pre>async function getData() {<br>  try {<br>    const response = await fetch(&#39;https://api.example.com/data&#39;);<br>    const data = await response.json();<br>    return data;<br>  } catch (error) {<br>    console.error(error);<br>  }<br>}<br><br>getData()<br>  .then(data =&gt; console.log(data))<br>  .catch(error =&gt; console.error(error));</pre><p>In this example, the async and await version of the code is arguably easier to read and understand, because it looks more like synchronous code.</p><p>That being said, you should use the approach that makes the most sense for your specific use case. Both Promises and async/await have their own strengths and weaknesses, and there isn&#39;t always a clear &quot;right&quot; or &quot;wrong&quot; choice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e96a9d568ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS — Components LifeCycle methods]]></title>
            <link>https://medium.com/@kiranahir/reactjs-components-lifecycle-methods-4acde260fb66?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/4acde260fb66</guid>
            <category><![CDATA[lifecycle-methods]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 09:30:25 GMT</pubDate>
            <atom:updated>2022-12-29T09:40:33.250Z</atom:updated>
            <content:encoded><![CDATA[<h3>React Components life cycle methods</h3><p>React components have a lifecycle of events that they go through from the time they are created until they are destroyed. These lifecycle events allow developers to hook into the lifecycle of a component at various points and perform certain actions.</p><p>Here are the main lifecycle methods of a React component, along with a brief explanation of each and an example of how they might be used:</p><p>constructor(): This method is called before a component is mounted (inserted into the DOM). It is used to initialize state and bind event handlers.</p><p>Example:</p><pre>constructor(props) {<br>  super(props);<br>  this.state = { count: 0 };<br>  this.handleClick = this.handleClick.bind(this);<br>}</pre><p>componentDidMount(): This method is called after a component is mounted (inserted into the DOM). It is often used to trigger an action or API call once the component has been rendered.</p><p>Example:</p><pre>componentDidMount() {<br>  axios.get(&#39;/items&#39;)<br>    .then(response =&gt; this.setState({ items: response.data }));<br>}</pre><p>shouldComponentUpdate(): This method is called before a component is re-rendered in response to a state or prop change. It allows the developer to return a boolean value indicating whether the component should be updated or not. This can be used to optimize performance by avoiding unnecessary re-renders.</p><p>Example:</p><pre>shouldComponentUpdate(nextProps, nextState) {<br>  return nextState.count !== this.state.count;<br>}</pre><p>componentDidUpdate(): This method is called after a component is updated (re-rendered). It is often used to trigger an action or API call after the component has been updated.</p><p>Example:</p><pre>componentDidUpdate(prevProps, prevState) {<br>  if (prevState.count !== this.state.count) {<br>    axios.post(&#39;/update-count&#39;, { count: this.state.count });<br>  }<br>}</pre><p>componentWillUnmount(): This method is called just before a component is destroyed (removed from the DOM). It is often used to clean up any resources or event listeners that the component has created.</p><p>Example:</p><pre>componentWillUnmount() {<br>  window.removeEventListener(&#39;resize&#39;, this.handleResize);<br>}</pre><p>render(): This method is called to render the JSX for a component. It must be present in every React component and should not contain side effects or trigger API calls.</p><pre>render() {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello, World!&lt;/h1&gt;<br>      &lt;button onClick={this.handleClick}&gt;Click me&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In addition to these lifecycle methods, there are also a few deprecated lifecycle methods that are no longer recommended for use in modern React applications: componentWillMount(), componentWillReceiveProps(), and componentWillUpdate(). These methods have been replaced by newer alternatives that provide better performance and are easier to work with.</p><p>Here is a summary of the main React component lifecycle methods:</p><ul><li>constructor(): Initializes state and binds event handlers. Called before a component is mounted.</li><li>componentDidMount(): Triggers an action or API call once the component is rendered. Called after a component is mounted.</li><li>shouldComponentUpdate(): Returns a boolean indicating whether the component should be updated or not. Called before a component is re-rendered.</li><li>componentDidUpdate(): Triggers an action or API call after the component is updated. Called after a component is updated.</li><li>componentWillUnmount(): Cleans up resources or event listeners. Called just before a component is destroyed.</li><li>render(): Renders the JSX for a component. Called whenever the component needs to be re-rendered.</li></ul><p>These lifecycle methods allow developers to hook into the lifecycle of a component and perform certain actions at various points in the process. They can be used to optimize performance, trigger actions or API calls, and clean up resources.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4acde260fb66" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hoisting in Javascript explained in simple terms]]></title>
            <link>https://medium.com/@kiranahir/hoisting-in-javascript-explained-in-simple-terms-665bbea01c1?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/665bbea01c1</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[advanced-javascript]]></category>
            <category><![CDATA[javascript-hoisting]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 09:18:12 GMT</pubDate>
            <atom:updated>2022-12-29T09:21:50.955Z</atom:updated>
            <content:encoded><![CDATA[<p>In JavaScript, hoisting is a behavior of the interpreter that occurs when it moves declarations to the top of the current scope. This means that declarations of variables and functions are processed before any code is executed.</p><p>Here’s an example to illustrate hoisting:</p><pre>console.log(x);  // Output: undefined<br>var x = 5;<br><br>console.log(y);  // Output: ReferenceError: y is not defined<br>let y = 10;</pre><p>In the example above, the first console.log statement logs undefined because the variable x is hoisted to the top of the current scope (in this case, the global scope). However, the let keyword is block-scoped, meaning that the variable y is not hoisted to the top of the current scope. As a result, the second console.log statement throws a ReferenceError because y is not defined.</p><p>It’s important to note that hoisting only affects declarations, not assignments. In the example above, the value of x is not hoisted, only the declaration of the variable x. This means that the value of x is still undefined when the first console.log statement is executed.</p><p>Hoisting can be a source of confusion in JavaScript because it can lead to unexpected behavior if you are not aware of it. It’s generally a good idea to always declare variables at the top of your code to avoid any confusion or unexpected behavior.</p><p>Here are a few examples that may be confusing due to hoisting:</p><pre>console.log(x);  // Output: undefined<br>var x = 5;</pre><p>In this example, the variable x is declared after the console.log statement, but it is hoisted to the top of the current scope. As a result, the console.log statement logs undefined instead of throwing a ReferenceError.</p><pre>function test() {<br>  console.log(a);  // Output: undefined<br>  console.log(b);  // Output: ReferenceError: b is not defined<br>  var a = 10;<br>  let b = 20;<br>}<br>test();</pre><p>In this example, the variables a and b are both declared inside the test function. However, a is declared using the var keyword, which is hoisted to the top of the function, while b is declared using the let keyword, which is not hoisted. As a result, the first console.log statement logs undefined, while the second console.log statement throws a ReferenceError.</p><pre>function test() {<br>  console.log(a);  // Output: 5<br>  console.log(b);  // Output: ReferenceError: b is not defined<br>  var a = 5;<br>  let b = 10;<br>}<br>var a = 1;<br>test();</pre><p>In this example, there is a global variable a and a local variable a inside the test function. The global variable a is assigned the value 1, and the local variable a is declared but not assigned a value. Because of hoisting, the local variable a is hoisted to the top of the test function, and the console.log statement logs 5. The variable b is declared using the let keyword, which is not hoisted, so the second console.log statement throws a ReferenceError.</p><pre>function test() {<br>  console.log(a);  // Output: 5<br>  var a = 5;<br>  console.log(a);  // Output: 5<br>}<br>test();</pre><p>In this example, the variable a is declared inside the test function and assigned the value 5. Because of hoisting, the declaration of a is moved to the top of the function, and the value of a is not initialized until the assignment statement is executed. As a result, both console.log statements log 5.</p><pre>function test() {<br>  console.log(a);  // Output: undefined<br>  console.log(b);  // Output: 20<br>  console.log(c);  // Output: ReferenceError: c is not defined<br>  var a = 5;<br>  let b = 10;<br>  b = 20;<br>  var c = 30;<br>}<br>test();</pre><p>In this example, the variables a, b, and c are all declared inside the test function. The variable a is declared using the var keyword and is hoisted to the top of the function, while b is declared using the let keyword and is not hoisted. The let keyword is block-scoped, so the assignment to b does not affect the hoisting behavior. The variable c is also declared using the var keyword and is hoisted to the top of the function. However, the console.log statement for c is executed before the declaration of c, so it throws a ReferenceError.</p><p>Hoisting is a behavior of the JavaScript interpreter that occurs when it processes declarations of variables and functions. Hoisting affects the way that your code is executed, and it can lead to unexpected behavior if you are not aware of it.</p><p>You can use hoisting in any JavaScript code that you write, but it’s generally a good idea to be aware of how it works and to structure your code in a way that avoids confusion or unexpected behavior.</p><p>One way to avoid confusion caused by hoisting is to always declare variables at the top of your code, before any other statements are executed. This makes it clear to anyone reading your code what variables are available and where they are declared.</p><p>It’s also a good idea to use the let and const keywords instead of the var keyword whenever possible. The let and const keywords are block-scoped, which means that they are not hoisted to the top of the current scope. This can make your code more predictable and easier to understand.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=665bbea01c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useState hook — ReactJS]]></title>
            <link>https://medium.com/@kiranahir/usestate-hook-reactjs-4e3d39a24bb4?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e3d39a24bb4</guid>
            <category><![CDATA[react-js-tutorials]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 05:57:39 GMT</pubDate>
            <atom:updated>2022-12-29T09:39:52.291Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is useState() hook in ReactJS</h3><p>The useState hook is a way to add state to functional components in React. It allows you to manage state inside a functional component and provides a way to update the state with the setState function.</p><p>Here’s an example of how to use useState:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Example() {<br>  // Declare a new state variable, which we&#39;ll call &quot;count&quot;<br>  const [count, setCount] = useState(0);<br><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>}</pre><p>In this example, we use the useState hook to add a piece of state called count to the functional component. The initial value of count is 0. We also get a function called setCount that we can use to update the value of count.</p><p>In the component’s render method, we display the current value of count and bind the setCount function to the onClick event of a button element. When the button is clicked, the setCount function is called with an updated value for count, which causes the component to re-render with the new value.</p><p>Here’s another example of using the useState hook in a functional component:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>function Form() {<br>  // Declare a new state variable, which we&#39;ll call &quot;name&quot;<br>  const [name, setName] = useState(&#39;&#39;);<br><br>  const handleChange = (event) =&gt; {<br>    setName(event.target.value);<br>  }<br><br>  const handleSubmit = (event) =&gt; {<br>    event.preventDefault();<br>    // Submit the form data to the server<br>  }<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;label&gt;<br>        Name:<br>        &lt;input type=&quot;text&quot; value={name} onChange={handleChange} /&gt;<br>      &lt;/label&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>}</pre><p>In this example, we use the useState hook to add a piece of state called name to the functional component. The initial value of name is an empty string. We also get a function called setName that we can use to update the value of name.</p><p>In the component’s render method, we render an input element that is bound to the name state variable using the value and onChange props. When the user types in the input field, the handleChange function is called, which updates the value of name using the setName function. When the form is submitted, the handleSubmit function is called, which prevents the default form submission behavior and could potentially submit the form data to the server.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e3d39a24bb4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useEffect hook — ReactJS]]></title>
            <link>https://medium.com/@kiranahir/useeffect-hook-reactjs-22c17c4a817a?source=rss-fdfc3eef0309------2</link>
            <guid isPermaLink="false">https://medium.com/p/22c17c4a817a</guid>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kiran Ahir]]></dc:creator>
            <pubDate>Thu, 29 Dec 2022 05:50:54 GMT</pubDate>
            <atom:updated>2022-12-29T09:39:06.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is useEffect() hook in ReactJS</h3><p>The useEffect hook is a function provided by the React library that allows you to perform side effects in function components. It is similar to the componentDidMount, componentDidUpdate, and componentWillUnmount lifecycle methods in class-based components.</p><p>The useEffect hook takes a function as an argument, which is called the &quot;effect&quot; function. This function is invoked after the component renders, and it can be used to perform tasks such as making API calls, setting up subscriptions, or updating the DOM. The effect function can also return a clean-up function, which is called before the component is unmounted or the effect is re-run.</p><p>Here is an example of how to use the useEffect hook to make an API call and update the component&#39;s state with the response:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br><br>function MyComponent() {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    async function fetchData() {<br>      const response = await fetch(&#39;https://example.com/api/data&#39;);<br>      const data = await response.json();<br>      setData(data);<br>    }<br>    fetchData();<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      {data ? &lt;p&gt;{data.message}&lt;/p&gt; : &lt;p&gt;Loading...&lt;/p&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>In this example, the useEffect hook is called with an empty array as the second argument. This tells React to only run the effect function once, when the component mounts. If the second argument is omitted or set to a non-empty array, the effect function will be re-run whenever one of the values in the array changes. This can be useful for performing tasks that depend on specific props or state values.</p><p>Here is another example of how you can use the useEffect hook to set up a subscription and clean it up when the component unmounts:</p><pre>import { useEffect, useState } from &#39;react&#39;;<br><br>function MyComponent() {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    const intervalId = setInterval(() =&gt; {<br>      setCount((prevCount) =&gt; prevCount + 1);<br>    }, 1000);<br>    return () =&gt; clearInterval(intervalId);<br>  }, []);<br><br>  return &lt;div&gt;Count: {count}&lt;/div&gt;;<br>}</pre><p>In this example, the useEffect hook is called with an empty array as the second argument, which means that the effect function will only be run once, when the component mounts. The effect function sets up an interval that increments the count state variable every second. It also returns a clean-up function that clears the interval when the component unmounts.</p><p>As a result, the component will display the current count, which will be incremented every second until the component is unmounted.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22c17c4a817a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>