Do You Really Know UseEffect?
Tags: react, javascript, functions, frontend
Published: 2022-02-24 09:25:09

<p>React 16.8 comes bearing with gifts such as Hooks and React community couldn't be happier and why won't they be as Hooks gives the developer to create functional components with the power of Class components.</p>
<h2 id="some-of-the-famous-hooks-are">Some of the famous hooks are</h2>
<ul>
<li>State Hook </li>
<li>Effect Hook</li>
<li>Context Hook and so on.</li>
</ul>
<p>But do you really understand them? Let's talk about the <code>Effect Hook</code> in this article and we will try to understand when and how to use them.</p>
<h2 id="using-effect-hooks">Using Effect Hooks</h2>
<p>As mentioned in the document </p>
<blockquote>
<p>The Effect Hook lets you perform side effects in function components</p>
</blockquote>
<p>let's talk about what are these side effects? Imagine you are making a web app where you are needed to <code>fetch</code> some data from the server or set up a subscription using <code>WebRTC</code> these are some examples of side effects.</p>
<p>In the above example where you are fetching some data from API does not need cleanup means you can execute the function and forget about it. But the later one where you are subscribing needs the cleanup where you have to write some addition line so that every time your component unmounts the cleanup happens and your resources are not wasted up.</p>
<h3 id="lets-talk-about-the-effects-without-cleanup">let's talk about the Effects without Cleanup</h3>
<p>For using Effects in our React functional component we use <code>useEffect</code> Hook</p>
<pre><code>  useEffect (<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Something Happened"</span>)
   })
</code></pre><p>Now <code>useEffect</code> accepts two arguments one is a callback function and one is an array.</p>
<h3 id="case-1">Case 1</h3>
<p>In this, we won't pass the second argument, and let's see what happens.</p>
<pre><code>useEffect (<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Something Changed"</span>)
   })
</code></pre><p><strong>Result:</strong> Every time our components render the <code>useEffect</code> Hook gonna run and we can see the text <code>Something Changed</code> in the console.</p>
<h3 id="case-2">Case 2</h3>
<p>In this, we will pass an empty array as the second argument <code>[ ]</code>, and let's see what happens.</p>
<pre><code>useEffect (<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Only Once"</span>)
   },[ ])
</code></pre><p><strong>Result:</strong> This time <code>useEffect</code> Hook gonna run on mounting/ unmounting of our component and we can see the text <code>Only Once</code> in the console for only one time.</p>
<h3 id="case-3">Case 3</h3>
<p>In this, we will pass an array containing a state value as the second argument <code>[ someState]</code>, and let's see what happens. </p>
<pre><code> const [someState , setSomeState] = useState();

 useEffect (<span class="hljs-function"><span class="hljs-params">()</span>=&gt;</span>{
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"State Changed"</span>)
   },[someState ]);
</code></pre><p><strong>Result:</strong> This time <code>useEffect</code> Hook gonna run when the value of the <code>someState</code> changes of our component and we can see the text <code>State Changed</code> in the console when we change the state.</p>
<h2 id="enough-theory-lets-see-some-code-now">Enough theory let's see some code now.</h2>
<iframe src="https://codesandbox.io/embed/cases-of-useeffect-nmpug?fontsize=14&amp;hidenavigation=1&amp;theme=dark" style="width:100%;height:500px;border:0;border-radius:4px;overflow:hidden" sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe>


<p>Above all cases are used in this Play around with the code to get to know more about the <code>useEffect</code>.</p>
<h3 id="now-lets-talk-about-the-effects-with-cleanup">Now let's talk about the Effects with Cleanup</h3>
<p>These are tricky ones, we already have seen the examples of hooks with clean up but let's see the code part which is provided in an official document, and try to understand it.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">FriendStatus</span>(<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">const</span> [isOnline, setIsOnline] = useState(<span class="hljs-literal">null</span>);

  useEffect(() =&gt; {
   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleStatusChange</span>(<span class="hljs-params">status</span>) </span>{
      setIsOnline(status.isOnline);
    }
    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    <span class="hljs-comment">// Specify how to clean up after this effect:</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cleanup</span>(<span class="hljs-params"></span>) </span>{
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
   });

   <span class="hljs-keyword">if</span> (isOnline === <span class="hljs-literal">null</span>) {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Loading...'</span>;
   }
   <span class="hljs-keyword">return</span> isOnline ? <span class="hljs-string">'Online'</span> : <span class="hljs-string">'Offline'</span>;
  }
</code></pre><p>As you can see we are returning a function this is called <code>clean up function</code>. This is an optional cleanup mechanism for effects so that when your component had been unmounted from the DOM tree it also unsubscribes to the <code>FriendStatus</code>. As we already know that effects run with every render so this is important to clean up from the previous render also.</p>
<h2 id="lets-wrap-up">Let's Wrap up</h2>
<p>So, we learned three ways how useEffect can be used and we also learned that some effects need cleanups while others don't.</p>
<p>If you learned something or liked my content follow me on Twitter.</p>
<p><a href="https://twitter.com/theysaymaurya?ref_src=twsrc%5Etfw" class="twitter-follow-button">Follow @theysaymaurya</a></p>
<p>or </p>
<p>follow me on Hashnode <a class="user-mention" href="https://hashnode.com/@theashishmaurya">Ashish maurya</a></p>
</br><p style="color:#808080;">This blog is posted using <a href="www.blogtiple.com">Blogtiple</a></p>