React - How to implement useEffect hook in your application
Tags: react, programming, javascript, webdev
Published: 2023-02-09 09:22:04


The useEffect hook is a powerful feature in React that allows you to synchronize a component with an external system. It is a hook that lets you tell React what to do after render.

Here is a basic example that demonstrates how to use the useEffect hook:

<pre>
 <code id="htmlViewer" style="color:rgb(255, 255, 255); font-weight:400;background-color:rgb(51, 51, 51);background:rgb(51, 51, 51);display:block;padding: .5em;"><span style="color:rgb(252, 194, 140); font-weight:400;">import</span> <span class="hljs-title class_">React</span>, { useState, useEffect } <span style="color:rgb(252, 194, 140); font-weight:400;">from</span> <span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;react&#x27;</span>;

<span style="color:rgb(252, 194, 140); font-weight:400;">const</span> <span class="hljs-title function_">Example</span> = (<span style="color:rgb(255, 255, 255); font-weight:400;"></span>) =&gt; {
  <span style="color:rgb(252, 194, 140); font-weight:400;">const</span> [count, setCount] = <span class="hljs-title function_">useState</span>(<span style="color:rgb(211, 99, 99); font-weight:400;">0</span>);

  <span class="hljs-title function_">useEffect</span>(<span style="color:rgb(255, 255, 255); font-weight:400;">() =&gt;</span> {
    <span class="hljs-variable language_">document</span>.<span style="color:rgb(255, 255, 255); font-weight:400;">title</span> = <span style="color:rgb(162, 252, 162); font-weight:400;">`Count: <span style="color:rgb(162, 252, 162); font-weight:400;">${count}</span>`</span>;
  }, [count]);

  <span style="color:rgb(252, 194, 140); font-weight:400;">return</span> (
    <span style="color:rgb(255, 255, 255); font-weight:400;"><span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span style="color:rgb(162, 252, 162); font-weight:400;">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span style="color:rgb(252, 194, 140); font-weight:400;">export</span> <span style="color:rgb(252, 194, 140); font-weight:400;">default</span> <span class="hljs-title class_">Example</span>;</code></pre>


In this example, we are using the useState hook to manage the state of our component. The state count is set to 0 initially.

We then use the useEffect hook to update the document title whenever the count changes. The useEffect hook takes two arguments: a callback function and an array of dependencies. The callback function is the code that we want to run after render, and the array of dependencies is a list of values that we want to watch for changes. In this case, we only want to run the effect when count changes, so we pass [count] as the second argument.

Every time the component re-renders, React will compare the values in the dependency array to their previous values. If any of the values have changed, the effect will run again. If the values have not changed, the effect will not run. This is how React knows when to re-run an effect and when to skip it.

This is just a simple example, but you can use the useEffect hook to perform all sorts of complex logic in your React components, such as fetching data from an API, setting up and cleaning up subscriptions, and more.

## **USE CASES** 
Here are a few more examples to illustrate different use cases for the useEffect hook:

**Fetching data from an API**

<pre>
 <code id="htmlViewer" style="color:rgb(255, 255, 255); font-weight:400;background-color:rgb(51, 51, 51);background:rgb(51, 51, 51);display:block;padding: .5em;"><span style="color:rgb(252, 194, 140); font-weight:400;">import</span> <span class="hljs-title class_">React</span>, { useState, useEffect } <span style="color:rgb(252, 194, 140); font-weight:400;">from</span> <span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;react&#x27;</span>;

<span style="color:rgb(252, 194, 140); font-weight:400;">const</span> <span class="hljs-title function_">Example</span> = (<span style="color:rgb(255, 255, 255); font-weight:400;"></span>) =&gt; {
  <span style="color:rgb(252, 194, 140); font-weight:400;">const</span> [data, setData] = <span class="hljs-title function_">useState</span>(<span style="color:rgb(252, 194, 140); font-weight:400;">null</span>);

  <span class="hljs-title function_">useEffect</span>(<span style="color:rgb(255, 255, 255); font-weight:400;">() =&gt;</span> {
    <span class="hljs-title function_">fetch</span>(<span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;https://jsonplaceholder.typicode.com/posts&#x27;</span>)
      .<span class="hljs-title function_">then</span>(<span style="color:rgb(255, 255, 255); font-weight:400;"><span style="color:rgb(255, 255, 255); font-weight:400;">response</span> =&gt;</span> response.<span class="hljs-title function_">json</span>())
      .<span class="hljs-title function_">then</span>(<span style="color:rgb(255, 255, 255); font-weight:400;"><span style="color:rgb(255, 255, 255); font-weight:400;">json</span> =&gt;</span> <span class="hljs-title function_">setData</span>(json));
  }, []);

  <span style="color:rgb(252, 194, 140); font-weight:400;">return</span> (
    <span style="color:rgb(255, 255, 255); font-weight:400;"><span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">div</span>&gt;</span>
      {data ? (
        data.map(post =&gt; (
          <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">key</span>=<span style="color:rgb(162, 252, 162); font-weight:400;">{post.id}</span>&gt;</span>
            <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">h2</span>&gt;</span>{post.title}<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">p</span>&gt;</span>{post.body}<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">p</span>&gt;</span>
          <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">div</span>&gt;</span>
        ))
      ) : (
        <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">p</span>&gt;</span>Loading...<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">p</span>&gt;</span>
      )}
    <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span style="color:rgb(252, 194, 140); font-weight:400;">export</span> <span style="color:rgb(252, 194, 140); font-weight:400;">default</span> <span class="hljs-title class_">Example</span>;
</code></pre>

**Setting up and cleaning up a subscription**

<pre>
 <code id="htmlViewer" style="color:rgb(255, 255, 255); font-weight:400;background-color:rgb(51, 51, 51);background:rgb(51, 51, 51);display:block;padding: .5em;"><span style="color:rgb(252, 194, 140); font-weight:400;">import</span> <span class="hljs-title class_">React</span>, { useState, useEffect } <span style="color:rgb(252, 194, 140); font-weight:400;">from</span> <span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;react&#x27;</span>;

<span style="color:rgb(252, 194, 140); font-weight:400;">const</span> <span class="hljs-title function_">Example</span> = (<span style="color:rgb(255, 255, 255); font-weight:400;"></span>) =&gt; {
  <span style="color:rgb(252, 194, 140); font-weight:400;">const</span> [width, setWidth] = <span class="hljs-title function_">useState</span>(<span class="hljs-variable language_">window</span>.<span style="color:rgb(255, 255, 255); font-weight:400;">innerWidth</span>);

  <span class="hljs-title function_">useEffect</span>(<span style="color:rgb(255, 255, 255); font-weight:400;">() =&gt;</span> {
    <span style="color:rgb(252, 194, 140); font-weight:400;">const</span> <span class="hljs-title function_">handleResize</span> = (<span style="color:rgb(255, 255, 255); font-weight:400;"></span>) =&gt; <span class="hljs-title function_">setWidth</span>(<span class="hljs-variable language_">window</span>.<span style="color:rgb(255, 255, 255); font-weight:400;">innerWidth</span>);
    <span class="hljs-variable language_">window</span>.<span class="hljs-title function_">addEventListener</span>(<span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;resize&#x27;</span>, handleResize);
    <span style="color:rgb(252, 194, 140); font-weight:400;">return</span> <span style="color:rgb(255, 255, 255); font-weight:400;">() =&gt;</span> <span class="hljs-variable language_">window</span>.<span class="hljs-title function_">removeEventListener</span>(<span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;resize&#x27;</span>, handleResize);
  }, []);

  <span style="color:rgb(252, 194, 140); font-weight:400;">return</span> (
    <span style="color:rgb(255, 255, 255); font-weight:400;"><span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">p</span>&gt;</span>Window width: {width}<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span style="color:rgb(252, 194, 140); font-weight:400;">export</span> <span style="color:rgb(252, 194, 140); font-weight:400;">default</span> <span class="hljs-title class_">Example</span>;
</code></pre>

In this example, we are using the useEffect hook to set up and clean up a subscription to the resize event of the window object. The effect runs every time the component re-renders, but we don't need to do anything in the dependency array, because the effect does not depend on any values from props or state. The return value of the effect function is a cleanup function that removes the event listener when the component unmounts.

**Updating a value based on a previous value**

<pre>
 <code id="htmlViewer" style="color:rgb(255, 255, 255); font-weight:400;background-color:rgb(51, 51, 51);background:rgb(51, 51, 51);display:block;padding: .5em;"><span style="color:rgb(252, 194, 140); font-weight:400;">import</span> <span class="hljs-title class_">React</span>, { useState, useEffect } <span style="color:rgb(252, 194, 140); font-weight:400;">from</span> <span style="color:rgb(162, 252, 162); font-weight:400;">&#x27;react&#x27;</span>;

<span style="color:rgb(252, 194, 140); font-weight:400;">const</span> <span class="hljs-title function_">Example</span> = (<span style="color:rgb(255, 255, 255); font-weight:400;"></span>) =&gt; {
  <span style="color:rgb(252, 194, 140); font-weight:400;">const</span> [count, setCount] = <span class="hljs-title function_">useState</span>(<span style="color:rgb(211, 99, 99); font-weight:400;">0</span>);
  <span style="color:rgb(252, 194, 140); font-weight:400;">const</span> [doubleCount, setDoubleCount] = <span class="hljs-title function_">useState</span>(<span style="color:rgb(211, 99, 99); font-weight:400;">0</span>);

  <span class="hljs-title function_">useEffect</span>(<span style="color:rgb(255, 255, 255); font-weight:400;">() =&gt;</span> {
    <span class="hljs-title function_">setDoubleCount</span>(count * <span style="color:rgb(211, 99, 99); font-weight:400;">2</span>);
  }, [count]);

  <span style="color:rgb(252, 194, 140); font-weight:400;">return</span> (
    <span style="color:rgb(255, 255, 255); font-weight:400;"><span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">p</span>&gt;</span>Count: {count}<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">p</span>&gt;</span>Double Count: {doubleCount}<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span style="color:rgb(162, 252, 162); font-weight:400;">{()</span> =&gt;</span> setCount(count + 1)}&gt;Increment<span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span style="color:rgb(98, 200, 243); font-weight:400;">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  );
};

<span style="color:rgb(252, 194, 140); font-weight:400;">export</span> <span style="color:rgb(252, 194, 140); font-weight:400;">default</span> <span class="hljs-title class_">Example</span>;
</code></pre>

In this example, we are using the useEffect hook to update a value doubleCount based on a previous value count. The effect runs whenever count changes, and we pass [count]

**Happy coding! 😊**