{"id":351402,"date":"2024-05-20T12:48:55","date_gmt":"2024-05-20T12:48:55","guid":{"rendered":"http:\/\/savepearlharbor.com\/?p=351402"},"modified":"-0001-11-30T00:00:00","modified_gmt":"-0001-11-29T21:00:00","slug":"","status":"publish","type":"post","link":"https:\/\/savepearlharbor.com\/?p=351402","title":{"rendered":"<span>React Custom Hook: useTimeout<\/span>"},"content":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<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 &#171;useTimeout&#187; hook, one of the many carefully crafted hooks available in the collection of React custom hooks.<\/p>\n<p>Github:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/react-custom-hooks\" rel=\"noopener noreferrer nofollow\"><u>https:\/\/github.com\/sergeyleschev\/react-custom-hooks<\/u><\/a><\/p>\n<pre><code class=\"javascript\">import { useCallback, useEffect, useRef } from \"react\"  export default function useTimeout(callback, delay) {     const callbackRef = useRef(callback)     const timeoutRef = useRef()     useEffect(() => {         callbackRef.current = callback     }, [callback])     const set = useCallback(() => {         timeoutRef.current = setTimeout(() => callbackRef.current(), delay)     }, [delay])     const clear = useCallback(() => {         timeoutRef.current &amp;&amp; clearTimeout(timeoutRef.current)     }, [])     useEffect(() => {         set()         return clear     }, [delay, set, clear])     const reset = useCallback(() => {         clear()         set()     }, [clear, set])     return { reset, clear } }<\/code><\/pre>\n<p>The &#171;<strong>useTimeout<\/strong>&#187; 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>\n<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>\n<p>Moreover, the &#171;useTimeout&#187; hook optimizes performance by utilizing useCallback to memoize the &#171;set&#187; and &#171;clear&#187; functions. This means that the functions are only recreated when their dependencies change, preventing unnecessary renders and enhancing efficiency.<\/p>\n<pre><code class=\"javascript\">import { useState } from \"react\" import useTimeout from \".\/useTimeout\"  export default function TimeoutComponent() {     const [count, setCount] = useState(10)     const { clear, reset } = useTimeout(() => setCount(0), 1000)     return (         &lt;div>             &lt;div>{count}&lt;\/div>             &lt;button onClick={() => setCount(c => c + 1)}>Increment&lt;\/button>             &lt;button onClick={clear}>Clear Timeout&lt;\/button>             &lt;button onClick={reset}>Reset Timeout&lt;\/button>         &lt;\/div>     ) }<\/code><\/pre>\n<p>The &#171;<em>useTimeout<\/em>&#187; hook can be utilized in various scenarios where timed actions are required. For example, in a countdown component like the &#171;TimeoutComponent&#187; showcased above, you can easily implement a timer that resets after a specific duration. By using the &#171;useTimeout&#187; hook, you can effortlessly update the countdown value and manage the timeout without worrying about complex timeout management code.<\/p>\n<p>Full Version | React Custom Hooks: <a href=\"https:\/\/habr.com\/en\/articles\/746760\/\" rel=\"noopener noreferrer nofollow\">https:\/\/habr.com\/en\/articles\/746760\/<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/752832\/\"> https:\/\/habr.com\/ru\/articles\/752832\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div><!--[--><!--]--><\/div>\n<div id=\"post-content-body\">\n<div>\n<div class=\"article-formatted-body article-formatted-body article-formatted-body_version-2\">\n<div xmlns=\"http:\/\/www.w3.org\/1999\/xhtml\">\n<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 &#171;useTimeout&#187; hook, one of the many carefully crafted hooks available in the collection of React custom hooks.<\/p>\n<p>Github:\u00a0<a href=\"https:\/\/github.com\/sergeyleschev\/react-custom-hooks\" rel=\"noopener noreferrer nofollow\"><u>https:\/\/github.com\/sergeyleschev\/react-custom-hooks<\/u><\/a><\/p>\n<pre><code class=\"javascript\">import { useCallback, useEffect, useRef } from \"react\"  export default function useTimeout(callback, delay) {     const callbackRef = useRef(callback)     const timeoutRef = useRef()     useEffect(() => {         callbackRef.current = callback     }, [callback])     const set = useCallback(() => {         timeoutRef.current = setTimeout(() => callbackRef.current(), delay)     }, [delay])     const clear = useCallback(() => {         timeoutRef.current &amp;&amp; clearTimeout(timeoutRef.current)     }, [])     useEffect(() => {         set()         return clear     }, [delay, set, clear])     const reset = useCallback(() => {         clear()         set()     }, [clear, set])     return { reset, clear } }<\/code><\/pre>\n<p>The &#171;<strong>useTimeout<\/strong>&#187; 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>\n<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>\n<p>Moreover, the &#171;useTimeout&#187; hook optimizes performance by utilizing useCallback to memoize the &#171;set&#187; and &#171;clear&#187; functions. This means that the functions are only recreated when their dependencies change, preventing unnecessary renders and enhancing efficiency.<\/p>\n<pre><code class=\"javascript\">import { useState } from \"react\" import useTimeout from \".\/useTimeout\"  export default function TimeoutComponent() {     const [count, setCount] = useState(10)     const { clear, reset } = useTimeout(() => setCount(0), 1000)     return (         &lt;div>             &lt;div>{count}&lt;\/div>             &lt;button onClick={() => setCount(c => c + 1)}>Increment&lt;\/button>             &lt;button onClick={clear}>Clear Timeout&lt;\/button>             &lt;button onClick={reset}>Reset Timeout&lt;\/button>         &lt;\/div>     ) }<\/code><\/pre>\n<p>The &#171;<em>useTimeout<\/em>&#187; hook can be utilized in various scenarios where timed actions are required. For example, in a countdown component like the &#171;TimeoutComponent&#187; showcased above, you can easily implement a timer that resets after a specific duration. By using the &#171;useTimeout&#187; hook, you can effortlessly update the countdown value and manage the timeout without worrying about complex timeout management code.<\/p>\n<p>Full Version | React Custom Hooks: <a href=\"https:\/\/habr.com\/en\/articles\/746760\/\" rel=\"noopener noreferrer nofollow\">https:\/\/habr.com\/en\/articles\/746760\/<\/a><\/p>\n<\/p>\n<\/div>\n<\/div>\n<\/div>\n<p><!----><!----><\/div>\n<p><!----><!----><br \/> \u0441\u0441\u044b\u043b\u043a\u0430 \u043d\u0430 \u043e\u0440\u0438\u0433\u0438\u043d\u0430\u043b \u0441\u0442\u0430\u0442\u044c\u0438 <a href=\"https:\/\/habr.com\/ru\/articles\/752832\/\"> https:\/\/habr.com\/ru\/articles\/752832\/<\/a><br \/><\/br><\/br><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-351402","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/351402","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=351402"}],"version-history":[{"count":0,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=\/wp\/v2\/posts\/351402\/revisions"}],"wp:attachment":[{"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=351402"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=351402"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/savepearlharbor.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=351402"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}