{"id":12094,"date":"2025-04-15T06:40:03","date_gmt":"2025-04-15T06:40:03","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/qanda\/?p=12094"},"modified":"2025-04-15T06:40:03","modified_gmt":"2025-04-15T06:40:03","slug":"useref-in-react","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/qanda\/react\/useref-in-react","title":{"rendered":"What is useRef for?"},"content":{"rendered":"<h2>What is useRef?<\/h2>\n<p>The useRef is a hook that allows us to persist values across renders without causing a re-render when the value changes. It\u2019s commonly used for two main purposes:<\/p>\n<p>Accessing DOM Elements: We can use useRef to store a reference to a DOM element and directly interact with it (e.g., focusing an input field).<\/p>\n<p>Persisting Mutable Values: We can store values (like flags or previous state) that we want to persist across renders, but without triggering a re-render when they change.<br \/>\nThe value we store in useRef is accessible through ref.current.<\/p>\n<h2>Syntax:<\/h2>\n<p><code>const myRef = useRef(initialValue);<\/code><\/p>\n<p>initialValue: This is the initial value we want to assign to the ref (it can be any data type: object, array, number, etc.).<\/p>\n<p>myRef.current: We access the actual value using .current<\/p>\n<h3>A Quick Comparison: useState vs. useRef:<\/h3>\n<p><strong>useState:<\/strong> Triggers a re-render when the state value changes.<br \/>\n<strong>useRef:<\/strong> Does not trigger a re-render when the value changes.<\/p>\n<h2>Code 1 Explanation:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">export default function useIsMountedRef() {\r\n  const isMounted = useRef(true);\r\n  useEffect(\r\n    () =&gt; () =&gt; {\r\n      isMounted.current = false;\r\n    },\r\n    []\r\n  );\r\n  return isMounted;\r\n}<\/pre>\n<h3>What\u2019s happening here?<\/h3>\n<p>useRef(true) initializes isMounted with the value true.<br \/>\n-&gt; isMounted.current = true means the component is mounted when the component first renders.<\/p>\n<p><strong>Inside<\/strong> useEffect, the cleanup function (() =&gt; { isMounted.current = false; }) sets isMounted.current to false when the component unmounts (because useEffect with an empty dependency array [] only runs once \u2014 after the initial mount and cleanup on unmount).<\/p>\n<p>So, useRef(true) tracks whether the component is mounted:<br \/>\nIt starts with true (mounted).<br \/>\nOnce the component unmounts, it sets the value to false.<\/p>\n<h3>Why use useRef here?<\/h3>\n<p>If we\u2019re doing something asynchronous, like an API call, and we want to avoid updating state or doing something after the component has unmounted (because that could lead to errors), we can check if the component is still mounted using this ref.<\/p>\n<h3>What is the difference between useRef(true) and useRef(false)?<\/h3>\n<ul>\n<li>useRef(true) means the component is initially considered &#8220;mounted.&#8221;<\/li>\n<li>useRef(false) would mean the component is initially considered &#8220;unmounted,&#8221; which could be useful to track something else from the beginning.<\/li>\n<\/ul>\n<h2>Code 2 Explanation:<\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"r\">const mounted = useRef(false);\r\nuseEffect(() =&gt; {\r\n  if (!mounted.current) {\r\n    mounted.current = true;\r\n  } else {\r\n    \/\/ code\r\n  }\r\n}, [dependency]);\r\n<\/pre>\n<h3>What\u2019s happening here?<\/h3>\n<p>useRef(false) initializes the mounted ref to false. This is tracking whether the effect has run before.<\/p>\n<p><span style=\"font-weight: 400;\">Inside the <\/span><span style=\"font-weight: 400;\">useEffect<\/span><span style=\"font-weight: 400;\">:<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"2\"><span style=\"font-weight: 400;\">On the first render, <\/span><span style=\"font-weight: 400;\">mounted.current<\/span><span style=\"font-weight: 400;\"> is <\/span><span style=\"font-weight: 400;\">false<\/span><span style=\"font-weight: 400;\">, so the first block (<\/span><span style=\"font-weight: 400;\">mounted.current = true<\/span><span style=\"font-weight: 400;\">) will execute, updating the <\/span><span style=\"font-weight: 400;\">mounted<\/span><span style=\"font-weight: 400;\"> ref to <\/span><span style=\"font-weight: 400;\">true<\/span><span style=\"font-weight: 400;\">.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"2\"><span style=\"font-weight: 400;\">On subsequent renders (or when <\/span><span style=\"font-weight: 400;\">dependency<\/span><span style=\"font-weight: 400;\"> changes), <\/span><span style=\"font-weight: 400;\">mounted.current<\/span><span style=\"font-weight: 400;\"> will be <\/span><span style=\"font-weight: 400;\">true<\/span><span style=\"font-weight: 400;\">, and it will enter the <\/span><span style=\"font-weight: 400;\">else<\/span><span style=\"font-weight: 400;\"> block.<\/span><\/li>\n<\/ul>\n<h3>Why use useRef here?<\/h3>\n<p><span style=\"font-weight: 400;\">This pattern can be useful for skipping certain code on the first render (like an initialization phase) and only running it on subsequent renders.<\/span><\/p>\n<p><strong>For example:<\/strong><\/p>\n<ul>\n<li style=\"font-weight: 400;\" aria-level=\"1\"><span style=\"font-weight: 400;\">The first time the component renders, we set <\/span><span style=\"font-weight: 400;\">mounted.current = true<\/span><span style=\"font-weight: 400;\"> to signal that we\u2019ve seen the component.<\/span><\/li>\n<li style=\"font-weight: 400;\" aria-level=\"1\">On subsequent renders (when <span>mounted.current<\/span><span> is <\/span><span>true<\/span><span>), we can run our logic inside the <\/span><span>else<\/span><span> block.<\/span><\/li>\n<\/ul>\n<h2>Summary:<\/h2>\n<p>useRef keeps a mutable value across renders, but it doesn\u2019t cause re-renders when that value changes.<\/p>\n<p>In <strong>code 1,<\/strong> it tracks whether a component is mounted or not.<\/p>\n<p>In <strong>code 2<\/strong>, it tracks whether the effect has already run once, allowing us to skip code on the first render.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>What is useRef? The useRef is a hook that allows us to persist values across renders without causing a re-render when the value changes. It\u2019s commonly used for two main purposes: Accessing DOM Elements: We can use useRef to store a reference to a DOM element and directly interact with it (e.g., focusing an input [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":12095,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"inline_featured_image":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-12094","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/12094"}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/comments?post=12094"}],"version-history":[{"count":1,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/12094\/revisions"}],"predecessor-version":[{"id":12096,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/posts\/12094\/revisions\/12096"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media\/12095"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/media?parent=12094"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/categories?post=12094"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/qanda\/wp-json\/wp\/v2\/tags?post=12094"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}