<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gareth D on Medium]]></title>
        <description><![CDATA[Stories by Gareth D on Medium]]></description>
        <link>https://medium.com/@garethdavisrogers?source=rss-d0baabbc7d8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6fGkaWN4EMDjj8JkX5vcqQ.png</url>
            <title>Stories by Gareth D on Medium</title>
            <link>https://medium.com/@garethdavisrogers?source=rss-d0baabbc7d8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:35:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@garethdavisrogers/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Using setInterval and clearInterval with React Hooks]]></title>
            <link>https://medium.com/@garethdavisrogers/using-setinterval-and-clearinterval-with-react-hooks-7fcf26dc8fdb?source=rss-d0baabbc7d8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fcf26dc8fdb</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[setinterval]]></category>
            <category><![CDATA[clearinterval]]></category>
            <category><![CDATA[useeffect]]></category>
            <dc:creator><![CDATA[Gareth D]]></dc:creator>
            <pubDate>Sat, 16 Oct 2021 18:10:31 GMT</pubDate>
            <atom:updated>2021-10-16T18:10:31.090Z</atom:updated>
            <content:encoded><![CDATA[<p>We are going to practice our react hooks today by creating a simple bathtub app. The app has a ‘bathtub’ with 5 levels of water. There are two buttons. The first button fills the tub when clicked until the bathtub is full. The second button drains the tub until empty. The tub fills and drains one level at a time every two seconds. Each level will be 20px high. The application will also have a counter displaying the current water level in the tub.</p><p>We will start with App.js:</p><pre>import React from &quot;react&quot;;</pre><pre>const App = () =&gt; {</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Water Counter: waterLevelHere&lt;/h1&gt;<br>      &lt;div id=&quot;bathtub&quot;&gt;&lt;/div&gt;<br>      &lt;div id=&quot;buttons&quot;&gt;<br>        &lt;button&gt;<br>          increaseWaterLevel<br>        &lt;/button&gt;<br>        &lt;button&gt;<br>          decreaseWaterLevel<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>Start by importing useState and useEffect from react, initializing an empty useEffect function, and creating a waterLevel hook initialized to zero and an actionType hook to pass ‘actions’ to our useEffect function.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;</pre><pre>const App = () =&gt; {<br>  const [waterLevel, setWaterLevel] = useState(0);<br>  const [actionType, setActionType] = useState();</pre><pre>  useEffect(()=&gt; {return});</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Water Counter: {waterLevel}&lt;/h1&gt;<br>      &lt;div id=&quot;bathtub&quot;&gt;&lt;/div&gt;<br>      &lt;div id=&quot;buttons&quot;&gt;<br>        &lt;button&gt;<br>          increaseWaterLevel<br>        &lt;/button&gt;<br>        &lt;button&gt;<br>          decreaseWaterLevel<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>Next, let’s create an interval with setInterval in the useEffect function that checks the actionType to know whether to increase or decrease. We pass in the waterLevel and actionType as the second argument of useEffect. We will also don’t want the water level to go over 5 or under 0, so we set these limits in our logic. setWaterLevel will take the prevWaterLevel as a parameter and return the incremented water level. We also set a very simple onClick function to our buttons to set the corresponding action type. Set the second argument of setInterval to 2000 milliseconds.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br>import Water from &quot;./Water&quot;;</pre><pre>const App = () =&gt; {<br>  const [waterLevel, setWaterLevel] = useState(0);<br>  const [actionType, setActionType] = useState();</pre><pre>useEffect(() =&gt; {<br>    setInterval(() =&gt; {<br>      if (actionType === &quot;increase&quot; &amp;&amp; waterLevel &lt; 5) {<br>        setWaterLevel((prevWaterLevel) =&gt; prevWaterLevel + 1);<br>      }<br>      if (actionType === &quot;decrease&quot; &amp;&amp; waterLevel &gt; 0) {<br>        setWaterLevel((prevWaterLevel) =&gt; prevWaterLevel - 1);<br>      }<br>    }, 2000);<br>  }, [actionType, waterLevel]);</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Water Counter: {waterLevel}&lt;/h1&gt;<br>      &lt;div id=&quot;bathtub&quot;&gt;<br>        &lt;Water waterLevel={waterLevel} /&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;buttons&quot;&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setActionType(&quot;increase&quot;);<br>          }}<br>        &gt;<br>          increaseWaterLevel<br>        &lt;/button&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setActionType(&quot;decrease&quot;);<br>          }}<br>        &gt;<br>          decreaseWaterLevel<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>Uh-oh. On clicking either button, all the useEffect functions are running concurrently and ignore the waterLevel limits we set. What’s going on?! We need a cleanup function in our useEffect function to stop the current interval. Currently setInterval is running once, then twice, then three times ad infinitum. The interval will need to be cleared each time useEffect is run for the function to receive both the updated waterLevel state and to stop the current function from running when the bathtub is full, empty, or alternating between filling the tub and draining it. We can do this by storing setInterval in a constant, then returning an anonymous cleanup function that runs the clearInterval method on our new interval constant.</p><pre>import React, { useState, useEffect } from &quot;react&quot;;</pre><pre>const App = () =&gt; {<br>  const [waterLevel, setWaterLevel] = useState(0);<br>  const [actionType, setActionType] = useState();</pre><pre>useEffect(() =&gt; {<br>    const interval = setInterval(() =&gt; {<br>      if (actionType === &quot;increase&quot; &amp;&amp; waterLevel &lt; 5) {<br>        setWaterLevel((prevWaterLevel) =&gt; prevWaterLevel + 1);<br>      }<br>      if (actionType === &quot;decrease&quot; &amp;&amp; waterLevel &gt; 0) {<br>        setWaterLevel((prevWaterLevel) =&gt; prevWaterLevel - 1);<br>      }<br>    }, 2000);<br>    return () =&gt; clearInterval(interval);<br>  }, [actionType, waterLevel]);</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Water Counter: {waterLevel}&lt;/h1&gt;<br>      &lt;div id=&quot;bathtub&quot;&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;buttons&quot;&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setActionType(&quot;increase&quot;);<br>          }}<br>        &gt;<br>          increaseWaterLevel<br>        &lt;/button&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setActionType(&quot;decrease&quot;);<br>          }}<br>        &gt;<br>          decreaseWaterLevel<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>Works much better! Now the counter and state are working we are almost done. Lastly we are going to add a basic visual for the water with a Water component. The component will map one 20px high water unit for each waterLevel it receives as props.</p><pre>import React from &quot;react&quot;;</pre><pre>const Water = ({ waterLevel }) =&gt; {<br>  let waterMap = [];<br>  for (let i = 0; i &lt; waterLevel; i++) {<br>    waterMap.push(<br>      &lt;div className=&quot;water&quot; key={`water${i}`}&gt;<br>        {i}<br>      &lt;/div&gt;<br>    );<br>  }<br>  return &lt;div&gt;{waterMap}&lt;/div&gt;;<br>};</pre><pre>export default Water;</pre><p>Then import it into your main app.</p><pre>const [waterLevel, setWaterLevel] = useState(0);<br>  const [actionType, setActionType] = useState();</pre><pre>useEffect(() =&gt; {<br>    const interval = setInterval(() =&gt; {<br>      if (actionType === &quot;increase&quot; &amp;&amp; waterLevel &lt; 5) {<br>        setWaterLevel((prevWaterLevel) =&gt; prevWaterLevel + 1);<br>      }<br>      if (actionType === &quot;decrease&quot; &amp;&amp; waterLevel &gt; 0) {<br>        setWaterLevel((prevWaterLevel) =&gt; prevWaterLevel - 1);<br>      }<br>    }, 2000);<br>    return () =&gt; clearInterval(interval);<br>  }, [actionType, waterLevel]);</pre><pre>return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Water Counter: {waterLevel}&lt;/h1&gt;<br>      &lt;div id=&quot;bathtub&quot;&gt;<br>        &lt;Water waterLevel={waterLevel} /&gt;<br>      &lt;/div&gt;<br>      &lt;div id=&quot;buttons&quot;&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setActionType(&quot;increase&quot;);<br>          }}<br>        &gt;<br>          increaseWaterLevel<br>        &lt;/button&gt;<br>        &lt;button<br>          onClick={() =&gt; {<br>            setActionType(&quot;decrease&quot;);<br>          }}<br>        &gt;<br>          decreaseWaterLevel<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>You can probably create much better CSS but this will work if you just want a visual…</p><pre>body {<br>  display: flex;<br>  flex-direction: column;<br>  justify-content: center;<br>  align-items: center;<br>  background: lightgray;<br>}<br>#bathtub {<br>  width: 90vw;<br>  height: 50vh;<br>  background: whitesmoke;<br>  border-radius: 5px;<br>  display: flex;<br>  flex-direction: column-reverse;<br>  padding: 5vw;<br>}</pre><pre>#buttons {<br>  display: flex;<br>  flex-direction: row;<br>  justify-content: space-around;<br>}</pre><pre>.water {<br>  height: 20px;<br>  background: blue;<br>  color: blue;<br>}</pre><pre>button {<br>  height: 200px;<br>  padding: 5px;<br>}</pre><p>Alright, this was my first Medium article so go easy on me! I hope this look at setInterval and clearInterval inside the useEffect function has been helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fcf26dc8fdb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>