{"id":3388,"date":"2026-09-14T15:38:52","date_gmt":"2026-09-14T07:38:52","guid":{"rendered":"http:\/\/www.shubhsutra.com\/blog\/?p=3388"},"modified":"2026-09-14T15:38:52","modified_gmt":"2026-09-14T07:38:52","slug":"what-is-the-purpose-of-the-useeffect-hook-4d1f-cf0c43","status":"publish","type":"post","link":"http:\/\/www.shubhsutra.com\/blog\/2026\/09\/14\/what-is-the-purpose-of-the-useeffect-hook-4d1f-cf0c43\/","title":{"rendered":"What is the purpose of the useEffect hook?"},"content":{"rendered":"<p>Hey there, fellow devs! I&#8217;m a supplier of Hooks, and I&#8217;ve been getting a lot of questions lately about the <code>useEffect<\/code> hook. So, I thought I&#8217;d take a moment to break it down and explain what its purpose is. <a href=\"https:\/\/www.gscseatbelt.com\/hooks\/\">Hooks<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.gscseatbelt.com\/uploads\/202335941\/small\/seat-belt-shoulder-strap68f0ec5a-422c-433b-852e-1a8c30755047.jpg\"><\/p>\n<p>First off, if you&#8217;re new to React, Hooks are a relatively new addition to the library. They were introduced in React 16.8, and they allow you to use state and other React features without writing a class. <code>useEffect<\/code> is one of the most commonly used Hooks, and it&#8217;s super powerful.<\/p>\n<p>So, what&#8217;s the deal with <code>useEffect<\/code>? Well, in a nutshell, it&#8217;s a way to perform side effects in functional components. Side effects are things like data fetching, subscriptions, or manually changing the DOM. In class components, these side effects are usually handled in the <code>componentDidMount<\/code>, <code>componentDidUpdate<\/code>, and <code>componentWillUnmount<\/code> lifecycle methods. With <code>useEffect<\/code>, you can handle all of these in one place.<\/p>\n<p>Let&#8217;s start with the basics. Here&#8217;s a simple example of how you might use <code>useEffect<\/code> to perform a side effect:<\/p>\n<pre><code class=\"language-jsx\">import React, { useEffect } from 'react';\n\nfunction Example() {\n  useEffect(() =&gt; {\n    \/\/ This is where you put your side effect code\n    console.log('Component mounted or updated!');\n    \/\/ You can also return a cleanup function if needed\n    return () =&gt; {\n      console.log('Component will unmount!');\n    };\n  });\n\n  return &lt;div&gt;Hello, World!&lt;\/div&gt;;\n}\n<\/code><\/pre>\n<p>In this example, the <code>useEffect<\/code> hook takes a function as an argument. This function is called the effect function, and it contains the code for your side effect. The effect function is called after every render, both on the initial render and on subsequent updates.<\/p>\n<p>The optional return value of the effect function is a cleanup function. This cleanup function is called before the component unmounts, and it&#8217;s used to clean up any resources that were created in the effect function. In our example, we&#8217;re just logging a message to the console, but in a real-world scenario, you might use the cleanup function to unsubscribe from a subscription or clear a timer.<\/p>\n<p>Now, let&#8217;s talk about when the effect function is called. By default, the effect function is called after every render. This means that if your component re-renders because of a state change or a prop change, the effect function will be called again. Sometimes, this is what you want, but other times, you might want to limit when the effect function is called.<\/p>\n<p>That&#8217;s where the second argument to <code>useEffect<\/code> comes in. This argument is an array of values, and it&#8217;s called the dependency array. If you pass a dependency array as the second argument to <code>useEffect<\/code>, the effect function will only be called if one of the values in the dependency array has changed since the last render.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre><code class=\"language-jsx\">import React, { useState, useEffect } from 'react';\n\nfunction Example() {\n  const [count, setCount] = useState(0);\n\n  useEffect(() =&gt; {\n    document.title = `You clicked ${count} times`;\n  }, [count]);\n\n  return (\n    &lt;div&gt;\n      &lt;p&gt;You clicked {count} times&lt;\/p&gt;\n      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;\n        Click me\n      &lt;\/button&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/code><\/pre>\n<p>In this example, we&#8217;re using <code>useEffect<\/code> to update the document title whenever the <code>count<\/code> state variable changes. We pass <code>[count]<\/code> as the second argument to <code>useEffect<\/code>, which means that the effect function will only be called if <code>count<\/code> has changed since the last render.<\/p>\n<p>If you pass an empty dependency array (<code>[]<\/code>) to <code>useEffect<\/code>, the effect function will only be called on the initial render. This is equivalent to the <code>componentDidMount<\/code> lifecycle method in class components.<\/p>\n<pre><code class=\"language-jsx\">import React, { useEffect } from 'react';\n\nfunction Example() {\n  useEffect(() =&gt; {\n    console.log('Component mounted!');\n    return () =&gt; {\n      console.log('Component will unmount!');\n    };\n  }, []);\n\n  return &lt;div&gt;Hello, World!&lt;\/div&gt;;\n}\n<\/code><\/pre>\n<p>In this example, the effect function is only called on the initial render, and the cleanup function is called before the component unmounts.<\/p>\n<p>Now, let&#8217;s talk about some real-world use cases for <code>useEffect<\/code>. One common use case is data fetching. When you&#8217;re building a web application, you often need to fetch data from an API. You can use <code>useEffect<\/code> to perform this data fetching operation.<\/p>\n<p>Here&#8217;s an example:<\/p>\n<pre><code class=\"language-jsx\">import React, { useState, useEffect } from 'react';\n\nfunction Example() {\n  const [data, setData] = useState(null);\n  const [loading, setLoading] = useState(true);\n\n  useEffect(() =&gt; {\n    async function fetchData() {\n      try {\n        const response = await fetch('https:\/\/api.example.com\/data');\n        const json = await response.json();\n        setData(json);\n        setLoading(false);\n      } catch (error) {\n        console.error('Error fetching data:', error);\n        setLoading(false);\n      }\n    }\n\n    fetchData();\n  }, []);\n\n  if (loading) {\n    return &lt;div&gt;Loading...&lt;\/div&gt;;\n  }\n\n  return (\n    &lt;div&gt;\n      {JSON.stringify(data)}\n    &lt;\/div&gt;\n  );\n}\n<\/code><\/pre>\n<p>In this example, we&#8217;re using <code>useEffect<\/code> to fetch data from an API on the initial render. We set the <code>loading<\/code> state variable to <code>true<\/code> initially, and we update it to <code>false<\/code> once the data has been fetched. We also handle any errors that occur during the data fetching process.<\/p>\n<p>Another common use case for <code>useEffect<\/code> is subscriptions. For example, if you&#8217;re building a real-time application, you might need to subscribe to a WebSocket or an event stream. You can use <code>useEffect<\/code> to manage these subscriptions.<\/p>\n<pre><code class=\"language-jsx\">import React, { useEffect } from 'react';\n\nfunction Example() {\n  useEffect(() =&gt; {\n    const socket = new WebSocket('ws:\/\/example.com\/socket');\n\n    socket.addEventListener('message', (event) =&gt; {\n      console.log('Received message:', event.data);\n    });\n\n    return () =&gt; {\n      socket.close();\n    };\n  }, []);\n\n  return &lt;div&gt;Real-time application&lt;\/div&gt;;\n}\n<\/code><\/pre>\n<p>In this example, we&#8217;re using <code>useEffect<\/code> to create a WebSocket connection on the initial render. We add an event listener to the WebSocket to handle incoming messages, and we return a cleanup function to close the WebSocket connection before the component unmounts.<\/p>\n<p>So, there you have it! That&#8217;s a basic overview of the purpose of the <code>useEffect<\/code> hook. It&#8217;s a powerful tool that allows you to perform side effects in functional components in a clean and concise way. Whether you&#8217;re fetching data, managing subscriptions, or manually changing the DOM, <code>useEffect<\/code> has got you covered.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.gscseatbelt.com\/uploads\/202335941\/small\/nylon-cam-bucklebe1e75ee-5097-443f-a5bd-6a0d1375da1d.jpg\"><\/p>\n<p>If you&#8217;re looking to integrate high &#8211; quality React Hooks into your projects, I&#8217;m here as a Hooks supplier to offer you reliable resources. Our Hooks are designed to simplify your development process and help you build more efficient and maintainable applications. If you&#8217;re interested in procurement or have any questions about our offerings, don&#8217;t hesitate to reach out for a chat. Let&#8217;s work together to take your React applications to the next level!<\/p>\n<p><a href=\"https:\/\/www.gscseatbelt.com\/hooks\/\">Hooks<\/a> References:<\/p>\n<ul>\n<li>React official documentation<\/li>\n<li>React Hooks in Action by Michael Chan<\/li>\n<\/ul>\n<hr>\n<p><a href=\"https:\/\/www.gscseatbelt.com\/\">Good Success Corp.<\/a><br \/>Good Success Corp. is one of the leading hooks manufacturers and suppliers in China. We warmly welcome you to buy cheap hooks for sale here from our factory. All customized products are with high quality and competitive price. Contact us for more details.<br \/>Address: NO.54, CHANG MA ROAD, CHANG HUA 500051, TAIWAN, R.O.C.<br \/>E-mail: sales@gscbelt.com<br \/>WebSite: <a href=\"https:\/\/www.gscseatbelt.com\/\">https:\/\/www.gscseatbelt.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey there, fellow devs! I&#8217;m a supplier of Hooks, and I&#8217;ve been getting a lot of &hellip; <a title=\"What is the purpose of the useEffect hook?\" class=\"hm-read-more\" href=\"http:\/\/www.shubhsutra.com\/blog\/2026\/09\/14\/what-is-the-purpose-of-the-useeffect-hook-4d1f-cf0c43\/\"><span class=\"screen-reader-text\">What is the purpose of the useEffect hook?<\/span>Read more<\/a><\/p>\n","protected":false},"author":943,"featured_media":3388,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3351],"class_list":["post-3388","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-hooks-4dfa-d09366"],"_links":{"self":[{"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/posts\/3388","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/users\/943"}],"replies":[{"embeddable":true,"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/comments?post=3388"}],"version-history":[{"count":0,"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/posts\/3388\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/posts\/3388"}],"wp:attachment":[{"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/media?parent=3388"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/categories?post=3388"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.shubhsutra.com\/blog\/wp-json\/wp\/v2\/tags?post=3388"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}