<?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 Sergey Leschev on Medium]]></title>
        <description><![CDATA[Stories by Sergey Leschev on Medium]]></description>
        <link>https://medium.com/@sergeyleschev?source=rss-121dba2162b4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QKBayedLmUYhrryW_j5IXQ.png</url>
            <title>Stories by Sergey Leschev on Medium</title>
            <link>https://medium.com/@sergeyleschev?source=rss-121dba2162b4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:06:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergeyleschev/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[Tackling Memory Leaks in Node.js]]></title>
            <link>https://medium.com/@sergeyleschev/tackling-memory-leaks-in-node-js-fa7cf9112c56?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa7cf9112c56</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[memory-leak]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Sun, 09 Feb 2025 07:34:39 GMT</pubDate>
            <atom:updated>2025-02-13T11:22:15.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NhXP6841qoDnW2kYZvKXBQ.jpeg" /><figcaption>Tackling Memory Leaks in Node.js</figcaption></figure><p>Memory leaks in Node.js can be silent killers for your applications. They degrade performance, increase costs, and eventually lead to crashes. Let’s break down common causes and actionable strategies to prevent or fix them.</p><h3>1️⃣ References: The Hidden Culprits</h3><ul><li>Global Variables: Accidentally assigning objects to global variables (e.g., global.data = …) keeps them in memory forever.</li></ul><pre>// 🚨 Leak Example: Accidentally assigning to global scope  <br>function processUserData(user) {<br>  global.cachedUser = user; // Stored globally, never garbage-collected!<br>}</pre><p>Fix: Use modules or closures to encapsulate data:</p><pre>// ✅ Safe approach: Module-scoped cache  <br>const userCache = new Map();  <br>function processUserData(user) {<br>  userCache.set(user.id, user);<br>}</pre><ul><li>Multiple References: Unused objects retained by other references (e.g., caches, arrays).</li></ul><pre>// 🚨 Leak Example: Cached array with lingering references  <br>const cache = [];<br>function processData(data) {<br>  cache.push(data); // Data remains even if unused!<br>}</pre><p>Fix: Use WeakMap for ephemeral references:</p><pre>// ✅ WeakMap allows garbage collection when keys are removed  <br>const weakCache = new WeakMap();  <br>function processData(obj) {<br>  weakCache.set(obj, someMetadata); // Auto-cleared if obj is deleted<br>}</pre><ul><li>Singletons: Poorly managed singletons can accumulate stale data.</li></ul><h3>2️⃣ Closures &amp; Scopes: The Memory Traps</h3><ul><li>Recursive Closures: Functions inside loops or recursive calls that capture outer scope variables.</li></ul><pre>// 🚨 Leak Example: Closure in a loop retains outer variables  <br>for (var i = 0; i &lt; 10; i++) {<br>  setTimeout(() =&gt; console.log(i), 1000); // All logs print &quot;10&quot;!<br>}</pre><p>Fix: Use let or break the closure:</p><pre>// ✅ let creates a block-scoped variable  <br>for (let i = 0; i &lt; 10; i++) {<br>  setTimeout(() =&gt; console.log(i), 1000); // Logs 0-9<br>}</pre><ul><li>require in the Middle of Code: Dynamically requiring modules inside functions can lead to repeated module loading.</li></ul><pre>// 🚨 Leak Example: Repeatedly loading a module  <br>function getConfig() {<br>  const config = require(&#39;./config.json&#39;); // Re-loaded every call!<br>  return config;<br>}</pre><p>Fix: Load once at the top:</p><pre>// ✅ Load once, reuse  <br>const config = require(&#39;./config.json&#39;);  <br>function getConfig() {<br>  return config;<br>}</pre><h3>3️⃣ OS &amp; Language Objects: Resource Leaks</h3><ul><li>Open Descriptors: Unclosed files, sockets, or database connections.</li></ul><pre>// 🚨 Leak Example: Forgetting to close a file  <br>fs.open(&#39;largefile.txt&#39;, &#39;r&#39;, (err, fd) =&gt; {<br>  // Read file but never close fd!<br>});</pre><p>Fix: Always close resources:</p><pre>// ✅ Cleanup with try-finally  <br>fs.open(&#39;largefile.txt&#39;, &#39;r&#39;, (err, fd) =&gt; {<br>  try {<br>    // Read file...<br>  } finally {<br>    fs.close(fd, () =&gt; {}); // Ensure cleanup<br>  }<br>});</pre><ul><li>setTimeout/setInterval: Forgotten timers referencing objects.</li></ul><pre>// 🚨 Leak Example: Uncleared interval  <br>const interval = setInterval(() =&gt; {<br>  fetchData(); // Runs forever, even if unused!<br>}, 5000);</pre><p>Fix: Clear timers when done:</p><pre>// ✅ Clear interval on cleanup  <br>function startInterval() {<br>  const interval = setInterval(fetchData, 5000);<br>  return () =&gt; clearInterval(interval); // Return cleanup function<br>}<br>const stopInterval = startInterval();<br>stopInterval(); // Call when done</pre><h3>4️⃣ Events &amp; Subscriptions: The Silent Accumulators</h3><ul><li>EventEmitter Listeners: Not removing listeners.</li></ul><pre>// 🚨 Leak Example: Adding listeners without removing  <br>const emitter = new EventEmitter();<br>emitter.on(&#39;data&#39;, (data) =&gt; process(data)); // Listener persists forever!</pre><p>Fix: Always remove listeners:</p><pre>// ✅ Use named functions for removal  <br>function onData(data) { process(data); }<br>emitter.on(&#39;data&#39;, onData);<br>emitter.off(&#39;data&#39;, onData); // Explicit cleanup</pre><ul><li>Stale Callbacks: Passing anonymous functions to event handlers (e.g., on(‘data’, () =&gt; {…})).</li></ul><pre>// 🚨 Leak Example: Anonymous function in event listener  <br>const EventEmitter = require(&#39;events&#39;);<br>const myEmitter = new EventEmitter();<br><br>setInterval(() =&gt; {<br>  myEmitter.on(&#39;data&#39;, (message) =&gt; {<br>    console.log(&#39;Received:&#39;, message);<br>  });<br>}, 1000);<br><br>// Постоянно добавляются новые слушатели на &#39;data&#39; (утечка памяти)<br>setInterval(() =&gt; {<br>  myEmitter.emit(&#39;data&#39;, &#39;Hello, world!&#39;);<br>}, 3000);</pre><p>Fix: Use once() for one-time events:</p><pre>// ✅ Auto-remove after firing  <br>setInterval(() =&gt; {<br>  myEmitter.once(&#39;data&#39;, (message) =&gt; {<br>    console.log(&#39;Received:&#39;, message);<br>  });<br>}, 1000);</pre><h3>5️⃣ Cache: A Double-Edged Sword</h3><ul><li>Unbounded Caches: Caches that grow indefinitely.</li></ul><pre>// 🚨 Leak Example: Cache with no limits  <br>const cache = new Map();<br>function getData(key) {<br>  if (!cache.has(key)) {<br>    cache.set(key, fetchData(key)); // Grows forever!<br>  }<br>  return cache.get(key);<br>}</pre><p>Fix: Use an LRU cache with TTL:</p><pre>// ✅ npm install lru-cache  <br>import LRUCache from &#39;lru-cache&#39;;<br>const cache = new LRUCache({ max: 100, ttl: 60 * 1000 }); // Limit to 100 items, 1min TTLRarely Used Values: Cache entries that are never accessed.</pre><h3>6️⃣ Mixins: The Risky Extensions</h3><ul><li>Messing with Built-ins: Adding methods to Object.prototype or native classes.</li></ul><pre>// 🚨 Leak Example: Adding to Object.prototype  <br>Object.prototype.log = function() { console.log(this); };  <br>// All objects now have `log`, causing confusion and leaks!</pre><p>Fix: Use utility functions instead:</p><pre>// ✅ Safe utility module  <br>const logger = {<br>  log: (obj) =&gt; console.log(obj)<br>};<br>logger.log(user); // No prototype pollution</pre><ul><li>Process-Level Mixins: Attaching data to process or global contexts.</li></ul><h3>7️⃣ Concurrency: Worker &amp; Process Management</h3><ul><li>Orphaned Workers/Threads: Forgetting to terminate child processes or Worker threads.</li></ul><pre>// 🚨 Leak Example: Forgetting to terminate a worker  <br>const { Worker } = require(&#39;worker_threads&#39;);<br>const worker = new Worker(&#39;./task.js&#39;);  <br>// Worker runs indefinitely!</pre><p>Fix: Track and terminate workers:</p><pre>// ✅ Cleanup with a pool  <br>const workers = new Set();<br>function createWorker() {<br>  const worker = new Worker(&#39;./task.js&#39;);<br>  workers.add(worker);<br>  worker.on(&#39;exit&#39;, () =&gt; workers.delete(worker));<br>}<br>// Terminate all on shutdown  <br>process.on(&#39;exit&#39;, () =&gt; workers.forEach(w =&gt; w.terminate()));</pre><ul><li>Shared State in Clusters: Memory duplication in multi-process setups.</li></ul><h3>🔧 Pro Tips for Prevention</h3><ul><li>Heap Snapshots: Use node — inspect + Chrome DevTools to compare heap snapshots.</li><li>Monitor Event Listeners: Tools like emitter.getMaxListeners() or EventEmitter.listenerCount() to find leaks.</li><li>Automate Cleanup: Use destructors, finally blocks, or libraries like async-exit-hook for resource cleanup.</li></ul><p>Memory leaks are inevitable in complex systems, but with vigilance and the right practices, you can keep them in check. 💡</p><p>#NodeJS #MemoryLeaks #WebDev #Programming #TechTips #SoftwareEngineering #Debugging</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa7cf9112c56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode, Hard++ (Acceptance 24%, Latest): 2867. Count Valid Paths in a Tree. DFS. O(n). Swift.]]></title>
            <link>https://medium.com/@sergeyleschev/leetcode-hard-acceptance-24-latest-2867-count-valid-paths-in-a-tree-dfs-o-n-swift-b36efb1fcc5f?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b36efb1fcc5f</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 11:09:21 GMT</pubDate>
            <atom:updated>2023-09-24T11:09:21.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kd-qO3Yni7T4h4fCc7XHZg.jpeg" /><figcaption>Sergey Leschev. LeetCode Global TOP 200.</figcaption></figure><h3>Intuition</h3><p>The intuition is to employ a depth-first search (DFS) approach through the tree.</p><h3>Approach</h3><p>During each step in the traversal, we perform the following key calculations:</p><ol><li>Determine the path that ends at the current node.</li><li>Compute two different subtree paths that traverse the current node.</li><li>Maintain an array that keeps track of the cases where paths contain either 0 or 1 prime number.</li></ol><p>This method allows us to efficiently count the valid paths in the tree while considering the presence of prime numbers.</p><h3>Complexity</h3><ul><li>Time complexity: O(n)</li><li>Space complexity: O(n)</li></ul><h3>Code</h3><pre>class Solution {<br>    func countPaths(_ n: Int, _ edges: [[Int]]) -&gt; Int {<br>        var ans = 0<br>        var primes = Array(repeating: 1, count: n + 5)<br><br>        primes[1] = 0<br>        for i in 2...Int(sqrt(Double(n + 5))) {<br>            if primes[i] == 0 {<br>                continue<br>            }<br>            for j in stride(from: i * i, to: primes.count, by: i) {<br>                primes[j] = 0<br>            }<br>        }<br>        var adjList = Array(repeating: [Int](), count: n + 1)<br>        for edge in edges {<br>            adjList[edge[0]].append(edge[1])<br>            adjList[edge[1]].append(edge[0])<br>        }<br>        func dfs(_ curr: Int, _ parent: Int, _ adjList: [[Int]]) -&gt; [Int] {<br>            var count = [0, 0]<br>            let isPrime = primes[curr] == 1<br>            for child in adjList[curr] {<br>                if child == parent {<br>                    continue<br>                }<br>                let next = dfs(child, curr, adjList)<br>                if isPrime {<br>                    // Path ends at curr<br>                    ans += next[0]<br>                    // curr is conduit for path<br>                    ans += count[1] * next[0]<br>                    count[1] += next[0]<br>                } else {<br>                    // Ends at curr<br>                    ans += next[1]<br>                    // curr is conduit for path<br>                    ans += count[0] * next[1]<br>                    ans += count[1] * next[0]<br>                    count[0] += next[0]<br>                    count[1] += next[1]<br>                }<br>            }<br>            count[isPrime ? 1 : 0] += 1<br>            return count<br>        }<br>        dfs(1, -1, adjList)<br>        return ans<br>    }<br>}</pre><p>Sources: <a href="https://github.com/sergeyleschev/leetcode-swift/blob/main/2501-3000/2867.%20Count%20Valid%20Paths%20in%20a%20Tree.swift">Github</a></p><p><strong>Contacts</strong><br>I have a clear focus on time-to-market and don’t prioritize technical debt. And I took part in the Pre-Sale/RFX activity as a System Architect, assessment efforts for Mobile (iOS-Swift, Android-Kotlin), Frontend (React-TypeScript) and Backend (NodeJS-.NET-PHP-Kafka-SQL-NoSQL). And I also formed the work of Pre-Sale as a CTO from Opportunity to Proposal via knowledge transfer to Successful Delivery.</p><p>🛩️ #startups #management #cto #swift #typescript #database<br>📧 Email: <a href="/service/mailto:sergey.leschev@gmail.com">sergey.leschev@gmail.com</a><br>👋 LinkedIn: <a href="https://linkedin.com/in/sergeyleschev/">https://linkedin.com/in/sergeyleschev/</a><br>👋 LeetCode: <a href="https://leetcode.com/sergeyleschev/">https://leetcode.com/sergeyleschev/</a><br>👋 Twitter: <a href="https://twitter.com/sergeyleschev">https://twitter.com/sergeyleschev</a><br>👋 Github: <a href="https://github.com/sergeyleschev">https://github.com/sergeyleschev</a><br>🌎 Website: <a href="https://sergeyleschev.github.io/">https://sergeyleschev.github.io</a><br>🌎 Reddit: <a href="https://reddit.com/user/sergeyleschev">https://reddit.com/user/sergeyleschev</a><br>🌎 Quora: <a href="https://quora.com/sergey-leschev">https://quora.com/sergey-leschev</a><br>🌎 Medium: <a href="https://medium.com/@sergeyleschev">https://medium.com/@sergeyleschev</a><br>🖨️ PDF Design Patterns: <a href="https://sergeyleschev.github.io/sergeyleschev-design-patterns.pdf">Download</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b36efb1fcc5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useTimeout]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-usetimeout-c47db1bc34b9?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c47db1bc34b9</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Wed, 30 Aug 2023 21:42:24 GMT</pubDate>
            <atom:updated>2023-08-30T21:42:24.993Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VjG9wGZYERDteDuFONAxw.png" /><figcaption>React Custom Hook: useTimeout</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useTimeout” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useCallback, useEffect, useRef } from &quot;react&quot;<br><br>export default function useTimeout(callback, delay) {<br>    const callbackRef = useRef(callback)<br>    const timeoutRef = useRef()<br>    useEffect(() =&gt; {<br>        callbackRef.current = callback<br>    }, [callback])<br>    const set = useCallback(() =&gt; {<br>        timeoutRef.current = setTimeout(() =&gt; callbackRef.current(), delay)<br>    }, [delay])<br>    const clear = useCallback(() =&gt; {<br>        timeoutRef.current &amp;&amp; clearTimeout(timeoutRef.current)<br>    }, [])<br>    useEffect(() =&gt; {<br>        set()<br>        return clear<br>    }, [delay, set, clear])<br>    const reset = useCallback(() =&gt; {<br>        clear()<br>        set()<br>    }, [clear, set])<br>    return { reset, clear }<br>}</pre><p>The “<strong>useTimeout</strong>” hook encapsulates the logic for setting, clearing, and resetting timeouts within a React component. It takes two parameters: a callback function and a delay duration in milliseconds. Whenever the specified delay elapses, the provided callback function is executed.</p><p>One of the significant advantages of this custom hook is that it ensures the callback function remains up to date even if it changes during component re-renders. By using a useRef to store the callback reference, the hook guarantees that the latest version of the function is always called.</p><p>Moreover, the “useTimeout” hook optimizes performance by utilizing useCallback to memoize the “set” and “clear” functions. This means that the functions are only recreated when their dependencies change, preventing unnecessary renders and enhancing efficiency.</p><pre>import { useState } from &quot;react&quot;<br>import useTimeout from &quot;./useTimeout&quot;<br><br>export default function TimeoutComponent() {<br>    const [count, setCount] = useState(10)<br>    const { clear, reset } = useTimeout(() =&gt; setCount(0), 1000)<br>    return (<br>        &lt;div&gt;<br>            &lt;div&gt;{count}&lt;/div&gt;<br>            &lt;button onClick={() =&gt; setCount(c =&gt; c + 1)}&gt;Increment&lt;/button&gt;<br>            &lt;button onClick={clear}&gt;Clear Timeout&lt;/button&gt;<br>            &lt;button onClick={reset}&gt;Reset Timeout&lt;/button&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>The “<em>useTimeout</em>” hook can be utilized in various scenarios where timed actions are required. For example, in a countdown component like the “TimeoutComponent” showcased above, you can easily implement a timer that resets after a specific duration. By using the “useTimeout” hook, you can effortlessly update the countdown value and manage the timeout without worrying about complex timeout management code.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c47db1bc34b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useStorage]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-usestorage-f0ff25391df7?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ff25391df7</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 21:42:23 GMT</pubDate>
            <atom:updated>2023-08-29T21:42:23.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*blT_zWnyVgGGqCMX2DBW0g.png" /><figcaption>React Custom Hook: useStorage</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useStorage” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useCallback, useState, useEffect } from &quot;react&quot;<br><br>export function useLocalStorage(key, defaultValue) {<br>    return useStorage(key, defaultValue, window.localStorage)<br>}<br>export function useSessionStorage(key, defaultValue) {<br>    return useStorage(key, defaultValue, window.sessionStorage)<br>}<br>function useStorage(key, defaultValue, storageObject) {<br>    const [value, setValue] = useState(() =&gt; {<br>        const jsonValue = storageObject.getItem(key)<br>        if (jsonValue != null) return JSON.parse(jsonValue)<br>        if (typeof defaultValue === &quot;function&quot;) {<br>            return defaultValue()<br>        } else {<br>            return defaultValue<br>        }<br>    })<br>    useEffect(() =&gt; {<br>        if (value === undefined) return storageObject.removeItem(key)<br>        storageObject.setItem(key, JSON.stringify(value))<br>    }, [key, value, storageObject])<br>    const remove = useCallback(() =&gt; {<br>        setValue(undefined)<br>    }, [])<br>    return [value, setValue, remove]<br>}</pre><p>The <strong>useStorage</strong> hook provides two convenient functions: useLocalStorage and useSessionStorage. With useLocalStorage, you can effortlessly store and retrieve data in the browser’s local storage, while useSessionStorage offers the same functionality but with the session storage instead.</p><p>One of the key advantages of this custom hook is its simplicity. You can use it to store any type of data, such as strings, numbers, or even complex objects, with just a few lines of code. Additionally, useStorage handles the serialization and deserialization of data for you, so you don’t have to worry about converting values to and from JSON.</p><p>Another advantage is the automatic synchronization between the stored data and the component’s state. Whenever the stored data changes, the hook updates the component’s state accordingly. Similarly, when the component’s state changes, the hook automatically persists the new value to the storage. This bidirectional synchronization ensures that your application always reflects the latest data, making it ideal for scenarios where real-time updates are crucial.</p><p>The useStorage hook also provides a remove function, allowing you to easily delete stored values when they are no longer needed. This functionality comes in handy when implementing features like logout buttons or clearing user-specific data.</p><pre>import { useSessionStorage, useLocalStorage } from &quot;./useStorage&quot;<br><br>export default function StorageComponent() {<br>    const [name, setName, removeName] = useSessionStorage(&quot;name&quot;, &quot;Sergey&quot;)<br>    const [age, setAge, removeAge] = useLocalStorage(&quot;age&quot;, 26)<br>    return (<br>        &lt;div&gt;<br>            &lt;div&gt;<br>                {name} - {age}<br>            &lt;/div&gt;<br>            &lt;button onClick={() =&gt; setName(&quot;John&quot;)}&gt;Set Name&lt;/button&gt;<br>            &lt;button onClick={() =&gt; setAge(40)}&gt;Set Age&lt;/button&gt;<br>            &lt;button onClick={removeName}&gt;Remove Name&lt;/button&gt;<br>            &lt;button onClick={removeAge}&gt;Remove Age&lt;/button&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>You can use the <em>useStorage</em> hook in a variety of scenarios. For example, imagine you have a settings panel where users can customize their preferences. By using useLocalStorage, you can easily store and retrieve these settings, ensuring that they persist across page reloads or even if the user closes and reopens the browser.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ff25391df7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useStateWithValidation]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-usestatewithvalidation-84e4618df4de?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e4618df4de</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Mon, 28 Aug 2023 21:38:22 GMT</pubDate>
            <atom:updated>2023-08-28T21:38:22.635Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpw0FeDXJ_vLwTE62585iw.png" /><figcaption>React Custom Hook: useStateWithValidation</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useStateWithValidation” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useState, useCallback } from &quot;react&quot;<br><br>export default function useStateWithValidation(validationFunc, initialValue) {<br>    const [state, setState] = useState(initialValue)<br>    const [isValid, setIsValid] = useState(() =&gt; validationFunc(state))<br>    const onChange = useCallback(<br>        nextState =&gt; {<br>            const value =<br>                typeof nextState === &quot;function&quot; ? nextState(state) : nextState<br>            setState(value)<br>            setIsValid(validationFunc(value))<br>        },<br>        [validationFunc]<br>    )<br>    return [state, onChange, isValid]<br>}</pre><p>The <strong>useStateWithValidation</strong> hook combines the useState and useCallback hooks from React to provide an elegant solution. It takes two parameters: a validation function and an initial value. The validation function determines whether the current state is considered valid or not.</p><p>One of the key advantages of this custom hook is its flexibility. You can pass any validation function that suits your specific requirements. Whether it’s checking the length of a string, ensuring a numeric value falls within a certain range, or performing more complex validations, useStateWithValidation has got you covered.</p><pre>import useStateWithValidation from &quot;./useStateWithValidation&quot;<br><br>export default function StateWithValidationComponent() {<br>    const [username, setUsername, isValid] = useStateWithValidation(<br>        name =&gt; name.length &gt; 5,<br>        &quot;&quot;<br>    )<br>    return (<br>        &lt;&gt;<br>            &lt;div&gt;Valid: {isValid.toString()}&lt;/div&gt;<br>            &lt;input<br>                type=&quot;text&quot;<br>                value={username}<br>                onChange={e =&gt; setUsername(e.target.value)}<br>            /&gt;<br>        &lt;/&gt;<br>    )<br>}</pre><p>In this example, the StateWithValidationComponent uses the <em>useStateWithValidation</em> hook to manage the username state. The validation function checks if the length of the username is greater than 5 characters, and the isValid variable reflects the validity of the current input.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e4618df4de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useStateWithHistory]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-usestatewithhistory-961ce54a4df2?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/961ce54a4df2</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Sun, 27 Aug 2023 21:38:22 GMT</pubDate>
            <atom:updated>2023-08-27T21:38:22.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2AdlGBkOrNg2MlqES7XdA.png" /><figcaption>React Custom Hook: useStateWithHistory</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useStateWithHistory” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useCallback, useRef, useState } from &quot;react&quot;<br><br>export default function useStateWithHistory(<br>    defaultValue,<br>    { capacity = 10 } = {}<br>) {<br>    const [value, setValue] = useState(defaultValue)<br>    const historyRef = useRef([value])<br>    const pointerRef = useRef(0)<br>    const set = useCallback(<br>        v =&gt; {<br>            const resolvedValue = typeof v === &quot;function&quot; ? v(value) : v<br>            if (historyRef.current[pointerRef.current] !== resolvedValue) {<br>                if (pointerRef.current &lt; historyRef.current.length - 1) {<br>                    historyRef.current.splice(pointerRef.current + 1)<br>                }<br>                historyRef.current.push(resolvedValue)<br>                while (historyRef.current.length &gt; capacity) {<br>                    historyRef.current.shift()<br>                }<br>                pointerRef.current = historyRef.current.length - 1<br>            }<br>            setValue(resolvedValue)<br>        },<br>        [capacity, value]<br>    )<br>    const back = useCallback(() =&gt; {<br>        if (pointerRef.current &lt;= 0) return<br>        pointerRef.current--<br>        setValue(historyRef.current[pointerRef.current])<br>    }, [])<br>    const forward = useCallback(() =&gt; {<br>        if (pointerRef.current &gt;= historyRef.current.length - 1) return<br>        pointerRef.current++<br>        setValue(historyRef.current[pointerRef.current])<br>    }, [])<br>    const go = useCallback(index =&gt; {<br>        if (index &lt; 0 || index &gt; historyRef.current.length - 1) return<br>        pointerRef.current = index<br>        setValue(historyRef.current[pointerRef.current])<br>    }, [])<br>    return [<br>        value,<br>        set,<br>        {<br>            history: historyRef.current,<br>            pointer: pointerRef.current,<br>            back,<br>            forward,<br>            go,<br>        },<br>    ]<br>}</pre><p>Advantages of <strong>useStateWithHistory</strong>:</p><ol><li>Automatic history tracking: useStateWithHistory automatically keeps track of the values you set, allowing you to access the complete history whenever you need it.</li><li>Efficient memory usage: The hook utilizes a capacity parameter, ensuring that the history doesn’t grow indefinitely. You can define the maximum number of historical values to keep, preventing excessive memory consumption.</li><li>Time-travel functionality: With back(), forward(), and go() functions, you can seamlessly navigate through the recorded history. Travel back and forth between previous states or jump directly to a specific index, enabling powerful undo/redo or step-by-step functionality.</li></ol><p>Where to use useStateWithHistory:</p><ol><li>Form management: Simplify the process of handling form inputs by providing an easy way to track changes, revert to previous values, or redo modifications.</li><li>Undo/Redo functionality: Implement undo/redo functionality in your application with ease. Track state changes and allow users to navigate back and forth through their actions effortlessly.</li><li>Step-by-step navigation: Use useStateWithHistory to build interactive guides or tutorials where users can navigate between different steps while preserving their progress.</li></ol><pre>import { useState } from &quot;react&quot;<br>import useStateWithHistory from &quot;./useStateWithHistory&quot;<br><br>export default function StateWithHistoryComponent() {<br>    const [count, setCount, { history, pointer, back, forward, go }] =<br>        useStateWithHistory(1)<br>    const [name, setName] = useState(&quot;Sergey&quot;)<br>    return (<br>        &lt;div&gt;<br>            &lt;div&gt;{count}&lt;/div&gt;<br>            &lt;div&gt;{history.join(&quot;, &quot;)}&lt;/div&gt;<br>            &lt;div&gt;Pointer - {pointer}&lt;/div&gt;<br>            &lt;div&gt;{name}&lt;/div&gt;<br>            &lt;button onClick={() =&gt; setCount(currentCount =&gt; currentCount * 2)}&gt;<br>                Double<br>            &lt;/button&gt;<br>            &lt;button onClick={() =&gt; setCount(currentCount =&gt; currentCount + 1)}&gt;<br>                Increment<br>            &lt;/button&gt;<br>            &lt;button onClick={back}&gt;Back&lt;/button&gt;<br>            &lt;button onClick={forward}&gt;Forward&lt;/button&gt;<br>            &lt;button onClick={() =&gt; go(2)}&gt;Go To Index 2&lt;/button&gt;<br>            &lt;button onClick={() =&gt; setName(&quot;John&quot;)}&gt;Change Name&lt;/button&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Throughout this article series, we focused on one of the gems from the collection of React custom hooks — “<em>useStateWithHistory</em>”. This hook, sourced from the “react-custom-hooks” repository, revolutionizes how we work in our React applications.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=961ce54a4df2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useScript]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-usescript-1cce1bc1e3c8?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cce1bc1e3c8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 21:36:30 GMT</pubDate>
            <atom:updated>2023-08-26T21:36:30.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uT6cBtJmjmvLVbZuPif1YA.png" /><figcaption>React Custom Hook: useScript</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useScript” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import useAsync from &quot;../useAsync/useAsync&quot;<br><br>export default function useScript(url) {<br>    return useAsync(() =&gt; {<br>        const script = document.createElement(&quot;script&quot;)<br>        script.src = url<br>        script.async = true<br>        return new Promise((resolve, reject) =&gt; {<br>            script.addEventListener(&quot;load&quot;, resolve)<br>            script.addEventListener(&quot;error&quot;, reject)<br>            document.body.appendChild(script)<br>        })<br>    }, [url])<br>}</pre><p>One of the significant advantages of <strong>useScript</strong> is its ability to handle script loading asynchronously. By setting the script’s async attribute to true, you ensure that it won’t block the rendering of your application. This improves the performance and overall user experience, especially when dealing with larger scripts or slow network connections.</p><p>useScript can be used in various scenarios. For instance, you can load external libraries like jQuery, enabling you to harness its powerful functionalities without adding bulk to your bundle. Additionally, you can load analytics scripts, social media widgets, or any other script necessary for your application’s dynamic behavior.</p><pre>import useScript from &quot;./useScript&quot;<br><br>export default function ScriptComponent() {<br>    const { loading, error } = useScript(<br>        &quot;https://code.jquery.com/jquery-3.6.0.min.js&quot;<br>    )<br>    if (loading) return &lt;div&gt;Loading&lt;/div&gt;<br>    if (error) return &lt;div&gt;Error&lt;/div&gt;<br>    return &lt;div&gt;{window.$(window).width()}&lt;/div&gt;<br>}</pre><p>In the example above, we see how useScript is utilized in a ScriptComponent. The <em>useScript</em> hook is called with the URL of the jQuery library as an argument. The hook returns the loading and error states, which can be used to display a loading spinner or an error message accordingly. Once the script is successfully loaded, the component displays the current window width using jQuery.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cce1bc1e3c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useRenderCount]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-userendercount-23210ffde422?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/23210ffde422</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Sat, 26 Aug 2023 04:51:01 GMT</pubDate>
            <atom:updated>2023-08-26T04:51:01.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JrJohJDg9NaMxFAiUDmb5Q.png" /><figcaption>React Custom Hook: useRenderCount</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useRenderCount” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useEffect, useRef } from &quot;react&quot;<br><br>export default function useRenderCount() {<br>    const count = useRef(1)<br>    useEffect(() =&gt; count.current++)<br>    return count.current<br>}</pre><p>The <strong>useRenderCount</strong> hook utilizes React’s useEffect and useRef hooks to keep a count of renders. With each render, the count is incremented, providing you with real-time feedback on the component’s render frequency.</p><p>One of the major advantages of using useRenderCount is its simplicity. By abstracting the logic into a reusable hook, you can easily integrate it into any component without cluttering your codebase. Additionally, it provides a clear and concise way to monitor render behavior, which can be crucial for performance optimization and debugging.</p><pre>import useRenderCount from &quot;./useRenderCount&quot;<br>import useToggle from &quot;../useToggle/useToggle&quot;<br><br>export default function RenderCountComponent() {<br>    const [boolean, toggle] = useToggle(false)<br>    const renderCount = useRenderCount()<br>    return (<br>        &lt;&gt;<br>            &lt;div&gt;{boolean.toString()}&lt;/div&gt;<br>            &lt;div&gt;{renderCount}&lt;/div&gt;<br>            &lt;button onClick={toggle}&gt;Toggle&lt;/button&gt;<br>        &lt;/&gt;<br>    )<br>}</pre><p>This versatile hook can be applied in various scenarios. For instance, when you’re developing a complex component that exhibits unexpected rendering patterns, <em>useRenderCount</em> helps you pinpoint the problem by showing the exact number of renders. It is also handy for measuring the impact of certain optimizations or refactoring techniques, allowing you to assess their effectiveness.</p><p>To get started, simply import the useRenderCount hook and call it within your component. You can see its power in action by checking out the RenderCountComponent example above. By combining useRenderCount with other custom hooks like useToggle, you can build interactive components while keeping an eye on render counts.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23210ffde422" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: usePrevious]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-useprevious-bc1cdc6dbf4e?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc1cdc6dbf4e</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Fri, 25 Aug 2023 04:46:03 GMT</pubDate>
            <atom:updated>2023-08-25T04:46:03.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j0lkE1SYDk7UgMpQQ5465A.png" /><figcaption>React Custom Hook: usePrevious</figcaption></figure><p>n this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “usePrevious” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useRef } from &quot;react&quot;<br><br>export default function usePrevious(value) {<br>    const currentRef = useRef(value)<br>    const previousRef = useRef()<br>    if (currentRef.current !== value) {<br>        previousRef.current = currentRef.current<br>        currentRef.current = value<br>    }<br>    return previousRef.current<br>}</pre><p>The advantages of using <strong>usePrevious</strong> are remarkable. By using useRef, this hook efficiently stores the current and previous values, updating them whenever the value changes. By comparing the current and previous values, you can easily detect and respond to changes in your component’s data.</p><p>This custom hook can be a game-changer in various scenarios. For instance, you can utilize usePrevious to compare and visualize changes in data, track state transitions, or implement undo/redo functionality. Additionally, it can be valuable in form handling, animations, and any situation where having access to the previous value is crucial for your application’s logic.</p><p>Let’s take a glance at how usePrevious can be used in practice. Consider a React component called PreviousComponent, where we have a count state, a name state, and a button to increment the count and change the name. By incorporating usePrevious, we can effortlessly display the current count alongside its previous value, enabling users to visualize the count’s changes at a glance.</p><pre>import { useState } from &quot;react&quot;<br>import usePrevious from &quot;./usePrevious&quot;<br><br>export default function PreviousComponent() {<br>    const [count, setCount] = useState(0)<br>    const [name, setName] = useState(&quot;Sergey&quot;)<br>    const previousCount = usePrevious(count)<br>    return (<br>        &lt;div&gt;<br>            &lt;div&gt;<br>                {count} - {previousCount}<br>            &lt;/div&gt;<br>            &lt;div&gt;{name}&lt;/div&gt;<br>            &lt;button onClick={() =&gt; setCount(currentCount =&gt; currentCount + 1)}&gt;<br>                Increment<br>            &lt;/button&gt;<br>            &lt;button onClick={() =&gt; setName(&quot;John&quot;)}&gt;Change Name&lt;/button&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Throughout this article series, we focused on one of the gems from the collection of React custom hooks — “<em>usePrevious</em>”. This hook, sourced from the “react-custom-hooks” repository, revolutionizes how we work in our React applications.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc1cdc6dbf4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Custom Hook: useOnScreen]]></title>
            <link>https://medium.com/@sergeyleschev/react-custom-hook-useonscreen-e01dfa2b51fa?source=rss-121dba2162b4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e01dfa2b51fa</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Sergey Leschev]]></dc:creator>
            <pubDate>Thu, 24 Aug 2023 18:46:01 GMT</pubDate>
            <atom:updated>2023-08-24T18:46:01.289Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Kk-M-BTl2MuTBFSqTD_Fg.png" /><figcaption>React Custom Hook: useOnScreen</figcaption></figure><p>In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useOnScreen” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.</p><p>Github: <a href="https://github.com/sergeyleschev/react-custom-hooks">https://github.com/sergeyleschev/react-custom-hooks</a></p><pre>import { useEffect, useState } from &quot;react&quot;<br><br>export default function useOnScreen(ref, rootMargin = &quot;0px&quot;) {<br>    const [isVisible, setIsVisible] = useState(false)<br>    useEffect(() =&gt; {<br>        if (ref.current == null) return<br>        const observer = new IntersectionObserver(<br>            ([entry]) =&gt; setIsVisible(entry.isIntersecting),<br>            { rootMargin }<br>        )<br>        observer.observe(ref.current)<br>        return () =&gt; {<br>            if (ref.current == null) return<br>            observer.unobserve(ref.current)<br>        }<br>    }, [ref.current, rootMargin])<br>    return isVisible<br>}</pre><p>The useOnScreen hook leverages the power of the Intersection Observer API, making it efficient and reliable. By simply providing a ref to the element you want to monitor, useOnScreen will notify you when it enters or exits the viewport.</p><p>One of the key advantages of <strong>useOnScreen</strong> is its simplicity. With just a few lines of code, you can detect if an element is visible and respond accordingly. This can be immensely useful in scenarios where you want to trigger animations, lazy load images, or load additional content as the user scrolls.</p><p>To use this hook, first import it into your component file. Then, create a ref using the useRef hook to target the desired element. Pass the ref as the first argument to the useOnScreen hook, and you’re all set! You can also provide an optional rootMargin value to adjust the visible threshold.</p><pre>import { useRef } from &quot;react&quot;<br>import useOnScreen from &quot;./useOnScreen&quot;<br><br>export default function OnScreenComponentComponent() {<br>    const headerTwoRef = useRef()<br>    const visible = useOnScreen(headerTwoRef, &quot;-100px&quot;)<br>    return (<br>        &lt;div&gt;<br>            &lt;h1&gt;Header&lt;/h1&gt;<br>            &lt;div&gt;<br>              ...<br>            &lt;/div&gt;<br>            &lt;h1 ref={headerTwoRef}&gt;Header 2 {visible &amp;&amp; &quot;(Visible)&quot;}&lt;/h1&gt;<br>            &lt;div&gt;<br>              ...<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>In our example code, the OnScreenComponentComponent demonstrates how to use the <em>useOnScreen</em> hook. By attaching the ref to the second header element, we can display a “(Visible)” text when it enters the viewport. Feel free to customize the logic within your component to suit your specific needs.</p><p>Full Version | React Custom Hooks: <a href="https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18">https://medium.com/@sergeyleschev/supercharge-your-projects-with-custom-hooks-4d946b297d18</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e01dfa2b51fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>