<?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 Tasos Kakouris on Medium]]></title>
        <description><![CDATA[Stories by Tasos Kakouris on Medium]]></description>
        <link>https://medium.com/@tasoskakour?source=rss-7cc6cee90c71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-pVR7yh7U60NrFpSKedgow.jpeg</url>
            <title>Stories by Tasos Kakouris on Medium</title>
            <link>https://medium.com/@tasoskakour?source=rss-7cc6cee90c71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 07:45:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tasoskakour/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[Build a React-Router Dialog]]></title>
            <link>https://medium.com/@tasoskakour/build-a-react-router-dialog-f3de3a98922d?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3de3a98922d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 11:15:44 GMT</pubDate>
            <atom:updated>2022-12-18T11:15:44.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*gf2SQQkecCVTz2_a.png" /></figure><p><em>This article, along with others, are originally published at my personal website: </em><a href="https://tasoskakour.com/"><em>https://tasoskakour.com</em></a>, <em>make sure to check them out :-).</em></p><h3>What is a Dialog?</h3><p>According to <a href="https://m3.material.io/components/dialogs/overview">Material Design</a>, Dialogs (also known as Modals), can require an action, communicate information, or help users accomplish a task.</p><p>Dialogs allow us, to <strong>focus</strong> on a content without losing the <strong>background</strong> contextual information associated with it.</p><h3>Instagram Example</h3><p>Imagine you’re on Instagram scrolling a list of posts and you click on a post to see more details about it. Traditionally this could be implemented by just <strong>navigating</strong> to another page, but this — at times — does not feel very <strong>user-friendly</strong>.</p><p>What can be done instead, is to <strong>show a Dialog</strong> with the details of this post, <strong>without leaving</strong> the page preserving the list of posts in the background. Then, the user can just close the post and move on with the list, clicking on another post and so on.</p><p>Look at what Instagram does with their posts and how user-friendly it feels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*XwU2nH324rnyUyc2.gif" /></figure><h3>A Naive Attempt</h3><p>We could assume that we could implement the functionality above with writing something like this:</p><pre>const App = () =&gt; {<br>  const [selectedPost, setSelectedPost] = useState(null);<br><br>  return &lt;div&gt;<br>    &lt;ListOfPosts&gt;<br>      {posts.map(post =&gt; &lt;Post post={post} onClick={() =&gt; setSelectedPost(post)}/&gt;)}<br>    &lt;/ListOfPosts&gt;<br>    &lt;PostDetailsDialog selectedPost={selectedPost}&gt;<br>  &lt;div/&gt;<br>}</pre><p>Looks like pretty straight-forward right?</p><p><strong>Or… maybe not?</strong></p><p>The above code could definitely work in general, but we’re missing one very <strong>important</strong> thing.</p><p>What about the <strong>page url</strong>? With an implementation like the above, the url of the page <strong>does not change</strong> each time a Post is shown.</p><p>And from a UI/UX perspective, it’s always for the best if the page-url follows the <strong>user journey</strong> of our app.</p><p>Furthermore, by <strong>changing</strong> the page url when the PostDetailsDialog is shown and by keeping a unique url for each post, we also allow the user to easily share the post by just <strong>sharing</strong> the URL that is present at that moment on their browser!</p><p>Now, take a look at how Instagram behaves, when we <strong>share</strong> the url of a post: <a href="https://www.instagram.com/p/CfeYvQOD1z-/">https://www.instagram.com/p/CfeYvQOD1z-/</a></p><p>The post shows up in a <strong>new page</strong> without being inside a Dialog and without showing the list of posts in the background. It just <strong>focuses</strong> on that shared post.</p><h3>Requirements</h3><p>These are the requirements that need to be met in order to achieve the aforementioned functionality:</p><ol><li>Show a <strong>Dialog</strong> for each post clicked</li><li><strong>Page url</strong> must change and must be unique for each post</li><li>When a user visits a Post from a shared URL, the post must be shown normally in a <strong>new page</strong> (without being inside a Dialog)</li></ol><p>We can use <strong>React Router</strong> combined with a <strong>Dialog</strong> component in order to satisfy the requirements above.</p><h3>Code &amp; Implementation</h3><p>You can find the full code here: <a href="https://codesandbox.io/s/react-router-modal-gallery-qs44n1">https://codesandbox.io/s/react-router-modal-gallery-qs44n1</a></p><p><strong>What we will achieve (notice how the URL changes)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/0*riFbSFq_IRrdJsPt.gif" /></figure><p><strong>And when we visit the image from a shared url the post opens in an new page:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/0*oDNh7oh_FrpqB8Jr.gif" /></figure><h3>Coding time</h3><p>The key thing here, is that we are going to utilize the location prop of the Routes component provided by react-router-dom.</p><p>Basically, by using the location prop we can &quot;override&quot; the actual location of where our app is at that moment. The backgroundLocation (you can name the variable whatever you like) comes from the location state of our app.</p><p>We then check if the backgroundLocation is set, and if it is, it means that we must show a Dialog and preserve the background location, thus we apply the location prop at the Routes component.</p><p>Otherwise, if the backgroundLocation is not set, then the location prop just takes the default value of location and our app follows the &quot;normal&quot; flow - that means that our Post will be rendered as is inside the page (and not inside a Dialog).</p><pre>// App.js<br>import { Box, Container, Divider, Typography } from &quot;@mui/material&quot;;<br>import { Outlet, Route, Routes, useLocation } from &quot;react-router-dom&quot;;<br>import About from &quot;./About&quot;;<br>import ImageList from &quot;./ImageList&quot;;<br>import ImageView from &quot;./ImageView&quot;;<br>import ImageModal from &quot;./ImageModal&quot;;<br>import Home from &quot;./Home&quot;;<br><br>const Layout = () =&gt; (<br>  &lt;Container maxWidth=&quot;md&quot;&gt;<br>    &lt;Box mb={2}&gt;<br>      &lt;Typography variant=&quot;h4&quot;&gt;Application Demo&lt;/Typography&gt;<br>      &lt;Divider /&gt;<br>    &lt;/Box&gt;<br>    &lt;Outlet /&gt;<br>  &lt;/Container&gt;<br>);<br><br>const App = () =&gt; {<br>  const location = useLocation();<br>  const { state } = location;<br><br>  return (<br>    &lt;div&gt;<br>      &lt;Routes location={state?.backgroundLocation || location}&gt;<br>        &lt;Route path=&quot;/&quot; element={&lt;Layout /&gt;}&gt;<br>          &lt;Route index element={&lt;Home /&gt;} /&gt;<br>          &lt;Route path=&quot;/about&quot; element={&lt;About /&gt;} /&gt;<br>          &lt;Route path=&quot;/images&quot; element={&lt;ImageList /&gt;} /&gt;<br>          &lt;Route path=&quot;/images/:id&quot; element={&lt;ImageView /&gt;} /&gt;<br>        &lt;/Route&gt;<br>      &lt;/Routes&gt;<br><br>      {/* Show the modal when a `backgroundLocation` is set */}<br>      {state?.backgroundLocation &amp;&amp; (<br>        &lt;Routes&gt;<br>          &lt;Route path=&quot;/images/:id&quot; element={&lt;ImageModal /&gt;} /&gt;<br>        &lt;/Routes&gt;<br>      )}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default App;</pre><p>Take a look at how we can set the state alongside the url in a Link component, when the user clicks on a image. It&#39;s like saying to our app: &quot;Hey, the user clicked on an image, so we must show the image inside a Dialog and preserve the background location&quot;.</p><pre>// ImageList.js<br>import { Box, Grid, Stack, Typography } from &quot;@mui/material&quot;;<br>import React, { useState } from &quot;react&quot;;<br>import { Link, useLocation } from &quot;react-router-dom&quot;;<br>import { IMAGES } from &quot;./images&quot;;<br><br>const ImageBox = ({ image, location }) =&gt; {<br>  const [hovered, setHovered] = useState(false);<br>  const { id, src } = image;<br><br>  return (<br>    &lt;Box width=&quot;100%&quot; position=&quot;relative&quot;&gt;<br>      &lt;Link to={`/images/${id}`} state={{ backgroundLocation: location }}&gt;<br>        &lt;Box<br>          onMouseEnter={() =&gt; setHovered(true)}<br>          component=&quot;img&quot;<br>          src={src}<br>          alt=&quot;post&quot;<br>          width=&quot;100%&quot;<br>          height=&quot;250px&quot;<br>        /&gt;<br>        {hovered &amp;&amp; (<br>          &lt;Box<br>            onMouseLeave={() =&gt; setHovered(false)}<br>            position=&quot;absolute&quot;<br>            top={0}<br>            left={0}<br>            bottom={0}<br>            right={0}<br>            width=&quot;100%&quot;<br>            height=&quot;250px&quot;<br>            bgcolor=&quot;rgba(0, 0, 0, 0.3)&quot;<br>            // sx={{ opacity: 0.6 }}<br>          /&gt;<br>        )}<br>      &lt;/Link&gt;<br>    &lt;/Box&gt;<br>  );<br>};<br><br>const ImageList = () =&gt; {<br>  let location = useLocation();<br><br>  return (<br>    &lt;Grid container spacing={2} alignItems=&quot;center&quot; justifyContent=&quot;center&quot;&gt;<br>      {IMAGES.map(({ title, src, id }, index) =&gt; (<br>        &lt;Grid key={id} item sm={4}&gt;<br>          &lt;ImageBox image={{ title, src, id }} location={location} /&gt;<br>        &lt;/Grid&gt;<br>      ))}<br>    &lt;/Grid&gt;<br>  );<br>};<br><br>export default ImageList;</pre><pre>// ImageModal.js<br>import { useNavigate, useParams } from &quot;react-router-dom&quot;;<br>import ImageView from &quot;./ImageView&quot;;<br>import { getImage } from &quot;./images&quot;;<br>import { Button, Dialog, DialogActions, DialogContent } from &quot;@mui/material&quot;;<br><br>const ImageModal = () =&gt; {<br>  let navigate = useNavigate();<br>  let { id } = useParams();<br>  let image = getImage(id);<br><br>  if (!image) return null;<br><br>  const handleClose = () =&gt; {<br>    navigate(-1);<br>  };<br><br>  return (<br>    &lt;Dialog open onClose={handleClose}&gt;<br>      &lt;DialogContent&gt;<br>        &lt;ImageView /&gt;<br>      &lt;/DialogContent&gt;<br>      &lt;DialogActions&gt;<br>        &lt;Button onClick={handleClose}&gt;Close&lt;/Button&gt;<br>      &lt;/DialogActions&gt;<br>    &lt;/Dialog&gt;<br>  );<br>};<br><br>export default ImageModal;</pre><pre>// ImageView.js<br>import { ArrowBackIos } from &quot;@mui/icons-material&quot;;<br>import { Button, Link, Stack, Typography, Box } from &quot;@mui/material&quot;;<br>import React from &quot;react&quot;;<br>import { useLocation, useParams, Link as RouterLink } from &quot;react-router-dom&quot;;<br>import { getImage } from &quot;./images&quot;;<br><br>const ImageView = () =&gt; {<br>  const { state } = useLocation();<br>  const { id } = useParams();<br>  const image = getImage(id);<br>  const { src, title } = image;<br><br>  const isInsideModal = state?.backgroundLocation;<br><br>  return (<br>    &lt;div&gt;<br>      {!isInsideModal &amp;&amp; (<br>        &lt;Link component={RouterLink} to=&quot;/images&quot; underline=&quot;none&quot;&gt;<br>          &lt;Button startIcon={&lt;ArrowBackIos /&gt;} variant=&quot;text&quot;&gt;<br>            Back to Images<br>          &lt;/Button&gt;<br>        &lt;/Link&gt;<br>      )}<br>      &lt;Box display=&quot;flex&quot; justifyContent=&quot;center&quot;&gt;<br>        &lt;Stack direction=&quot;column&quot; spacing={1}&gt;<br>          &lt;Typography variant=&quot;h5&quot; fontWeight={600}&gt;<br>            {title}<br>          &lt;/Typography&gt;<br><br>          &lt;Box component=&quot;img&quot; sx={{ width: &quot;400px&quot; }} src={src} alt=&quot;dog&quot; /&gt;<br>        &lt;/Stack&gt;<br>      &lt;/Box&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ImageView;</pre><h3>The End</h3><p>I hope you found the article informative.</p><p>See you soon! 🙂</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-router-dialog"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3de3a98922d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implement “useUndoRedo” React hook]]></title>
            <link>https://medium.com/@tasoskakour/utilizing-a-custom-reducer-in-order-to-accomplish-undo-redo-functionality-e5211ac351b9?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5211ac351b9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[usereducer]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Sat, 09 Jul 2022 15:36:34 GMT</pubDate>
            <atom:updated>2022-07-11T06:31:01.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*JZwhVJ_kBn6awT2M.png" /></figure><p><em>This article, along with others, are originally published at my personal website: </em><a href="https://tasoskakour.com/"><em>https://tasoskakour.com</em></a>, <em>make sure to check them out :-).</em></p><h3>Undo/Redo algorithm</h3><p>I’m pretty sure you have clicked a lot of <em>Undos</em> and <em>Redos</em> in your life — I know I have. Both of these functions are pretty important in a workflow as they allow us to travel back and forth in time and to fix potential mistakes.</p><p>Have you ever wondered what an undo-redo implementation would look like in a computer program? I’m sure there are myriad implementations out there but the <strong>fundamentals</strong> are pretty much the same:</p><ol><li>A mechanism to store the present value accompanied with the <strong>past</strong> and <strong>future</strong> values.</li><li>An algorithm that will appropriately alter the state according to the <em>undo</em>, <em>redo</em> and <em>set</em> action.</li></ol><p>Based on the two points above, I believe that a <strong>Reducer</strong> perfectly fits the use case. It’s a function which takes two arguments — the current state and an action — and returns based on both arguments a new state.</p><p>Let’s try and think how we can utilize a reducer in order to accomplish an undo/redo mechanism.</p><p><strong>Point 1</strong>: We need to store the past and future values along with the present value.</p><p>One way we can accomplish that is by storing the past, present and future values inside an object. Note that past and future values need to be an <strong>array</strong> in order to travel back and forward anywhere in time.</p><pre>const state = {<br>    past: [...] // past values<br>    present: ... // present value<br>    future: [...] // future values<br>}</pre><p><strong>Point 2</strong>: An algorithm for each of the undo, redo and set actions.</p><p>For the sake of explaining the algorithm better, let’s assume that our counter’s state looks like this at some point in the application:</p><pre>const state = {<br>    past: [0, 1, 2, 3]  <br>    present: 4<br>    future: [5, 6]  <br>}</pre><p><strong>Undo Action</strong></p><p>In an undo action, we need to look into the past but we mustn’t lose track of the present. So:</p><ul><li><strong>Past</strong>: The last value of the past is removed from the array.</li><li><strong>Present</strong>: It takes the last value from the past (which is removed as mentioned above).</li><li><strong>Future</strong>: We append the present value to the start of the future array.</li></ul><p>So, after an undo action our state would become:</p><pre>const state = {<br>    past: [0, 1, 2]  <br>    present: 3<br>    future: [4, 5, 6]  <br>}</pre><p><strong>Redo Action</strong></p><p>In a redo action, we need to look into the future. Hence:</p><ul><li><strong>Past</strong>: We push the present value to the end of the past array.</li><li><strong>Present</strong>: The first value of the future array now becomes the present value.</li><li><strong>Future</strong>: We remove the first element of the future array (which now represents the present value).</li></ul><pre>const state = {<br>    past: [0, 1, 2, 3]  <br>    present: 4<br>    future: [5, 6]  <br>}</pre><p><strong>Set Action</strong></p><p>How would the state need to be adjusted when the <em>set</em> action takes place? E.g when the counter is incremented or decremented?</p><ul><li><strong>Past</strong>: The (past) present value now belongs to the past. So we push the value to the past array.</li><li><strong>Present</strong>: It’s being set with the new value.</li><li><strong>Future</strong>: The future is cleared.</li></ul><pre>const state = { <br>    past: [0, 1, 2, 3, 4]  <br>    present: 5<br>    future: []<br>}</pre><h3>useUndoRedo: React hook implementation</h3><p>Take a look at this CodeSandbox: <a href="https://codesandbox.io/s/react-undo-redo-c3x8pw">https://codesandbox.io/s/react-undo-redo-c3x8pw</a></p><p>By utilizing the useReducer hook we&#39;re able to create a straightforward useUndoRedo custom hook which looks like setState but provides undo-redo mechanism along with the ability to actually see the past and future values of the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/0*QleLNBdF4jDyRRxw.gif" /></figure><p>The code of the useUndoRedo hook is shown below.</p><pre>// use-undo-redo.js<br><br>import { useReducer } from &quot;react&quot;;<br><br>const SET_STATE = &quot;SET_STATE&quot;;<br>const UNDO = &quot;UNDO&quot;;<br>const REDO = &quot;REDO&quot;;<br><br>const reducerWithUndoRedo = (state, action) =&gt; {<br>  const { past, present, future } = state;<br><br>  switch (action.type) {<br>    case SET_STATE:<br>      return {<br>        past: [...past, present],<br>        present: action.data,<br>        future: []<br>      };<br>    case UNDO:<br>      return {<br>        past: past.slice(0, past.length - 1),<br>        present: past[past.length - 1],<br>        future: [present, ...future]<br>      };<br>    case REDO:<br>      return {<br>        past: [...past, present],<br>        present: future[0],<br>        future: future.slice(1)<br>      };<br>    default:<br>      throw new Error();<br>  }<br>};<br><br>const useUndoRedo = (initialState = {}) =&gt; {<br>  const [state, dispatch] = useReducer(reducerWithUndoRedo, {<br>    past: [],<br>    present: initialState,<br>    future: []<br>  });<br>  const { past, present, future } = state;<br><br>  const setState = (newState) =&gt; dispatch({ type: SET_STATE, data: newState });<br>  const undo = () =&gt; dispatch({ type: UNDO });<br>  const redo = () =&gt; dispatch({ type: REDO });<br>  const isUndoPossible = past &amp;&amp; past.length &gt; 0;<br>  const isRedoPossible = future &amp;&amp; future.length &gt; 0;<br><br>  return {<br>    state: present,<br>    setState,<br>    undo,<br>    redo,<br>    pastStates: past,<br>    futureStates: future,<br>    isUndoPossible,<br>    isRedoPossible<br>  };<br>};<br><br>export default useUndoRedo;</pre><h3>The End</h3><p>I hope you found the article informative.</p><p>See you soon! 🙂</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-undo-redo"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5211ac351b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: useMemo vs useCallback]]></title>
            <link>https://medium.com/@tasoskakour/react-usememo-vs-usecallback-1d732ffebe8f?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d732ffebe8f</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[usememo]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Fri, 01 Jul 2022 15:44:15 GMT</pubDate>
            <atom:updated>2022-07-01T15:44:15.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*ZxPf-BG0TgLHJCp7.png" /></figure><p><em>This article, along with others, are originally published at my personal website: </em><a href="https://tasoskakour.com/"><em>https://tasoskakour.com</em></a>, <em>make sure to check them out :-).</em></p><h3>Memoization</h3><p>First of all let’s quickly explain what is useMemo and useCallback in React.</p><p>Both useMemo and useCallback are React hooks that have to do with a term called <strong>Memoization</strong>.</p><p>According to Wikipedia:</p><blockquote><em>In computing, memoization or memoisation is an optimization technique used primarily to speed up computer programs by storing the results of expensive function calls and returning the cached result when the same inputs occur again.</em></blockquote><p>A memoized function <strong>“remembers”</strong> the results corresponding to some set of specific inputs. As a result, subsequent calls with past inputs return the remembered result rather than recalculating it.</p><p>For example consider a costly function f(n) that calculates the factorial of a number n. We know that the final result of the function is <strong>invariant</strong> - e.g the factorial of 3 would always be 6. So why don&#39;t we just store the result and return the stored result the next time this function is called with input 3? That&#39;s memoization.</p><h3>useMemo in React</h3><p>Suppose we’ve got a React component that needs to run an <strong>expensive</strong> function that computes a value. The parameters of that function are taken from the component’s props — so we can’t move that function outside of the component.</p><p>That means the function will be invoked on every re-render of the component:</p><pre>const Component = (props) =&gt; {<br>    const {a, b, ...otherProps} = props;<br>    const x = computeExpensiveValue(a, b);<br><br>    return &lt;div&gt;{x}&lt;/div&gt;<br>}</pre><p>That implementation would be catastrophical for the performance of our component and the UI most probably would feel unresponsive.</p><p>🎉 <strong>useMemo to the rescue!</strong></p><p>With useMemo we can memoize the result of computeExpensiveValue function. That means the function will only re-run when input parameters <em>a</em> or <em>b</em> <strong>change</strong> and <strong>not</strong> on every re-render.</p><p>The syntax is really simple, we just pass an array of dependencies to the useMemo hook. useMemo will only recompute the memoized value when one of the dependencies has changed.</p><p><em>If no array is provided, a new value will be computed on every render.</em></p><pre>const Component = (props) =&gt; {<br>    const {a, b, ...otherProps} = props;<br>    const x = useMemo(() =&gt; computeExpensiveValue(a, b), [a, b]); <br><br>    return &lt;div&gt;{x}&lt;/div&gt;<br>}</pre><p>Of course we’ve got to be careful with useMemo and only use it as a performance optimization, as React states:</p><blockquote><strong><em>You may rely on useMemo as a performance optimization, not as a semantic guarantee.</em></strong><em> In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.</em></blockquote><h3>useCallback in React</h3><p>OK, now that we’ve understood useMemo, let’s talk a bit about the useCallback hook.</p><p>This hook is useful when we want to <strong>memoize functions</strong> (callbacks).</p><p>The most common use case we would want to memoize a function is when we pass it (the function) <strong>down</strong> to <strong>pure</strong> child components.</p><p>For example consider the scenario below:</p><pre>const PureComponent = React.memo((props) =&gt; {<br>    const {onToggleClick, ...otherProps} = props;<br><br>    return &lt;button onClick={() =&gt; onToggleClick()}&gt;some button&lt;/button&gt;<br>});<br><br>const Father = (props) =&gt; {<br>    const {a, b} = props;<br><br>    return &lt;div&gt; <br>        &lt;PureComponent {...otherProps} onToggleClick={() =&gt; console.log(a, b)} /&gt;<br><br>        {/* ... other stuff here ...*/}<br>    &lt;/div&gt;<br>}</pre><p>We want our PureComponent to re-render only when it&#39;s props change - that&#39;s why we wrapped it in a React.memo call. React.memo works by <strong>shallowly compare</strong> the prop changes.</p><p>However, when Father component re-renders the onToggleClick function is re-created - it does <strong>not</strong> have a stable reference. As a result, all our React.memo optimization is pointless.</p><p>🎉 <strong>useCallback to the rescue!</strong></p><p>By using the useCallback hook, we can instruct onToggleClick function to have a <strong>stable reference</strong> in each re-render.</p><pre>const onToggleClick = useCallback(() =&gt; console.log(a, b), []);</pre><p><strong>We aren’t finished yet</strong>. You may noticed an array as a second parameter to useCallback. This is the dependency array that will dictate to useCallback to change whenever one of the dependencies change - in this way onToggleClick will always have access to the latest value of a and b.</p><p>As React states:</p><blockquote><em>… every value referenced inside the callback should also appear in the dependencies array …</em></blockquote><p>So the final implementation would be something like:</p><pre>const PureComponent = React.memo((props) =&gt; {<br>    const {onToggleClick, ...otherProps} = props;<br><br>    return &lt;button onClick={() =&gt; onToggleClick()}&gt;some button&lt;/button&gt;<br>})<br><br>const Father = (props) =&gt; {<br>    const {a, b} = props;<br><br>    const onToggleClick = useCallback(() =&gt; console.log(a, b), [a, b]);<br><br>    return &lt;div&gt; <br>        &lt;PureComponent {...otherProps} onToggleClick={onToggleClick} /&gt;<br><br>        {/* ... other stuff here ...*/}<br>    &lt;/div&gt;<br>}</pre><p>So in a nutshell:</p><ul><li>useMemo is to memoize a calculation between a function&#39;s calls and between renders.</li><li>useCallback is to memoize a callback itself (referential equality) between renders.</li></ul><p>Finally we have to note here that:</p><pre>useCallback(fn, deps)</pre><p>is equivalent to:</p><pre>useMemo(() =&gt; fn, deps)</pre><p>I hope you found the article informative.</p><p>See you soon! 🙂</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-use-memo-vs-use-callback"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d732ffebe8f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New startTransition API in React]]></title>
            <link>https://blog.devgenius.io/new-starttransition-api-in-react-9d407c86eec1?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d407c86eec1</guid>
            <category><![CDATA[start-transition]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Tue, 26 Apr 2022 06:16:37 GMT</pubDate>
            <atom:updated>2022-04-26T16:05:55.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*gV2nmVSQDfT0XAml.png" /></figure><h3>What is a Transition?</h3><p>A transition is a new concept in React to distinguish between urgent and non-urgent updates.</p><ul><li><strong>Urgent updates</strong> reflect direct interaction, like typing, clicking, pressing, and so on.</li><li><strong>Transition updates</strong> transition the UI from one view to another.</li></ul><p>Urgent updates like typing, clicking, key pressing need <strong>immediate</strong> response to match our intuitions about how physical objects behave. Otherwise they feel <strong>“wrong”</strong>. However, <strong>transitions</strong> are different because the user doesn’t expect to see every intermediate value on screen.</p><p>For example, when you type in a search box you expect the input field itself to respond and show the typed character <strong>immediately</strong> when you press a key. However, the actual results may transition <strong>separately</strong> and a small delay would be often expected. If you change the search term again before the results are done rendering, you only care to see the <strong>latest</strong> results.</p><p>In React 18 we can use the startTransition API to mark any state updates as non-urgent.</p><p>In the code block below, there are two state updates — one that is urgent and one that is marked as non-urgent as it’s wrapped inside the startTransition callback:</p><pre>import {startTransition} from &#39;react&#39;;<br><br>// Urgent: Show what was typed<br>setInputValue(input);<br><br>// Mark any state updates inside as transitions (non-urgent)<br>startTransition(() =&gt; {<br>  // Transition: Show the results<br>  setResults(input);<br>});</pre><p>Non-urgent updates will be <strong>interrupted</strong> if more urgent updates like clicks or key presses come in. If a transition gets interrupted by the user (for example, by typing multiple characters in a row), React will throw out the <strong>stale</strong> rendering work that wasn’t finished and render only the <strong>latest</strong> update.</p><h3>Demo Application: Performance with and without startTransition</h3><p>We’ve built a simple application to demonstrate the power of the new startTransition API.</p><p>The application is basically a “Text Search” feature that provides the user with the ability to search a term inside a long block of text (in our case about 60000 characters).</p><p>Our application needs to provide two features:</p><ul><li>To render an <strong>input</strong> that allows the user to type a <strong>search</strong> term.</li><li>To <strong>highlight</strong> any characters that match (case insensitive) with the typed search term.</li></ul><p>The naive algorithm we used to get the matched terms is:</p><ol><li>Construct a regex from the <strong>search term</strong> that will match any characters (case insensitive).</li><li>Add the highlight class to all the <em>spans</em> of the matched characters.</li></ol><p>The code for the applyFilter function is seen below:</p><pre>const applyFilter = (query, setFilteredNode) =&gt; {<br>  setFilteredNode(() =&gt; {<br>    if (!query || query.trim().length === 0) {<br>      return INITIAL_VALUE;<br>    }<br><br>    const regex = new RegExp(<br>      query.trim().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, &quot;\\$&amp;&quot;),<br>      &quot;ig&quot;<br>    );<br><br>    const node = TEXT.replaceAll(regex, (s) =&gt; `##${s}##`)<br>      .split(&quot;##&quot;)<br>      .map((s, i) =&gt; (<br>        &lt;span key={i} className={i % 2 === 1 ? &quot;highlight&quot; : &quot;&quot;}&gt;<br>          {s}<br>        &lt;/span&gt;<br>      ));<br><br>    return node;<br>  });<br>};</pre><p>Obviously we could come up with more optimized algorithms — and this regex seriously hinders the performance — however our task here is to “create” a costly function that results in a heavy React state update so that we can see if the startTransition API will improve the situation.</p><p><strong>You can find all the code of the app </strong><a href="https://codesandbox.io/s/react-18-starttransition-demo-s2bvxy?file=/src/App.js"><strong>here</strong></a><strong>.</strong></p><h3>1st Implementation: Unoptimized without startTransition</h3><p>Our first implementation is a component with two simple state updates, one for the input value and one that will apply the filtered results. Whenever the input value changes, the function applyFilter will be called. Both state updates are marked as urgent by default:</p><pre>import {useState} from &#39;react&#39;;<br><br>const Unoptimized = () =&gt; {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const [filteredNode, setFilteredNode] = useState(INITIAL_VALUE);<br><br>  const onInputChange = (e) =&gt; setQuery(e.target.value);<br><br>  useEffect(() =&gt; {<br>    applyFilter(query, setFilteredNode);<br>  }, [query]);<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;input&quot;&gt;<br>        &lt;input onChange={onInputChange} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;text&quot;&gt;{filteredNode}&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p><strong>Unoptimized</strong></p><p>You can see that the characters are not displaying immediately in the input field and the UI feels a bit “slow”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2xWBYLTtS05Rg5eYmlDYEA.gif" /></figure><p><strong>Unoptimized with CPU 4x slowdown</strong></p><p>We applied a 4x CPU slowdown (from Chrome dev tools) to better emulate an average CPU or a mobile device. We can see that the UI definitely feels slow and not smooth at all:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*U5w_4VR0kI5_T4e2.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tMGUDLsoZVlQoEIJ.gif" /></figure><h3>2nd Implementation: Optimized with startTransition</h3><p>In our second implementation we utilize the startTransition API. Specifically we make use of the useTransition hook which returns a pending state as well - we use that state to indicate to the user that a transition is still being processed by blurring the screen (we could also show a loader).</p><p>We mark the state update of the results as non-urgent by wrapping it inside a startTransition callback:</p><pre>import {useState, useTransition} from &#39;react&#39;;<br><br>const Optimized = () =&gt; {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const [filteredNode, setFilteredNode] = useState(INITIAL_VALUE);<br>  const [pending, startTransition] = useTransition();<br><br>  const onInputChange = (e) =&gt; setQuery(e.target.value);<br><br>  useEffect(() =&gt; {<br>    startTransition(() =&gt; {<br>      applyFilter(query, setFilteredNode);<br>    });<br>  }, [query, startTransition]);<br><br>  return (<br>    &lt;&gt;<br>      {pending &amp;&amp; &lt;div className=&quot;fade&quot; /&gt;}<br>      &lt;div className=&quot;input&quot;&gt;<br>        &lt;input onChange={onInputChange} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;text&quot;&gt;{filteredNode}&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p><strong>Optimized</strong></p><p>Look how fast the characters are displayed on the input screen; it feels natural, smooth and what the user would expect. We blur the screen while the pending variable is true to indicate to the user that a transition is still in process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s8F_6qAOauSUqrE0eamE7Q.gif" /></figure><p><strong>Optimized with CPU 4x slowdown</strong></p><p>We even applied a CPU 4x slowdown to examine how the UI responds. It looks <strong>good</strong>, even in <strong>that scenario</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6HQ-GHumZJ18kOwy.gif" /></figure><h3>Alternative solutions prior to React 18?</h3><p>Before React 18 we did not have the startTransition API, so how do we fix it in earlier React versions?</p><p>The most common solution to face issues like this and to avoid heavy repetitive state updates was to make use of <strong>debounce</strong> or <strong>throttle</strong> techniques.</p><p>For example we could utilize this awesome <a href="https://www.npmjs.com/package/use-debounce">use-debounce</a> library and wrap the heavy state update of the results in a <strong>debounced callback</strong> like this:</p><pre>import {useState} from &#39;react&#39;;<br>import {useDebouncedCallback} from &#39;use-debounce&#39;;<br><br>const Debounced = () =&gt; {<br>  const [query, setQuery] = useState(&quot;&quot;);<br>  const [filteredNode, setFilteredNode] = useState(INITIAL_VALUE);<br>   <br>  const onInputChange = (e) =&gt; setQuery(e.target.value);<br><br>  const debounced = useDebouncedCallback(<br>    (query, setFilteredNode) =&gt; {<br>       applyFilter(value, setFilteredNode);<br>    },<br>    100 // debounce 100 ms<br>  );  <br><br>  useEffect(() =&gt; {<br>    debounced(query, setFilteredNode);<br>  }, [query, startTransition]);<br><br>  return (<br>    &lt;&gt;<br>      {pending &amp;&amp; &lt;div className=&quot;loader&quot; /&gt;}<br>      &lt;div className=&quot;input&quot;&gt;<br>        &lt;input onChange={onInputChange} /&gt;<br>      &lt;/div&gt;<br>      &lt;div className=&quot;text&quot;&gt;{filteredNode}&lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><p>But there are still a few <strong>problems</strong> with this approach.</p><p>First, the applyFilter function cannot be called in under 100ms from when the user finishes typing (or whatever amount of time you choose). On the other hand, by using the startTransition API, the heavy processing of the results starts <strong>as soon as possible</strong>, without having to wait an arbitrary amount of time.</p><p>Secondly, even if we used throttle instead of debounce to try to solve the first issue, the work of processing the results is <strong>un-interruptable</strong>. That means that if new urgent updates come in (like key pressing) while the results are still being processed the UI inevitably would be <strong>unresponsive</strong>. Whereas with the startTransition API, the processing work will be <strong>interrupted</strong> when the urgent updates come in, keeping in this way the input field responsive.</p><h3>The End</h3><p>I hope you found the article informative.</p><p>See you soon. 🙂</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-18-new-api-start-transition"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d407c86eec1" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/new-starttransition-api-in-react-9d407c86eec1">New startTransition API in React</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OAuth2 Authorization with React]]></title>
            <link>https://blog.devgenius.io/oauth2-authorization-with-react-df276f747d5a?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/df276f747d5a</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Mon, 18 Apr 2022 10:55:23 GMT</pubDate>
            <atom:updated>2022-04-20T07:16:47.261Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*3246zB5zUBPhRGaQ.png" /></figure><blockquote><em>If you want to use </em><strong><em>OAuth2</em></strong><em> authorization in your React project you can use my published package: </em><a href="https://github.com/tasoskakour/react-use-oauth2"><em>@tasoskakour/react-use-oauth2</em></a><em>.</em></blockquote><h3>What is OAuth2?</h3><p>OAuth2 is the industry-standard protocol for authorization. It provides us with specific authorization flows for web applications, desktop applications, mobile phones and living room devices. You can read more about the framework <a href="https://oauth.net/2/">here</a>.</p><h3>Where do we use OAuth2 on the web?</h3><p>One of the major uses of OAuth2 protocol is authentication and authorization with 3rd party providers such as Google, Facebook, Apple etc. The so called “Social Login”. I’m pretty sure that most of you have used Social Login with OAuth2 (as an end-user) in the past.</p><p>In the picture below we can see that the user can either Sign in manually with the traditional way of providing username and password (right side) or they can sign in via Facebook/Twitter/Google (left side). By choosing to login with one of those social providers, they basically are authenticating with that provider and authorize the application to have access to certain information of their social account. For example if they choose to login with Google, after a successful authentication, the app may know their Google email, profile photo and name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*V0pLt-d3Bn4yQwjb.png" /></figure><p>One of the <strong>benefits</strong> of using a social login is its simplicity. With one click and without even having to enter a username and password we can just start using an app in a matter of seconds. Of course we need to make sure that the app is <strong>trustworthy</strong> and we <strong>always</strong> need to pay attention to what information the application will eventually gather from our social account.</p><h3>OAuth2 Grant types</h3><p>The most common OAuth2 Grant types are <a href="https://oauth.net/2/grant-types/authorization-code/">Authorization Code</a> and <a href="https://oauth.net/2/grant-types/implicit/">Implicit Flow</a>.</p><p><strong>OAuth 2.0 Authorization Code Grant</strong></p><p>The Authorization Code grant type is used by confidential and public clients to exchange an authorization code for an access token. The steps of this flow are:</p><p><strong>1)</strong> Client (your app) constructs and sends the user to an authorization URL (e.g for Google it’s https://accounts.google.com/o/oauth2/v2/auth) that has the form of:</p><pre>https://authorization-server.com/auth?<br>response_type=code&amp;<br>client_id=CLIENT_ID&amp;<br>redirect_uri=REDIRECT_URI&amp;<br>scope=photos&amp;<br>state=1234zyx</pre><p><strong>2)</strong> The user sees the authorization prompt and clicks “Allow” (or “Deny”). (Probably the user will be asked to authenticate first).</p><p><strong>3)</strong> User is being redirected to the redirect_uri that was initially passed to the request on the first step along with a code and the state. This URL will has the form of:</p><pre>https://REDIRECT_URI.com/callback?<br>code=AUTH_CODE_HERE&amp;<br>state=1234zyx</pre><p><strong>Note:</strong> the state parameter must match the state initially generated on step 1. This is to mitigate CSRF attacks. Read more <a href="https://auth0.com/docs/secure/attack-protection/state-parameters">here</a>.</p><p><strong>4)</strong> In this step we need to exchange the received code with an actual access token. To accomplish this we need to make a POST request to the authorization server&#39;s token endpoint that has the form as seen below (e.g for Google it&#39;s https://oauth2.googleapis.com/token). Note that this request needs to be made from our server as we must not expose the CLIENT_SECRET to the front-end app.</p><pre>https://api.authorization-server.com/token<br>grant_type=authorization_code&amp;<br>code=AUTH_CODE_HERE&amp;<br>redirect_uri=REDIRECT_URI&amp;<br>client_id=CLIENT_ID&amp;<br>client_secret=CLIENT_SECRET</pre><p>5) The authorization server replies back with the access token and an expiration time:</p><pre>{<br>&quot;access_token&quot;:&quot;RsT5OjbzRn430zqMLgV3Ia&quot;,<br>&quot;expires_in&quot;:3600<br>}</pre><p><strong>Note</strong>: Authorization Code flow is generally considered secure. However it can be even more bulletproof by using the PKCE (<a href="https://tools.ietf.org/html/rfc7636">RFC 7636</a>) extension which utilizes code_verifier, code_challenge and a code_challenge_method. This extension is beyond the scope of this article. You can read more about it <a href="https://oauth.net/2/pkce/">here</a>.</p><p><strong>Implicit Flow Grant</strong></p><p>The Implicit flow is a simplified OAuth flow for JavaScript apps where the access token is returned immediately without an extra authorization code exchange step.</p><p>This means that the steps for Implicit Flow are the steps 1–3 that we wrote above for Authorization Code grant. Also one more difference is that the redirect URL will contain the access_token in the hash (#) parameters and not in the search (?) parameters of the URL. It will have the form of:</p><pre>https://REDIRECT_URI.com/callback#<br>access_token=ACCESS_TOKEN&amp;<br>expires_in=3600&amp;<br>token_type=Bearer&amp;<br>state=1234zyx</pre><p>Nowadays the OAuth 2.0 standard recommends to use <em>Authorization Code Grant</em> instead of <em>Implicit Flow</em> due to the inherent risks of returning access tokens in an HTTP redirect without any confirmation that it has been received by the client.</p><p>However, most major providers still support and let apps use <em>Implicit Flow</em>. For example here you can read Google’s documentation for <a href="https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow">OAuth 2.0 for Client-side Web Applications</a> which basically uses an <em>Implicit Flow</em>.</p><h3>React: Implement OAuth2 with hooks</h3><p>In this section we’re going to create a React hook called useOAuth2 that will implement an <strong>OAuth2</strong> with <strong>Authorization Code Grant</strong>.</p><blockquote><em>If you want to use </em><strong><em>OAUth2</em></strong><em> authorization in your React project you can use my published package: </em><a href="https://github.com/tasoskakour/react-use-oauth2"><em>@tasoskakour/react-use-oauth2</em></a><em>.</em></blockquote><p>To make the authorization more user-friendly we are going to utilize a Popup; that is the authorization to the 3rd party will happen <strong>inside the Popup</strong> along with the redirection.</p><p><strong>Step 1: Prepare the hook</strong></p><p>The props that our hook will need are:</p><ul><li><strong>authorizeUrl</strong>: The 3rd party authorization URL (e.g for Google is <a href="https://accounts.google.com/o/oauth2/v2/auth).">https://accounts.google.com/o/oauth2/v2/auth).</a></li><li><strong>clientId</strong>: The OAuth2 client id of your application.</li><li><strong>redirectUri</strong>: Determines where the 3rd party API server redirects the user after the user completes the authorization flow. In our implementation a Popup will be rendered on that redirectUri.</li><li><strong>scope</strong> (string — <em>optional</em>): A list of scopes depending on your application needs.</li></ul><p>Let’s get those props to our hook and let’s create a UI state helper that will include {loading, error} and a function called getAuth. This function will initialize the authorization flow so as a first step it will need to set the loading to true and clear any errors.</p><pre>// useOAuth2.js<br>import { useCallback, useState } from &#39;react&#39;; <br><br>const useOAuth2 = (props) =&gt; {<br>  const {<br>      authorizeUrl,<br>      clientId,<br>      redirectUri,<br>      scope = &#39;&#39;,<br>    } = props;<br><br>  const [{ loading, error }, setUI] = useState({ loading: false, error: null });<br><br>  const getAuth = useCallback(() =&gt; {<br>      // 1. Init<br>      setUI({<br>        loading: true,<br>        error: null,<br>      });<br>  })<br>}</pre><p><strong>Step 2: Generate state</strong></p><p>Before constructing the authorization URL, we need to generate a state parameter. This parameter is needed to mitigate <a href="https://auth0.com/docs/secure/attack-protection/state-parameters">CSRF attacks</a>. Also we could pass any other state information we wanted here in order to restore later after the redirection.</p><p>To generate the state we make use of the window.crypto function. The code to accomplish this is taken from <a href="https://medium.com/@dazcyril/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50">this</a> article.</p><p>We also need to persist the state to sessionStorage so that our Popup will be able to read it later after the redirection takes place (we could persist it to <em>cookies</em> or <em>localStorage</em> as well).</p><pre>// useOAuth2.js<br>import { useCallback, useState } from &#39;react&#39;; <br><br>const OAUTH_STATE_KEY = &#39;react-use-oauth2-state-key&#39;;<br><br>// https://medium.com/@dazcyril/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50<br>const generateState = () =&gt; {<br>	const validChars = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;<br>	let array = new Uint8Array(40);<br>	window.crypto.getRandomValues(array);<br>	array = array.map((x: number) =&gt; validChars.codePointAt(x % validChars.length));<br>	const randomState = String.fromCharCode.apply(null, array);<br>	return randomState;<br>};<br><br>const saveState = (state: string) =&gt; {<br>	sessionStorage.setItem(OAUTH_STATE_KEY, state);<br>};<br><br>const removeState = () =&gt; {<br>	sessionStorage.removeItem(OAUTH_STATE_KEY);<br>};<br><br>const useOAuth2 = (props) =&gt; {<br>  const {<br>      authorizeUrl,<br>      clientId,<br>      redirectUri,<br>      scope = &#39;&#39;,<br>    } = props;<br><br>  const [{ loading, error }, setUI] = useState({ loading: false, error: null });<br><br>  const getAuth = useCallback(() =&gt; {<br>      // 1. Init<br>      setUI({<br>        loading: true,<br>        error: null,<br>      });<br><br>      // 2. Generate and save state<br>      const state = generateState();<br>      saveState(state);<br>  })<br>}</pre><p><strong>Step 3: Open the Popup</strong></p><p>And now we’ll start the Authorization process!</p><p>We create the authorization URL utilizing the enhanceAuthorizeUrl function that takes the authorizeUrl, clientId, redirectUri, scope, state parameters and we open a <strong>Popup</strong> to that URL. For better Popup manipulation we make use of useRef to hold the Popup instance.</p><pre>// useOAuth2.js<br>import { useCallback, useState } from &#39;react&#39;; <br><br>const OAUTH_STATE_KEY = &#39;react-use-oauth2-state-key&#39;;<br>const POPUP_HEIGHT = 700;<br>const POPUP_WIDTH = 600;<br><br>// https://medium.com/@dazcyril/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50<br>const generateState = () =&gt; {<br>	const validChars = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;<br>	let array = new Uint8Array(40);<br>	window.crypto.getRandomValues(array);<br>	array = array.map((x) =&gt; validChars.codePointAt(x % validChars.length));<br>	const randomState = String.fromCharCode.apply(null, array);<br>	return randomState;<br>};<br><br>const saveState = (state) =&gt; {<br>	sessionStorage.setItem(OAUTH_STATE_KEY, state);<br>};<br><br>const removeState = () =&gt; {<br>	sessionStorage.removeItem(OAUTH_STATE_KEY);<br>};<br><br>const openPopup = (url) =&gt; {<br>	// To fix issues with window.screen in multi-monitor setups, the easier option is to<br>	// center the pop-up over the parent window.<br>	const top = window.outerHeight / 2 + window.screenY - POPUP_HEIGHT / 2;<br>	const left = window.outerWidth / 2 + window.screenX - POPUP_WIDTH / 2;<br>	return window.open(<br>		url,<br>		&#39;OAuth2 Popup&#39;,<br>		`height=${POPUP_HEIGHT},width=${POPUP_WIDTH},top=${top},left=${left}`<br>	);<br>};<br><br>const closePopup = (popupRef) =&gt; {<br>	popupRef.current?.close();<br>};<br><br>const enhanceAuthorizeUrl = (<br>	authorizeUrl,<br>	clientId,<br>	redirectUri,<br>	scope,<br>	state<br>) =&gt; {<br>	return `${authorizeUrl}?response_type=code&amp;client_id=${clientId}&amp;redirect_uri=${redirectUri}&amp;scope=${scope}&amp;state=${state}`;<br>};<br><br>const useOAuth2 = (props) =&gt; {<br>  const {<br>      authorizeUrl,<br>      clientId,<br>      redirectUri,<br>      scope = &#39;&#39;,<br>    } = props;<br><br>  const popupRef = useRef();<br>  const [{ loading, error }, setUI] = useState({ loading: false, error: null });<br><br>  const getAuth = useCallback(() =&gt; {<br>      // 1. Init<br>      setUI({<br>        loading: true,<br>        error: null,<br>      });<br><br>      // 2. Generate and save state<br>      const state = generateState();<br>      saveState(state);<br><br>      // 3. Open popup<br>      popupRef.current = openPopup(<br>        enhanceAuthorizeUrl(authorizeUrl, clientId, redirectUri, scope, state)<br>      );<br>  })<br>}</pre><p><strong>Create the Popup Component</strong></p><p>Let’s leave useOAuth2 hook for now and let&#39;s concentrate on the <strong>Popup</strong> implementation.</p><p>Now we’re in a state where the user is inside a Popup and performs the authorization with the 3rd party. After that they will be redirected to the redirect_uri we passed along in the initial request.</p><p>A convenient practice is to render the Popup with a React Route for that redirect_uri. For example make redirect_uri to be https://your-app.com/callback and then create the Routes as seen in the code block below. In this way, the authorization server will redirect us back to the redirect_uri which will render only our Popup component.</p><pre>// routes.js<br>import { BrowserRouter, Route, Routes } from &#39;react-router-dom&#39;;<br>import { OAuthPopup } from &#39;OAuth2Popup&#39;;<br><br>const Example = () =&gt; (<br>	&lt;BrowserRouter&gt;<br>		&lt;Routes&gt;<br>			&lt;Route element={&lt;OAuthPopup /&gt;} path=&quot;/callback&quot; /&gt;<br>			&lt;Route element={&lt;Home /&gt;} path=&quot;/&quot; /&gt;<br>            {/* ... your other routes ... */}<br>		&lt;/Routes&gt;<br>	&lt;/BrowserRouter&gt;<br>);</pre><p>Now let’s move on with the Popup component. It needs to take care of 3 things:</p><ol><li>Read the URL redirection parameters code and state. If an error has occured there will be an error parameter.</li><li>Check that the state parameter matches the one that was initially sent to the request; we read that parameter from <em>sessionStorage</em>.</li><li>Communicate back to the parent window <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/opener">(window.opener)</a> that the authorization either succeeded or failed.</li></ol><p>In order to establish communication between the <strong>Popup</strong> and it’s <strong>Opener</strong> we make use of window.opener.postMessage function which sends messages to the window that the <strong>Opener</strong> can listen to.</p><p>The steps above are translated to the code below:</p><pre>// OAuth2Popup.jsx<br>import { useEffect } from &#39;react&#39;;<br>import { queryToObject } from &#39;./tools&#39;;<br><br>const OAUTH_STATE_KEY = &#39;react-use-oauth2-state-key&#39;;<br>const OAUTH_RESPONSE = &#39;react-use-oauth2-response&#39;;<br><br>const checkState = (receivedState) =&gt; {<br>	const state = sessionStorage.getItem(OAUTH_STATE_KEY);<br>	return state === receivedState;<br>};<br><br>const queryToObject = (query) =&gt; {<br>	const parameters = new URLSearchParams(query);<br>	return Object.fromEntries(parameters.entries());<br>};<br><br>const OAuthPopup = (props) =&gt; {<br>	const {<br>		Component = (<br>			&lt;div style={{ margin: &#39;12px&#39; }} data-testid=&quot;popup-loading&quot;&gt;<br>				Loading...<br>			&lt;/div&gt;<br>		),<br>	} = props;<br><br>	// On mount<br>	useEffect(() =&gt; {<br>		const payload = queryToObject(window.location.search.split(&#39;?&#39;)[1]);<br>		const state = payload &amp;&amp; payload.state;<br>		const error = payload &amp;&amp; payload.error;<br><br>		if (!window.opener) {<br>			throw new Error(&#39;No window opener&#39;);<br>		}<br><br>		if (error) {<br>			window.opener.postMessage({<br>				type: OAUTH_RESPONSE,<br>				error: decodeURI(error) || &#39;OAuth error: An error has occured.&#39;,<br>			});<br>		} else if (state &amp;&amp; checkState(state)) {<br>			window.opener.postMessage({<br>				type: OAUTH_RESPONSE,<br>				payload,<br>			});<br>		} else {<br>			window.opener.postMessage({<br>				type: OAUTH_RESPONSE,<br>				error: &#39;OAuth error: State mismatch.&#39;,<br>			});<br>		}<br>	}, []);<br><br>	return Component;<br>};<br><br>export default OAuthPopup;</pre><p><strong>Step 4: Listen to Popup messages</strong></p><p>Let’s move back to our useOAuth2 hook.</p><p>After we open the Popup we need to register a <strong>Message Listener</strong> to the window that will listen to any messages coming from the Popup. In order to distinguish from all the other window messages, the Popup sets the type of the message to react-use-oauth2-response.</p><p>If the Popup returned an error then we set the appropriate UI state, otherwise we get the message payload which includes the code parameter.</p><p>There’s also a scenario where the user forcefully closed the Popup before completing authorization. In order to catch this, we set an interval that periodically checks if the popup was forcefully closed and if so it performs some cleanup tasks like resetting the UI, removing the message listener etc.</p><pre>// useOAuth2.js<br>import { useCallback, useState } from &#39;react&#39;; <br><br>const OAUTH_STATE_KEY = &#39;react-use-oauth2-state-key&#39;;<br>const POPUP_HEIGHT = 700;<br>const POPUP_WIDTH = 600;<br>const OAUTH_RESPONSE = &#39;react-use-oauth2-response&#39;;<br><br>// https://medium.com/@dazcyril/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50<br>const generateState = () =&gt; {<br>	const validChars = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;<br>	let array = new Uint8Array(40);<br>	window.crypto.getRandomValues(array);<br>	array = array.map((x) =&gt; validChars.codePointAt(x % validChars.length));<br>	const randomState = String.fromCharCode.apply(null, array);<br>	return randomState;<br>};<br><br>const saveState = (state) =&gt; {<br>	sessionStorage.setItem(OAUTH_STATE_KEY, state);<br>};<br><br>const removeState = () =&gt; {<br>	sessionStorage.removeItem(OAUTH_STATE_KEY);<br>};<br><br>const openPopup = (url) =&gt; {<br>	// To fix issues with window.screen in multi-monitor setups, the easier option is to<br>	// center the pop-up over the parent window.<br>	const top = window.outerHeight / 2 + window.screenY - POPUP_HEIGHT / 2;<br>	const left = window.outerWidth / 2 + window.screenX - POPUP_WIDTH / 2;<br>	return window.open(<br>		url,<br>		&#39;OAuth2 Popup&#39;,<br>		`height=${POPUP_HEIGHT},width=${POPUP_WIDTH},top=${top},left=${left}`<br>	);<br>};<br><br>const closePopup = (popupRef) =&gt; {<br>	popupRef.current?.close();<br>};<br><br>const cleanup = (<br>	intervalRef,<br>	popupRef,<br>	handleMessageListener<br>) =&gt; {<br>	clearInterval(intervalRef.current);<br>	closePopup(popupRef);<br>	removeState();<br>	window.removeEventListener(&#39;message&#39;, handleMessageListener);<br>};<br><br>const enhanceAuthorizeUrl = (<br>	authorizeUrl,<br>	clientId,<br>	redirectUri,<br>	scope,<br>	state<br>) =&gt; {<br>	return `${authorizeUrl}?response_type=code&amp;client_id=${clientId}&amp;redirect_uri=${redirectUri}&amp;scope=${scope}&amp;state=${state}`;<br>};<br><br>const useOAuth2 = (props) =&gt; {<br>  const {<br>      authorizeUrl,<br>      clientId,<br>      redirectUri,<br>      scope = &#39;&#39;,<br>    } = props;<br><br>  const popupRef = useRef();<br>  const [{ loading, error }, setUI] = useState({ loading: false, error: null });<br><br>  const getAuth = useCallback(() =&gt; {<br>      // 1. Init<br>      setUI({<br>        loading: true,<br>        error: null,<br>      });<br><br>      // 2. Generate and save state<br>      const state = generateState();<br>      saveState(state);<br><br>      // 3. Open popup<br>      popupRef.current = openPopup(<br>        enhanceAuthorizeUrl(authorizeUrl, clientId, redirectUri, scope, state)<br>      );<br><br>      // 4. Register message listener<br>      async function handleMessageListener(message) {<br>        try {<br>          const type = message &amp;&amp; message.data &amp;&amp; message.data.type;<br>          if (type === OAUTH_RESPONSE) {<br>            const errorMaybe = message &amp;&amp; message.data &amp;&amp; message.data.error;<br>            if (errorMaybe) {<br>              setUI({<br>                loading: false,<br>                error: errorMaybe || &#39;Unknown Error&#39;,<br>              });<br>            } else {<br>              const code = message &amp;&amp; message.data &amp;&amp; message.data.payload &amp;&amp; message.data.payload.code;<br>              // ... Check next step to see what we&#39;ll do with the code<br>            }<br>          }<br>        } catch (genericError) {<br>          console.error(genericError);<br>          setUI({<br>            loading: false,<br>            error: genericError.toString(),<br>          });<br>        } finally {<br>          // Clear stuff ...<br>          cleanup(intervalRef, popupRef, handleMessageListener);<br>        }<br>      }<br>      window.addEventListener(&#39;message&#39;, handleMessageListener);<br><br>      // 4. Begin interval to check if popup was closed forcefully by the user<br>      intervalRef.current = setInterval(() =&gt; {<br>        const popupClosed = !popupRef.current || !popupRef.current.window || popupRef.current.window.closed;<br>        if (popupClosed) {<br>          // Popup was closed before completing auth...<br>          setUI((ui) =&gt; ({<br>            ...ui,<br>            loading: false,<br>          }));<br>          console.warn(&#39;Warning: Popup was closed before completing authentication.&#39;);<br>          clearInterval(intervalRef.current);<br>          removeState();<br>          window.removeEventListener(&#39;message&#39;, handleMessageListener);<br>        }<br>      }, 250);<br><br>      // Remove listener(s) on unmount<br>      return () =&gt; {<br>        window.removeEventListener(&#39;message&#39;, handleMessageListener);<br>        if (intervalRef.current) clearInterval(intervalRef.current);<br>      };<br>    })<br>}</pre><p><strong>Step 5: Exchange code with an access token</strong></p><p>The final step is to exchange the received code with an actual access_token.</p><p>In order to accomplish this we’ll need a server because we must not expose the client_secret to the front-end app. Then, our server will make a POST request to the 3rd party authorization server /token endpoint to actually get the access_token.</p><p>E.g for Google this is https://oauth2.googleapis.com/token. Also note that the specs for each provider may differ.</p><p>The server route we need to create is really simple. For the sake of this tutorial we will implement it with <a href="https://github.com/fastify/fastify">fastify</a> framework:</p><pre>// server.js<br>import Fastify from &#39;fastify&#39;;<br>import fetch from &#39;node-fetch&#39;;<br><br>const fastify = Fastify({<br>	logger: true,<br>});<br><br>const CLIENT_SECRET = process.env.CLIENT_SECRET;<br>const AUTHORIZATION_SERVER_TOKEN_URL = process.env.AUTHORIZATION_SERVER_TOKEN_URL; // e.g https://oauth2.googleapis.com/token<br><br>fastify.post(&#39;/token&#39;, async (request, reply) =&gt; {<br>	const { code, client_id, redirect_uri } = request.query;<br><br>	const data = await fetch(<br>		`${AUTHORIZATION_SERVER_TOKEN_URL}?grant_type=authorization_code&amp;client_id=${client_id}&amp;client_secret=${CLIENT_SECRET}&amp;redirect_uri=${redirect_uri}&amp;code=${code}`,<br>		{<br>			method: &#39;POST&#39;,<br>		}<br>	);<br><br>	reply.send(await data.json());<br>});<br><br>fastify.listen(3001, (error) =&gt; {<br>	if (error) throw error;<br>});</pre><pre>// useOAuth2.js<br>import { useCallback, useState } from &#39;react&#39;; <br><br>const OAUTH_STATE_KEY = &#39;react-use-oauth2-state-key&#39;;<br>const POPUP_HEIGHT = 700;<br>const POPUP_WIDTH = 600;<br>const OAUTH_RESPONSE = &#39;react-use-oauth2-response&#39;;<br><br>// https://medium.com/@dazcyril/generating-cryptographic-random-state-in-javascript-in-the-browser-c538b3daae50<br>const generateState = () =&gt; {<br>	const validChars = &#39;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&#39;;<br>	let array = new Uint8Array(40);<br>	window.crypto.getRandomValues(array);<br>	array = array.map((x) =&gt; validChars.codePointAt(x % validChars.length));<br>	const randomState = String.fromCharCode.apply(null, array);<br>	return randomState;<br>};<br><br>const saveState = (state) =&gt; {<br>	sessionStorage.setItem(OAUTH_STATE_KEY, state);<br>};<br><br>const removeState = () =&gt; {<br>	sessionStorage.removeItem(OAUTH_STATE_KEY);<br>};<br><br>const openPopup = (url) =&gt; {<br>	// To fix issues with window.screen in multi-monitor setups, the easier option is to<br>	// center the pop-up over the parent window.<br>	const top = window.outerHeight / 2 + window.screenY - POPUP_HEIGHT / 2;<br>	const left = window.outerWidth / 2 + window.screenX - POPUP_WIDTH / 2;<br>	return window.open(<br>		url,<br>		&#39;OAuth2 Popup&#39;,<br>		`height=${POPUP_HEIGHT},width=${POPUP_WIDTH},top=${top},left=${left}`<br>	);<br>};<br><br>const closePopup = (popupRef) =&gt; {<br>	popupRef.current?.close();<br>};<br><br>const cleanup = (<br>	intervalRef,<br>	popupRef,<br>	handleMessageListener<br>) =&gt; {<br>	clearInterval(intervalRef.current);<br>	closePopup(popupRef);<br>	removeState();<br>	window.removeEventListener(&#39;message&#39;, handleMessageListener);<br>};<br><br>const enhanceAuthorizeUrl = (<br>	authorizeUrl,<br>	clientId,<br>	redirectUri,<br>	scope,<br>	state<br>) =&gt; {<br>	return `${authorizeUrl}?response_type=code&amp;client_id=${clientId}&amp;redirect_uri=${redirectUri}&amp;scope=${scope}&amp;state=${state}`;<br>};<br><br>const objectToQuery = (object) =&gt; {<br>	return new URLSearchParams(object).toString();<br>};<br><br>const formatExchangeCodeForTokenServerURL = (<br>	serverUrl,<br>	clientId,<br>	code,<br>	redirectUri<br>) =&gt; {<br>	return `${serverUrl}?${objectToQuery({<br>		client_id: clientId,<br>		code,<br>		redirect_uri: redirectUri,<br>	})}`;<br>};<br><br>const useOAuth2 = (props) =&gt; {<br>  const {<br>      authorizeUrl,<br>      clientId,<br>      redirectUri,<br>      scope = &#39;&#39;,<br>    } = props;<br><br>  const popupRef = useRef();<br>  const [{ loading, error }, setUI] = useState({ loading: false, error: null });<br><br>  const getAuth = useCallback(() =&gt; {<br>      // 1. Init<br>      setUI({<br>        loading: true,<br>        error: null,<br>      });<br><br>      // 2. Generate and save state<br>      const state = generateState();<br>      saveState(state);<br><br>      // 3. Open popup<br>      popupRef.current = openPopup(<br>        enhanceAuthorizeUrl(authorizeUrl, clientId, redirectUri, scope, state)<br>      );<br><br>      // 4. Register message listener<br>      async function handleMessageListener(message) {<br>        try {<br>          const type = message &amp;&amp; message.data &amp;&amp; message.data.type;<br>          if (type === OAUTH_RESPONSE) {<br>            const errorMaybe = message &amp;&amp; message.data &amp;&amp; message.data.error;<br>            if (errorMaybe) {<br>              setUI({<br>                loading: false,<br>                error: errorMaybe || &#39;Unknown Error&#39;,<br>              });<br>            } else {<br>              const code = message &amp;&amp; message.data &amp;&amp; message.data.payload &amp;&amp; message.data.payload.code;<br>              const response = await fetch(<br>                formatExchangeCodeForTokenServerURL(<br>                  &#39;https://your-server.com/token&#39;,<br>                  clientId,<br>                  code,<br>                  redirectUri<br>                )<br>              );<br>              if (!response.ok) {<br>                setUI({<br>                  loading: false,<br>                  error: &quot;Failed to exchange code for token&quot;,<br>                });<br>              } else {<br>                payload = await response.json();<br>                setUI({<br>                  loading: false,<br>                  error: null,<br>                });<br>                setData(payload);<br>                // Lines above will cause 2 rerenders but it&#39;s fine for this tutorial :-)<br>              }<br>            }<br>          }<br>        } catch (genericError) {<br>          console.error(genericError);<br>          setUI({<br>            loading: false,<br>            error: genericError.toString(),<br>          });<br>        } finally {<br>          // Clear stuff ...<br>          cleanup(intervalRef, popupRef, handleMessageListener);<br>        }<br>      }<br>      window.addEventListener(&#39;message&#39;, handleMessageListener);<br><br>      // 4. Begin interval to check if popup was closed forcefully by the user<br>      intervalRef.current = setInterval(() =&gt; {<br>        const popupClosed = !popupRef.current || !popupRef.current.window || popupRef.current.window.closed;<br>        if (popupClosed) {<br>          // Popup was closed before completing auth...<br>          setUI((ui) =&gt; ({<br>            ...ui,<br>            loading: false,<br>          }));<br>          console.warn(&#39;Warning: Popup was closed before completing authentication.&#39;);<br>          clearInterval(intervalRef.current);<br>          removeState();<br>          window.removeEventListener(&#39;message&#39;, handleMessageListener);<br>        }<br>		  }, 250);<br><br>      // Remove listener(s) on unmount<br>      return () =&gt; {<br>        window.removeEventListener(&#39;message&#39;, handleMessageListener);<br>        if (intervalRef.current) clearInterval(intervalRef.current);<br>      };<br>    })<br>}</pre><h3>The End</h3><p>I hope you found this article informative. 🙂</p><p>In a following article we will talk more about how we can specifically use Google OAuth2 and then the Google APIs to fetch information about the user.</p><p>Stay tuned!</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-use-oauth2"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df276f747d5a" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/oauth2-authorization-with-react-df276f747d5a">OAuth2 Authorization with React</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React: useState vs useReducer]]></title>
            <link>https://medium.com/@tasoskakour/react-usestate-vs-usereducer-8543ad05c154?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/8543ad05c154</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[usereducer]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Sat, 12 Feb 2022 12:00:29 GMT</pubDate>
            <atom:updated>2022-02-12T12:00:29.979Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*VtsCqzPNziXpJmRq.png" /></figure><p><em>This article, along with others, are originally published at my personal website: </em><a href="https://tasoskakour.com/"><em>https://tasoskakour.com</em></a>, <em>make sure to check them out :-).</em></p><h3>What is a Reducer?</h3><p>Generally speaking a reducer is basically a function which takes two arguments — the current state and an action — and returns based on both arguments a new state.</p><p>A reducer can be expressed as:</p><p>const reducer = (state, action) =&gt; newState;</p><p>If you have ever used <a href="https://redux.js.org/">Redux library</a> in the past then you will have first-hand experience with reducers and actions.</p><p>Some benefits of using reducers are:</p><ul><li>They are predictable, behave consistenly and are a nice fit for managing complex state.</li><li>Generally they are easy to test.</li><li>Powerful utilities like undo/redo, state persistence etc are, most of the times, easier to implement with a reducer.</li></ul><p>Having said all that, I must point out that we shouldn’t just use reducers for all of the use cases. Many times — especially for small apps and non-complex states — a reducer may do more harm than good as it may add more complexity and boilerplate code to our app.</p><h3>OK, so what is useReducer?</h3><p>So, React provides a hook named useReducer that we can use in order to manage our state with the help of a... reducer function.</p><p>The syntax is really simple, we just pass the <strong>reducer</strong> and the <strong>initialState</strong> and the hook returns the <strong>state</strong> and a <strong>dispatch</strong> function like this:</p><p>const [state, dispatch] = useReducer(reducer, initialState);</p><p>Then we can use the dispatch function by providing the action type and data (if needed), to update the state.</p><p>Let’s take a look at an example with a counter below:</p><pre>const reducer = (state, action) =&gt; {<br>    switch (action.type) {<br>        case &quot;INCREASE_COUNTER&quot;:<br>            return state + 1;<br>        case &quot;SET_COUNTER&quot;:<br>            return action.data;<br>        default:<br>            return state;<br>    }<br>}<br><br>const Component = () =&gt; {<br>    const [state, dispatch] = useReducer(reducer, 0); // initial counter state is 0<br><br>    // then somewhere in the app...<br>    return &lt;div&gt;<br>        &lt;button onClick={()=&gt; dispatch({type: &quot;INCREASE_COUNTER&quot;})}&gt;Increase counter&lt;/button&gt;<br>        &lt;button onClick={()=&gt; dispatch({type: &quot;SET_COUNTER&quot;, data: 5})}&gt;Set counter to 5&lt;/button&gt;<br>    &lt;/div&gt;<br>}</pre><p>The actions above will cause the reducer to update the state accordingly.</p><p><strong>Note:</strong> The returned dispatch function is memoized by default and can easily be distributed to children components, as we&#39;ll see in the tutorial below. However, any component that uses the state part returned from the useReducer will still <strong>rerender</strong> whenever that state changes. We&#39;ll not focus on the re-render parts in this article. We&#39;ll have other tutorials in the future that will talk just about how we can limit re-renders in an application. 👍</p><h3>Why all this…?</h3><p>You might be thinking, why writing all these complex reducers and using this weird dispatch function to perform some simple updates?</p><p>Well… that’s a valid question, as the example with the counter above could be written in just a few lines with a useState hook:</p><pre>const Component = () =&gt; {<br>    const [counter, setCounter] = useState(0); // initial counter state is 0<br><br>    // then somewhere in the app...<br>    return &lt;div&gt;<br>        &lt;button onClick={()=&gt; setCounter(c =&gt; c + 1)}&gt;Increase counter&lt;/button&gt;<br>        &lt;button onClick={()=&gt; setCounter(5)}&gt;Set counter to 5&lt;/button&gt;<br>    &lt;/div&gt;<br>}</pre><p>As a rule of thumb, it’s generally recommended to use a useReducer when our state is heavily dependent on previous state or if we&#39;ve got a really complex state. But as you saw from the previous example with the counter, it looks like using a reducer is an overkill.</p><p><strong>Each app is different and we need to carefully analyze the requirements to decide on our implementation.</strong> Also keep in mind that there are many packages out there that handle global state or reducer-like state (like the awesome <a href="https://github.com/pmndrs/zustand">zustand</a>) with just a few lines of code.</p><p>For the purpose of this tutorial, we’ll focus on the differences of useState and useReducer and we&#39;ll create a simple TODO app with two implementations, one using the useState hook and one using the useReducer hook.</p><h3>A Lorem ipsum TODO app</h3><p>Our final app will be as shown in the GIF below and will provide the user with the ability of adding some random lorem ipsum sentences and then marking them as completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/0*iontqxdCstMWSBuN.gif" /><figcaption>The final look of the app</figcaption></figure><h3>Implementation 1: Using a useState hook</h3><p>In our first implementation we are going to use a useState hook. The code can be found here: <a href="https://codesandbox.io/s/lorem-ipsum-app-with-usestate-w60el?file=/src/Actions.tsx">https://codesandbox.io/s/lorem-ipsum-app-with-usestate-w60el</a></p><p>We created 4 files for this solution:</p><ol><li>App.tsx: The app&#39;s starting point where the useItems is called.</li><li>useItems.ts: The hook which internally uses useState that handles the state of the items (adding an item, marking as completed etc).</li><li>Actions.tsx: A component that renders the buttons &quot;Add item&quot; and &quot;Mark all completed&quot;.</li><li>Items.tsx: The component that actually renders the sentences inside boxes.</li></ol><p>Let’s take a look at the useItems custom hook:</p><pre>// useItems.ts<br>import { useState, useCallback } from &quot;react&quot;;<br><br>export type ItemType = {<br>  text: string;<br>  completed?: boolean;<br>};<br><br>const useItems = () =&gt; {<br>  const [items, setItems] = useState&lt;ItemType[]&gt;([]);<br><br>  const addItem = useCallback(<br>    (item: Pick&lt;ItemType, &quot;text&quot;&gt;) =&gt;<br>      setItems((prevItems) =&gt; [item, ...prevItems]),<br>    []<br>  );<br><br>  const setItemCompleted = useCallback(<br>    (itemIndex: number, completed: boolean) =&gt;<br>      setItems((prevItems) =&gt;<br>        prevItems.map((item, i) =&gt;<br>          i === itemIndex ? { ...item, completed } : item<br>        )<br>      ),<br>    []<br>  );<br><br>  const toggleAllItemsCompleted = () =&gt; {<br>    const areAllCompleted =<br>      items.length &gt; 0 &amp;&amp;<br>      items.filter(({ completed }) =&gt; !completed).length === 0;<br>    setItems((prevItems) =&gt;<br>        prevItems.map((item) =&gt; ({ ...item, completed: !areAllCompleted }));<br>    );<br>  };<br><br>  return {<br>    items,<br>    addItem,<br>    setItemCompleted,<br>    toggleAllItemsCompleted<br>  };<br>};<br><br>export default useItems;</pre><p>The useItems hook returns 4 things:</p><ol><li>The items array that is actually an array of objects with each object representing an item.</li><li>The addItem function which will be used in order to add items to the array.</li><li>The setItemCompleted function which will be used in order to set an item as completed or not completed.</li><li>The toggleAllItemsCompleted function which toggles all the items to a completed (or not completed) state.</li></ol><p>The App component (App.tsx) calls the useItems hook and distribute the appropriate props to its children components as shown below.</p><p><em>You don’t need to pay attention to the styling, just focus on the functionality of the code</em>.</p><pre>// App.tsx<br>import useItems from &quot;./use-items&quot;;<br>import Items from &quot;./Items&quot;;<br>import styled from &quot;styled-components&quot;;<br>import Actions from &quot;./Actions&quot;;<br><br>const AppContainer = styled(&quot;div&quot;)`<br>  font-family: sans-serif;<br>  margin: 16px;<br>`;<br><br>const TitleContainer = styled(&quot;div&quot;)`<br>  display: flex;<br>  align-items: center;<br>  margin-bottom: 8px;<br>`;<br><br>const CompletedContainer = styled(&quot;div&quot;)`<br>  text-align: right;<br>  font-weight: 500;<br>`;<br><br>const Empty = styled(&quot;p&quot;)`<br>  font-style: italic;<br>`;<br><br>export const App = () =&gt; {<br>  const {<br>    items,<br>    addItem,<br>    setItemCompleted,<br>    toggleAllItemsCompleted<br>  } = useItems();<br><br>  const totalCompleted =<br>    items.filter(({ completed }) =&gt; completed)?.length ?? 0;<br><br>  return (<br>    &lt;AppContainer&gt;<br>      &lt;TitleContainer&gt;<br>        &lt;h3&gt;Your Items&lt;/h3&gt;<br>        &lt;Actions<br>          totalItems={items.length}<br>          addItem={addItem}<br>          toggleAllItemsCompleted={toggleAllItemsCompleted}<br>        /&gt;<br>      &lt;/TitleContainer&gt;<br>      &lt;CompletedContainer&gt;<br>        Completed: {totalCompleted}/{items.length}<br>      &lt;/CompletedContainer&gt;<br>      {items.length === 0 ? (<br>        &lt;Empty&gt;Add items by clicking the button above...&lt;/Empty&gt;<br>      ) : (<br>        &lt;Items items={items} setItemCompleted={setItemCompleted} /&gt;<br>      )}<br>    &lt;/AppContainer&gt;<br>  );<br>}</pre><p>The Actions (Actions.tsx) and Items (Items.tsx) components utilize the passed props in order to implement <em>onClick</em> actions and/or render the actual items as seen below:</p><pre>// Actions.tsx<br>import styled from &quot;styled-components&quot;;<br>import { ItemType } from &quot;./use-items&quot;;<br>import { LoremIpsum } from &quot;lorem-ipsum&quot;;<br><br>const lorem = new LoremIpsum({<br>  wordsPerSentence: {<br>    max: 6,<br>    min: 2<br>  }<br>});<br><br>type Props = {<br>  totalItems: number;<br>  addItem: (item: Pick&lt;ItemType, &quot;text&quot;&gt;) =&gt; void;<br>  toggleAllItemsCompleted: () =&gt; void;<br>};<br><br>const Container = styled(&quot;div&quot;)`<br>  display: flex;<br>  flex-wrap: wrap;<br>  align-items: center;<br>  margin: 0px 16px;<br>`;<br><br>const Button = styled(&quot;button&quot;)`<br>  border-radius: 4px;<br>  border: none;<br>  font-size: 14px;<br>  height: 30px;<br>  background-color: #3453e5;<br>  color: white;<br>  padding: 0px 12px;<br>  margin-right: 8px;<br>  cursor: pointer;<br><br>  :active {<br>    opacity: 0.9;<br>    transform: scale(1.05);<br>  }<br><br>  &amp;.outlined {<br>    border: 1px solid #3453e5;<br>    background: none;<br>    color: #3453e5;<br>  }<br>`;<br><br>const Actions = (props: Props) =&gt; {<br>  const { totalItems, addItem, toggleAllItemsCompleted } = props;<br><br>  return (<br>    &lt;Container&gt;<br>      &lt;Button<br>        onClick={() =&gt;<br>          addItem({<br>            text: lorem.generateWords()<br>          })<br>        }<br>      &gt;<br>        Add Item<br>      &lt;/Button&gt;<br>      {totalItems &gt; 1 &amp;&amp; (<br>        &lt;Button className=&quot;outlined&quot; onClick={() =&gt; toggleAllItemsCompleted()}&gt;<br>          Toggle All<br>        &lt;/Button&gt;<br>      )}<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Actions;<br></pre><pre>// Items.tsx<br>import { ItemType } from &quot;./use-items&quot;;<br>import styled from &quot;styled-components&quot;;<br><br>type Props = {<br>  items: ItemType[];<br>  setItemCompleted: (itemIndex: number, completed: boolean) =&gt; void;<br>};<br><br>const Container = styled(&quot;div&quot;)`<br>  display: flex;<br>  flex-wrap: wrap;<br>`;<br><br>const Item = styled(&quot;div&quot;)`<br>  margin: 8px;<br>  padding: 8px;<br>  border: 1px solid #a7a7a7;<br>  border-radius: 8px;<br>  cursor: pointer;<br>  color: #001a3a;<br>  font-size: 18px;<br>  text-transform: capitalize;<br><br>  &amp;:hover {<br>    box-shadow: 0px 0px 3px 1px #b9b9b9;<br>  }<br><br>  &amp;.completed {<br>    opacity: 0.75;<br>    text-decoration: line-through;<br>    color: #9f9f9f;<br>  }<br>`;<br><br>const Items = (props: Props) =&gt; {<br>  const { items, setItemCompleted } = props;<br><br>  return (<br>    &lt;Container&gt;<br>      {items.map(({ text, completed }, i) =&gt; (<br>        &lt;Item<br>          key={i}<br>          className={completed ? &quot;completed&quot; : &quot;&quot;}<br>          onClick={() =&gt; setItemCompleted(i, !completed)}<br>        &gt;<br>          {text}<br>        &lt;/Item&gt;<br>      ))}<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Items;</pre><p>So the useState solution definitely works. We&#39;ve got a custom hook that is responsible for managing the state and also exposes the functions addItem, setItemCompleted and toggleAllItemsCompleted that components deeper down in the tree can use to perform actions.</p><h3>Implementation 2: Using a useReducer hook</h3><p>For our second implementation we are going to use a useReducer hook. The code can be found here: <a href="https://codesandbox.io/s/lorem-ipsum-app-with-usereducer-h1c2s">https://codesandbox.io/s/lorem-ipsum-app-with-usereducer-h1c2s</a></p><p>Obviously the styling part and structure of the app is exactly the same with the previous implementation, that’s why we will omit any code related to styling and focus only on the important parts.</p><p>The key change is how the useItems hook is implemented (using a useReducer hook) and how the components utilize the dispatch function in order to perform the actions.</p><p>Let’s take a look at the useItems hook. We construct the reducer function by providing all the cases (actions) our app will have: <strong>ADD_ITEM</strong>, <strong>SET_ITEM_COMPLETED</strong> and <strong>TOGGLE_ALL_ITEMS_COMPLETED</strong>.</p><p>Finally the useReducer hook returns two things - the actual state (which contains the items) and a dispatch function.</p><pre>// useItems.ts<br>import { useReducer } from &quot;react&quot;;<br><br>export type ItemType = {<br>  text: string;<br>  completed?: boolean;<br>};<br><br>type State = {<br>  items: ItemType[];<br>};<br><br>export type Action =<br>  | {<br>      type: &quot;ADD_ITEM&quot;;<br>      data: {<br>        item: Pick&lt;ItemType, &quot;text&quot;&gt;;<br>      };<br>    }<br>  | {<br>      type: &quot;SET_ITEM_COMPLETED&quot;;<br>      data: { itemIndex: number; completed: boolean };<br>    }<br>  | { type: &quot;TOGGLE_ALL_ITEMS_COMPLETED&quot; };<br><br>const reducer = (state: State, action: Action): State =&gt; {<br>  switch (action.type) {<br>    case &quot;ADD_ITEM&quot;: {<br>      const { item } = action?.data;<br>      return {<br>        ...state,<br>        items: [item, ...state.items]<br>      };<br>    }<br><br>    case &quot;SET_ITEM_COMPLETED&quot;:<br>      const { itemIndex, completed } = action?.data;<br>      return {<br>        ...state,<br>        items: state?.items.map((item, i) =&gt;<br>          i === itemIndex ? { ...item, completed } : item<br>        )<br>      };<br><br>    case &quot;TOGGLE_ALL_ITEMS_COMPLETED&quot;: {<br>      const currentItems = state?.items ?? [];<br>      const areAllCompleted =<br>        currentItems.length &gt; 0 &amp;&amp;<br>        currentItems.filter(({ completed }) =&gt; !completed).length === 0;<br>      return {<br>        ...state,<br>        items: currentItems.map((item) =&gt; ({<br>          ...item,<br>          completed: !areAllCompleted<br>        }))<br>      };<br>    }<br><br>    default:<br>      throw new Error();<br>  }<br>};<br><br>const useItems = () =&gt; {<br>  const [state, dispatch] = useReducer(reducer, { items: [] });<br><br>  return {<br>    state,<br>    dispatch<br>  };<br>};<br><br>export default useItems;</pre><p>The App component will just have to distribute the dispatch function to its child components, <strong>instead of passing down separate functions like in the previous example</strong>.</p><pre>// App.tsx<br>import useItems from &quot;./use-items&quot;;<br>import Items from &quot;./Items&quot;;<br>import Actions from &quot;./Actions&quot;;<br>import styled from &quot;styled-components&quot;;<br><br>/*<br>...<br>styled components here<br>...<br>*/<br><br>export default function App() {<br>  const { state, dispatch } = useItems();<br>  const { items } = state;<br><br>  const totalCompleted =<br>    items.filter(({ completed }) =&gt; completed)?.length ?? 0;<br><br>  return (<br>    &lt;AppContainer&gt;<br>      &lt;TitleContainer&gt;<br>        &lt;h3&gt;Your Items&lt;/h3&gt;<br>        &lt;Actions totalItems={items.length} dispatch={dispatch} /&gt;<br>      &lt;/TitleContainer&gt;<br>      &lt;CompletedContainer&gt;<br>        Completed: {totalCompleted}/{items.length}<br>      &lt;/CompletedContainer&gt;<br>      {items.length === 0 ? (<br>        &lt;Empty&gt;Add items by clicking the button above...&lt;/Empty&gt;<br>      ) : (<br>        &lt;Items items={items} dispatch={dispatch} /&gt;<br>      )}<br>    &lt;/AppContainer&gt;<br>  );<br>}</pre><p>The Actions and Items components only need the dispatch function to perform things.</p><p>Also TypeScript will provide us with nice autocompletes for the dispatch function due to the fact that the type of the function is React.Dispatch&lt;Action&gt;. You can see at the GIF below that we can easily figure out how we can use the dispatch function from the types that IDE provides through TS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vCxlu_5itoRIZb5y.gif" /><figcaption>Handy autocompletes for the dispatch function</figcaption></figure><pre>// Actions.tsx<br>import styled from &quot;styled-components&quot;;<br>import { Action } from &quot;./use-items&quot;;<br>import { LoremIpsum } from &quot;lorem-ipsum&quot;;<br><br>const lorem = new LoremIpsum({<br>  wordsPerSentence: {<br>    max: 6,<br>    min: 2<br>  }<br>});<br><br>type Props = {<br>  totalItems: number;<br>  dispatch: React.Dispatch&lt;Action&gt;;<br>};<br><br>/*<br>...<br>styled components here<br>...<br>*/<br><br>const Actions = (props: Props) =&gt; {<br>  const { totalItems, dispatch } = props;<br><br>  return (<br>    &lt;Container&gt;<br>      &lt;Button<br>        onClick={() =&gt;<br>          dispatch({<br>            type: &quot;ADD_ITEM&quot;,<br>            data: {<br>              item: {<br>                text: lorem.generateWords()<br>              }<br>            }<br>          })<br>        }<br>      &gt;<br>        Add Item<br>      &lt;/Button&gt;<br>      {totalItems &gt; 1 &amp;&amp; (<br>        &lt;Button<br>          className=&quot;outlined&quot;<br>          onClick={() =&gt; dispatch({ type: &quot;TOGGLE_ALL_ITEMS_COMPLETED&quot; })}<br>        &gt;<br>          Toggle All<br>        &lt;/Button&gt;<br>      )}<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Actions;</pre><pre>// Items.tsx<br>import { Action, ItemType } from &quot;./use-items&quot;;<br>import styled from &quot;styled-components&quot;;<br><br>type Props = {<br>  items: ItemType[];<br>  dispatch: React.Dispatch&lt;Action&gt;;<br>};<br><br>/*<br>...<br>styled components here<br>...<br>*/<br><br>const Items = (props: Props) =&gt; {<br>  const { items, dispatch } = props;<br><br>  return (<br>    &lt;Container&gt;<br>      {items.map(({ text, completed }, i) =&gt; (<br>        &lt;Item<br>          key={i}<br>          className={completed ? &quot;completed&quot; : &quot;&quot;}<br>          onClick={() =&gt;<br>            dispatch({<br>              type: &quot;SET_ITEM_COMPLETED&quot;,<br>              data: { itemIndex: i, completed: !completed }<br>            })<br>          }<br>        &gt;<br>          {text}<br>        &lt;/Item&gt;<br>      ))}<br>    &lt;/Container&gt;<br>  );<br>};<br><br>export default Items;</pre><h3>Comparing the two implementations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aiMtAIBTUEYG068Ve_WUSg.png" /><figcaption>Differences between useState and useReducer</figcaption></figure><p>In my opinion, I think that the useReducer implementation is more suitable for this specific application. We can see that the app is more scalable with the reducer as we can easily just add new actions and then components will just need to use the dispatch function to update the state. It really provides more predictability and scalability to our code.</p><p>With the useState implementation we would have to add more custom functions (naming them in an appropriate way - and we know that naming things is hard in computer science 🙃), and then pass those functions down to our components to use.</p><p>Furthermore, due to the fact that the reducer is just a standalone function, we can easily test it independently from the other parts of the application.</p><p>Having said all that, I must point out that there are many ways and many implementations that could solve this problem. One could argue that using context is better, one could just use a npm library that provides global-state (or reducer-like state) with a just a few lines of code. In this tutorial I wanted to focus on just the core “native” libraries of React (useState and useReducer). We’ll create another tutorial in the future where we will analyze how we can achieve things with React context and other libraries.</p><h3>The End…</h3><p>Thanks for reading this article and remember… independently of what kind of tools you’ll use to solve any problem, in the end the code must be <strong>readable</strong> and the implementation <strong>scalable</strong>, <strong>maintanable</strong> and <strong>as little complex</strong> as possible.</p><p>Catch you later! 🙂</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-use-state-vs-use-reducer"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8543ad05c154" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React & useEffect cleanups]]></title>
            <link>https://towardsdev.com/react-useeffect-cleanups-f7cfe4fb1f77?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7cfe4fb1f77</guid>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Mon, 27 Dec 2021 13:01:22 GMT</pubDate>
            <atom:updated>2021-12-28T07:15:50.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*dnQ_xADAq1xBiKpV.png" /><figcaption>Image from <a href="https://undraw.co/">https://undraw.co</a></figcaption></figure><p>I hope you will enjoy this article! If you do, you can follow me on social media where I post more content like this one; check here: <a href="https://tasoskakour.com/">https://tasoskakour.com</a></p><p>Before jumping into what is a useEffect cleanup and when we need to apply it, take a look at the code below. Do you notice anything that is off?</p><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    setInterval(() =&gt; {<br>      console.log(&quot;Increasing count...&quot;);<br>      setCount((c) =&gt; c + 1);<br>    }, 1000);<br>  }, []);<br><br>  return &lt;h4&gt;Count: {count}&lt;/h4&gt;;<br>};<br><br>export default function App() {<br>  const [showCounter, setShowCounter] = useState(false);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; setShowCounter((sc) =&gt; !sc)}&gt;<br>        Show/Hide Counter<br>      &lt;/button&gt;<br>      {showCounter &amp;&amp; &lt;Counter /&gt;}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Now take a look at the demo and the console below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GpedEQeHpPM3ujrj.gif" /><figcaption>Memory leak demo</figcaption></figure><p><strong>So what is happening here?</strong></p><ol><li>We click the button to show the Counter</li><li>The Counter component is mounted and the interval starts</li><li>We click the button again to hide the Counter</li><li>The Counter component unmounts but the interval never stops, it keeps running</li></ol><p>So despite the fact that the Counter component unmounts after we click the button for the second time, the interval created inside the useEffect of Counter does not stop and it&#39;s <strong>running forever</strong> causing this error in the console:</p><p>index.js:27 Warning: Can&#39;t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.</p><p>➡️ Demo is available at: <a href="https://codesandbox.io/s/react-setinterval-memory-leak-4j60q?file=/src/App.js">https://codesandbox.io/s/react-setinterval-memory-leak-4j60q</a></p><h3>What is a useEffect cleanup?</h3><p>In most cases when we refer to a “useEffect cleanup” we mean that we need to write some code that will guarantee that will eliminate any potential memory leaks and that our app will remain bug free.</p><p>A potential memory leak, as we saw at our counter demo before, could be that we didn’t stop an interval (clear setInterval) when the component which created that interval unmounted, so now our interval keeps running forever! Or it could be that we didn’t clear a subscription we created and now we’ve got a listener that doesn’t ever get deactivated!</p><p>The situations above can very easily introduce major bugs to our app and despite the fact cleanups from useEffect are not always required, we need to acquire that as a best practice and whenever we write a useEffect we must ask ourselves: &quot;If the component unmounts, is unwanted code still running?&quot; or &quot;Do I need a cleanup function for this effect?&quot;.</p><h3>How to cleanup?</h3><p>Writing useEffect cleanup functions is pretty easy and straightforward. We just <em>return</em> a function from our useEffect as seen below:</p><pre>useEffect(()=&gt; {<br>  // our effect here...<br><br>  // we return the cleanup fn<br>  return () =&gt; {<br>    // our cleanup code here..<br>  }<br>}, []);</pre><h3>When do cleanups run?</h3><p>React performs the cleanup when the component unmounts. However, due to the fact that effects may run for many renders (and not just once), React <strong>also cleans up effects from the previous render before running the effects next time</strong>. Don’t worry if it’s hard to grasp this, we’ll better understand it with the examples below.</p><h3>Cleanup Examples</h3><p>Let’s fix our counter demo from before and introduce a cleanup function that will run when Counter component unmounts and will stop the interval:</p><pre>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  useEffect(() =&gt; {<br>    let interval;<br>    interval = setInterval(() =&gt; {<br>      console.log(&quot;Increasing count...&quot;);<br>      setCount((c) =&gt; c + 1);<br>    }, 1000);<br><br>    // our cleanup will run when the component unmounts<br>    return () =&gt; {<br>      clearInterval(interval);<br>    }<br>  }, []);<br><br>  return &lt;h4&gt;Count: {count}&lt;/h4&gt;;<br>};</pre><p>So generally speaking a subscription on a useEffect can be created and destroyed somewhat like this:</p><pre>const Subscription = () =&gt; {<br><br>  useEffect(() =&gt; {<br>    createSubscription();<br><br>    // our cleanup<br>    return () =&gt; {<br>      destroySubscription();<br>    }<br>  }, []);<br><br>  return &lt;div&gt;...&lt;/div&gt;<br>};</pre><p><strong>React also cleans up effects from the previous render before running the effects next time.</strong></p><p>Based on the sentence above, let’s take a look at the example below:</p><pre>const FriendStatus = (props) =&gt; {<br>  const { friendId } = props;<br><br>  useEffect(() =&gt; {<br>    // ...<br>    subscribeToFriendStatus(friendId, handleStatusChange);<br>  }, [friendId]);<br><br>  return &lt;div&gt;...&lt;/div&gt;<br>};</pre><p>The FriendStatus component above takes a friendId as a prop and subscribes to the friend&#39;s status with that friendId, which means that whenever the status of a friend changes we need to execute a function that for demo purposes we named it as handleStatusChange.</p><p>The useEffect will run once on mount and then whenever friendId changes (as we have passed friendId to our dependencies list of useEffect).</p><p>So imagine the scenario and flow below:</p><p>1.<strong> Run first effect</strong>: Mount with friendId: 1 -&gt; subscribeToFriendStatus(1, handleStatusChange)</p><p><em>(friendId changes)</em></p><p>2. <strong>Run next effect</strong>: Update with friendId: 2 -&gt; subscribeToFriendStatus(2, handleStatusChange)</p><p><em>(friendId changes)</em></p><p>3.<strong> Run next effect</strong>: Update with friendId: 3 -&gt; subscribeToFriendStatus(3, handleStatusChange)</p><p>The <strong>problem</strong> is that we never <strong>unsubscribe</strong> from a friendId before subscribing to the newly updated friendId and that means we end up having all these open subscriptions for all these friendIds!</p><p>By adding the cleanup function, as seen below, React will execute it before running effects for the next render (and of course eventually on unmount).</p><pre>const FriendStatus = (props) =&gt; {<br>  const {friendId} = props;<br><br>  useEffect(() =&gt; {<br>    // ...<br>    subscribeToFriendStatus(friendId, handleStatusChange);<br><br>    return () =&gt; {<br>      unSubscribeToFriendStatus(friendId, handleStatusChange);<br>    }<br>  }, [friendId]);<br><br>  return &lt;div&gt;...&lt;/div&gt;<br>};</pre><p>So the corrected flow now becomes:</p><p>1.<strong> Run first effect</strong>: Mount with friendId: 1 -&gt; subscribeToFriendStatus(1, handleStatusChange)</p><p><em>(friendId changes)</em></p><p>2.<strong> Clean up previous effect</strong>: Unsubscribe from friendId: 1 -&gt; unSubscribeToFriendStatus(1, handleStatusChange)</p><p>3.<strong> Run next effect</strong>: Update with friendId: 2 -&gt; subscribeToFriendStatus(2, handleStatusChange)</p><p><em>(friendId changes)</em></p><p>4.<strong> Clean up previous effect</strong>: Unsubscribe from friendId: 2 -&gt; unSubscribeToFriendStatus(2, handleStatusChange)</p><p>5.<strong> Run next effect</strong>: Update with friendId: 3 -&gt; subscribeToFriendStatus(3, handleStatusChange)</p><p><em>(component unmounts)</em></p><p>6.<strong> Clean up previous effect</strong>: Unsubscribe from friendId: 3 -&gt; unSubscribeToFriendStatus(3, handleStatusChange)</p><h3>The End</h3><p>I hope you liked this article and found it informative. Catch you later! 😀</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-use-effect-cleanups"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7cfe4fb1f77" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/react-useeffect-cleanups-f7cfe4fb1f77">React &amp; useEffect cleanups</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 18: Automatic Batching]]></title>
            <link>https://blog.devgenius.io/react-18-automatic-batching-2f5d691b4f19?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f5d691b4f19</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 08:17:56 GMT</pubDate>
            <atom:updated>2021-12-17T14:25:03.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*J3_GUEixVspgxT63.png" /><figcaption>React 18: Automatic Batching</figcaption></figure><p>I’m sure you have heard the term “React Batching” in the past, and maybe you were confused (as I was) at what it means and what it actually does in practical terms.</p><p><em>Before moving on with the post make sure that you check my personal website and subscribe to my blog where I post more content like this: </em><a href="https://tasoskakour.com/"><em>https://tasoskakour.com</em></a><em>.</em></p><p>Generally speaking the word <em>Batching</em> can be used in various ways but a general definition that makes sense for our use case can be expressed as:</p><blockquote><em>A group of jobs, data, or programs treated as a unit for computer processing.</em></blockquote><blockquote><em>(Batch Processing) A form of data processing in which a number of input jobs are grouped for processing during the same machine run.</em></blockquote><h3>What is React Batching</h3><p>Basically, when React applies “Batching” it means that it <strong>groups together multiple state updates into a single re-render</strong> mainly for better performance.</p><p>In React 17 and prior, React automatically batches any state updates <strong>only inside React event handlers</strong> (like a <em>click</em> or <em>change</em>).</p><p>Take a look at the code below and guess how many re-renders will the handleClick function cause?</p><p>Also don’t worry about the useRenderCount function. It&#39;s just a custom hook to count re-renders :-)</p><pre>const useRenderCount = () =&gt; {<br>  const renderCounter = useRef(0); <br>  useLayoutEffect(() =&gt; {<br>    renderCounter.current++;<br>  });<br>  return renderCounter.current;<br>};</pre><p>The actual demo:</p><pre>const Demo1 = () =&gt; {<br>    const renderCount = useRenderCount(); // we use this to count re-renders<br>    const [countUp, setCountUp] = useState(0);<br>    const [countDown, setCountDown] = useState(0);<br><br>    const handleClick = () =&gt; {<br>        setCountUp((cUp) =&gt; cUp + 1);<br>        setCountDown((cDown) =&gt; cDown - 1);<br>    };<br><br>    return (<br>        &lt;div style={{ textAlign: &quot;center&quot; }}&gt;<br>            &lt;h4&gt;Demo 1 (Batching)&lt;/h4&gt;<br>            &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;<br>            &lt;h2&gt;Count up: {countUp}&lt;/h2&gt;<br>            &lt;h2&gt;Count down: {countDown}&lt;/h2&gt;<br>            &lt;div&gt;Number of rerenders: {renderCount}&lt;/div&gt;<br>        &lt;/div&gt;<br>    );<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*cVErzMYoIg7_P_tf.gif" /><figcaption>Demo 1: React event handlers are batched successfully.</figcaption></figure><p>That’s right, it will only cause <strong>one</strong> re-render because React will batch the two state updates setCountUp and setCountDown into one!</p><p>Pretty cool right? React will take care that for us automatically and will avoid unnecessary re-renders which is great for performance! Also it will prevent our components from rendering “half-finished” states where only one state variable was updated, which may cause bugs.</p><h3>✋ But… There is a catch</h3><p><strong>React (prior to version 18) will only batch React event handlers. It will not batch updates inside of promises, setTimeout, native event handlers or any other events.</strong></p><p>In the real world there are many use cases where we need to update multiple states inside a handler where React cannot batch.</p><p>Let’s take a look at some examples below where React will not batch updates and it will cause more than one re-render.</p><h4>1) Updates inside setTimeout</h4><p>In the demo below, setCountUp and setCountDown will cause <strong>two</strong> re-renders as React cannot batch multiple updates inside a setTimeout callback.</p><pre>const Demo2 = () =&gt; {<br>  const renderCount = useRenderCount();<br>  const [countUp, setCountUp] = useState(0);<br>  const [countDown, setCountDown] = useState(0);<br><br>  const handleClick = () =&gt; {<br>    setTimeout(() =&gt; {<br>      setCountUp((cUp) =&gt; cUp + 1);<br>      setCountDown((cDown) =&gt; cDown - 1);<br>    }, 500);<br>  };<br><br>  return (<br>    &lt;div className=&quot;Demo&quot;&gt;<br>      &lt;h4&gt;Demo 2 (setTimeout)&lt;/h4&gt;<br>      &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;<br>      &lt;h2&gt;Count up: {countUp}&lt;/h2&gt;<br>      &lt;h2&gt;Count down: {countDown}&lt;/h2&gt;<br>      &lt;div&gt;Number of rerenders: {renderCount}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*tuDiLt65CWXeFVKt.gif" /><figcaption>Demo 2: React (&lt;17) is not able to batch setTimeout callbacks.</figcaption></figure><h4>2) Updates inside a promise</h4><p>In the example below we fetch a random cat image when the button is clicked. React cannot batch the multiple state updates that’s after the await fetch call, specifically the setCat(json.url) and setLoading(false).</p><p>However, it successfully batches the first two calls before the await: setLoading(true) and setCat(null).</p><p>So in total the handleClick function will cause 3 re-renders.</p><pre>const Demo3 = () =&gt; {<br>  const renderCount = useRenderCount();<br>  const [loading, setLoading] = useState(false);<br>  const [cat, setCat] = useState(null);<br><br>  const handleClick = async () =&gt; {<br>    // these two below will be batched<br>    setLoading(true);<br>    setCat(null);<br>    const response = await fetch(&quot;https://thatcopy.pw/catapi/rest/&quot;);<br>    if (response.ok) {<br>      const json = await response.json();<br>      setCat(json.url); // cannot batch<br>    }<br>    setLoading(false); // cannot batch<br>  };<br><br>  return (<br>    &lt;div className=&quot;Demo&quot;&gt;<br>      &lt;h4&gt;Demo 3 (Promise)&lt;/h4&gt;<br>      &lt;button onClick={handleClick}&gt;Click me&lt;/button&gt;<br>      &lt;h2&gt;Loading: {String(loading)}&lt;/h2&gt;<br>      &lt;h2<br>        style={{<br>          display: &quot;flex&quot;,<br>          justifyContent: &quot;center&quot;,<br>          alignItems: &quot;center&quot;<br>        }}<br>      &gt;<br>        Cat:{&quot; &quot;}<br>        {cat ? (<br>          &lt;img<br>            alt=&quot;cat&quot;<br>            width=&quot;35&quot;<br>            height=&quot;35&quot;<br>            src={cat}<br>            style={{ marginLeft: &quot;8px&quot; }}<br>          /&gt;<br>        ) : (<br>          &quot;&quot;<br>        )}<br>      &lt;/h2&gt;<br>      &lt;div&gt;Number of rerenders: {renderCount}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*NnXOo-WX6aWIi_de.gif" /><figcaption>Demo 3: React (&lt;17) is not able to batch promises.</figcaption></figure><h4>3) Updates inside a native event handler</h4><p>In the example below we use a native event handler by attaching a click listener to our button. React is not able to batch these multiple state updates as well.</p><pre>const Demo4 = () =&gt; {<br>  const renderCount = useRenderCount();<br>  const [countUp, setCountUp] = useState(0);<br>  const [countDown, setCountDown] = useState(0);<br><br>  useEffect(() =&gt; {<br>    const handleClick = () =&gt; {<br>      setCountUp((cUp) =&gt; cUp + 1);<br>      setCountDown((cDown) =&gt; cDown - 1);<br>    };<br><br>    const element = document.querySelector(&quot;#my-button&quot;);<br>    element.addEventListener(&quot;click&quot;, handleClick);<br><br>    return () =&gt; {<br>      element.removeEventListener(&#39;click&#39;, handleClick);<br>    };<br>  }, []);<br><br>  return (<br>    &lt;div className=&quot;Demo&quot;&gt;<br>      &lt;h4&gt;Demo 4 (Native event handler)&lt;/h4&gt;<br>      &lt;button id=&quot;my-button&quot;&gt;Click me&lt;/button&gt;<br>      &lt;h2&gt;Count up: {countUp}&lt;/h2&gt;<br>      &lt;h2&gt;Count down: {countDown}&lt;/h2&gt;<br>      &lt;div&gt;Number of rerenders: {renderCount}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*D3Jf8UL1_kDYl865.gif" /><figcaption>React (&lt;17) is not able to batch native event handlers.</figcaption></figure><h4>💡 Quick fix to the above scenarios</h4><p>Obviously, a fix to the above scenarios would be to store all the “individual” states to a big state (or use a useReducer).</p><p>For example, the Demo with the fetch promise could be written as shown below in order to prevent unwanted re-renders:</p><pre>const Demo3Fix = () =&gt; {<br>  const renderCount = useRenderCount();<br>  const [state, setState] = useState({<br>    loading: false,<br>    cat: null<br>  }); // a single state object<br><br>  const handleClick = async () =&gt; {<br>    setState({<br>      loading: true,<br>      cat: null<br>    }); // 1st re-render<br>    const response = await fetch(&quot;https://thatcopy.pw/catapi/rest/&quot;);<br>    if (response.ok) {<br>      const json = await response.json();<br>      setState((s) =&gt; ({ cat: json.url, loading: false })); // 2nd re-render<br>    } else {<br>      setState((s) =&gt; ({ ...s, loading: false })); // or this 2nd re-render<br>    }<br>  };<br><br>  const { cat, loading } = state;<br><br>  return (<br>    ...<br>  );<br>};</pre><p>➡️ All the previous React 17 demos are available in this CodeSandbox: <a href="https://codesandbox.io/s/cranky-mccarthy-g5ntm">https://codesandbox.io/s/cranky-mccarthy-g5ntm</a></p><h3>React 18 to the rescue 🎉</h3><p>React 18 adds automatic batching for all use cases to improve performance even further. You can read more <a href="https://reactjs.org/blog/2021/06/08/the-plan-for-react-18.html">here</a>. It’s still in beta.</p><p>That means that for <strong>all</strong> of our examples before, React (18) will automatically batch any multiple state updates into single update.</p><p>For proof, take a look at the <em>setTimeout</em> demo below where the only thing we changed was the version of React to 18 and the code inside index.js where we instruct React how to load our app. Specifically in order for React 18 to utilize these new features, we need to make use of the createRoot api.</p><p>index.js in React 17:</p><pre>import { render } from &quot;react-dom&quot;;<br>import App from &quot;./App&quot;;<br><br>render(&lt;App /&gt;, document.getElementById(&quot;root&quot;));</pre><p>index.js in React 18:</p><pre>import { createRoot } from &quot;react-dom&quot;;<br>import App from &quot;./App&quot;;<br><br>createRoot(document.getElementById(&quot;root&quot;)).render(&lt;App /&gt;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*pYC0RvtsFVqO6sMx.gif" /><figcaption>React 18: It batches setTimeout callbacks automatically!</figcaption></figure><p>➡️ Here’s the code with all the experiments for React 18: <a href="https://codesandbox.io/s/objective-elbakyan-6u76m">https://codesandbox.io/s/objective-elbakyan-6u76m</a></p><h3>What if you don’t want to batch?</h3><p>There may be a case where we don’t want React to batch the updates (although generally batching is considered safe). We can achieve that by using flushSync function like shown below:</p><pre>import { flushSync } from &#39;react-dom&#39;; <br><br>const handleClick = () =&gt; {<br>  flushSync(() =&gt; {<br>    setCountUp((cUp) =&gt; cUp + 1);  // 1st re-render <br>  })<br>  flushSync(() =&gt; { <br>    setCountDown((cDown) =&gt; cDown - 1); // 2nd re-render<br>  })  <br>};</pre><p>Also it’s worth noting here that in React version prior to 18 we could force state updates outside of React event handlers to be batched by using the undocumented API unstable_batchedUpdates like this:</p><pre>unstable_batchedUpdates(() =&gt; {<br>  // these 2 below will be batched<br>  setCountUp((cUp) =&gt; cUp + 1);<br>  setCountDown((cDown) =&gt; cDown - 1);<br>});</pre><p>According to the docs this API still exists in 18, but it isn’t necessary anymore because batching happens automatically. It also might get removed in a future version.</p><h3>The End</h3><p>I hope you enjoyed this article, catch you later! 😃</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/react-18-automatic-batching"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f5d691b4f19" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/react-18-automatic-batching-2f5d691b4f19">React 18: Automatic Batching</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immature Abstractions]]></title>
            <link>https://medium.com/@tasoskakour/immature-abstractions-24f9876ac01f?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/24f9876ac01f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Wed, 10 Nov 2021 15:22:38 GMT</pubDate>
            <atom:updated>2021-11-11T14:23:40.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*XfDU_RXXY_a2DetW.png" /><figcaption>Code over-thinking.</figcaption></figure><p>A few days ago we had a really insightful conversation with a colleague of mine about how we would implement a new feature in one of our projects.</p><p>I will explain in broad terms what this feature is about and then I’ll outline two possible solutions for this problem with one of them being “better” than the other.</p><p>Before moving on with the post make sure that you check my personal website and subscribe to my blog where I post more content like this: <a href="https://tasoskakour.com/">https://tasoskakour.com</a></p><h3>The Problem</h3><p>Let’s say we have built a widget that from now on we’ll call <strong>OurWidget</strong>. This widget achieves many things (called <em>tasks</em>), and one of those is to support and “use” other 3rd party widgets and their SDKs as well.</p><p>Which 3rd party widget should be used by <strong>OurWidget</strong> is dictated by a variable called <strong>widgetType</strong> which is given from a user input to the application.</p><p>For example, assume that <strong>OurWidget</strong> needs to accomplish a task called openWidget which basically opens the widget. And let&#39;s also assume that <strong>widgetType</strong> is <strong>FacebookWidget</strong>. So basically the <em>task</em> openWidget must open the <strong>FacebookWidget</strong>.</p><p>The steps <strong>OurWidget</strong> needs to execute in order to achieve this task are:</p><ol><li>Run some boilerplate code which is the same for all widgets.</li><li>Initialize <strong>FacebookWidget</strong> SDK.</li><li>Run some boilerplate code to prepare for the open task.</li><li>Finally open <strong>FacebookWidget</strong> by using the corresponding function from the SDK, e.g FB.openWidget().</li></ol><p>If the <strong>widgetType</strong> input was <strong>GoogleWidget</strong> then the algorithm above would be (notice how steps <em>1</em> and <em>3</em> are the same):</p><ol><li>Run some boilerplate code which is the same for all widgets.</li><li>Initialize <strong>GoogleWidget</strong> SDK.</li><li>Run same boilerplate code to prepare for the open task.</li><li>Finally open <strong>GoogleWidget</strong> by using the corresponding function from the SDK, e.g Google.openWidget().</li></ol><p>Of course we want our awesome <strong>OurWidget</strong> to support many 3rd party widgets as possible, like <strong>InstagramWidget</strong>, <strong>ViberWidget</strong>, <strong>WhateverWidget</strong> etc… Eventually we don’t know how many widgets we’ll support so our solution must be robust and scalable in order to easily add, remove, or modify widgets in the future.</p><p>Conceptually, we need to support <em>N</em> tasks for <em>M</em> widgets ( <em>N</em> and <em>M</em> can’t be known beforehand and are prone for change in the future). A naive diagram that demonstrates that, is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/0*VPZpcG9mdOg3XISC.png" /><figcaption>A system diagram.</figcaption></figure><h3>Think in Abstract Terms</h3><p>Personally I hate duplicated code. When I’m writing code and I’m about to spot a code duplication or when I’m “feeling” that a duplication is coming, I make sure to refactor a function or to improve something somewhere in order to avoid that duplication. In that way I’m confident that when I need to change something in the future I won’t have to change it at many places!</p><p>However, there are many cases that code duplication is “necessary” and is way more preferable than making the code more abstract. And I’m about to find that probably this is the case for the current problem we’re talking about as well.</p><h3>My First Solution</h3><p>Let’s take a closer look to the two pseudo-algorithms presented before, regarding the openWidget task:</p><p><strong>FacebookWidget</strong> (widgetType=”facebook”)</p><ol><li>Run some boilerplate code which is the same for all widgets.</li><li>Initialize <strong>FacebookWidget</strong> SDK.</li><li>Run some boilerplate code to prepare for the open task.</li><li>Finally pen <strong>FacebookWidget</strong> by using the corresponding function from the SDK, e.g FB.openWidget().</li></ol><p><strong>GoogleWidget</strong> (widgetType=”google”)</p><ol><li>Run some boilerplate code which is the same for all widgets.</li><li>Initialize <strong>GoogleWidget</strong> SDK.</li><li>Run same boilerplate code to prepare for the open task.</li><li>Finally open <strong>GoogleWidget</strong> by using the corresponding function from the SDK, e.g Google.openWidget().</li></ol><p>You’re spotting it as well right? The steps 1 and 3 are exactly the same for the two different widgets (and it will be the same for any future widget). So my mind is thinking, there’s the duplication, I need to make it abstract!</p><p>An abstract implementation:</p><pre>import FB from &#39;facebook&#39;;<br>import Google from &#39;google&#39;;<br><br>const Tasks = {<br>    init(widgetType) {<br>        // ... 5 boilerplate lines for init ...<br>        switch (widgetType){<br>            case &quot;Facebook&quot;:<br>                FB.init();<br>            case &quot;Google&quot;:<br>                Google.init();<br>            default:<br>                break;<br>        }<br>    }<br>    open(widgetType) {<br>        // ... 5 boilerplate lines for open ...<br>         switch (widgetType){<br>            case &quot;Facebook&quot;:<br>                FB.openWidget();<br>            case &quot;Google&quot;:<br>                Google.openWidget();<br>            default:<br>                break;<br>        }<br>    }<br>    close(widgetType) {<br>        // ... 5 boilerplate lines for close ...<br>        switch (widgetType){<br>            case &quot;Facebook&quot;:<br>                FB.closeWidget();<br>            case &quot;Google&quot;:<br>                Google.closeWidget();<br>            default:<br>                break;<br>        }<br>    }<br>}<br><br>// And then compose the tasks and the widgets<br><br>const {open, close} = Tasks;<br><br>const createWidget = (widgetType) =&gt; ({<br>        init: () =&gt; init(widgetType),<br>        open: () =&gt; open(widgetType), <br>        close: () =&gt; close(widgetType)<br>    })<br><br>const Facebook = createWidget(&#39;Facebook&#39;);<br>const Google = createWidget(&#39;Google&#39;);<br><br>// So for the Open Facebook Task:<br>Facebook.init();<br>Facebook.open();<br><br>// And for the Open Google Task:<br>Google.init();<br>Google.open(); <br><br>// same for other tasks added...</pre><p>And… Now I’m happy! I managed to avoid any code duplication, make the implementation abstract &amp; smart and able to support all the widgets of the world! If we need to add a widget we’ll just add a new <em>case</em> at the <em>switch</em> blocks for each of the tasks.</p><p>Or… not?</p><h3>Immature Abstraction</h3><p>After the discussion with my colleague where I proudly presented him with my abstract implementation above, he suggested that this abstraction albeit smart it could bring maintainability &amp; scalability problems in the future. That’s why it would be probably for the better if we approached this problem in a less “abstract” way.</p><p>I was hesitant at first, as I couldn’t believe how non-abstract implementation with so many code duplications (imagine N*M where N tasks M widgets) would be more scalable and maintainable in the future.</p><p>But now I get it…</p><blockquote><em>Code duplication is better than an immature abstraction.</em></blockquote><p>And in my case this was probably an immature and “hurried” abstraction.</p><p>There are many reasons why this is probably an inappropriate abstraction — most of those reasons are hypothetical “what ifs” but still they need to be taken into account in order to ensure scalability for this project.</p><p>For example, what if in order for <strong>FacebookWidget</strong> to actually “open”, the user must login first or do some other action which has nothing to do with openWidget but it&#39;s really specific to Facebook? The open function would need to be more convoluted to handle that.</p><p>Also the testing of these components would be more complex as well because there would be cases where the open function tests fail and we don&#39;t know why as it could be broken in many places for various reasons.</p><h3>A Less Abstract Approach</h3><p>In order to deliver this feature in a bullet-proof way, we need to make the implementation more “isolated” for each widget and avoid all these complex abstractions.</p><p>A simple way that we can solve this problem is seen below:</p><pre>import FB from &#39;fb&#39;;<br>import Google from &#39;google&#39;;<br><br>const Facebook = {<br>    init() {<br>        /// ... 5 lines same for all init functions<br>        FB.init();<br>    }<br>    open() {<br>        // ... 5 lines same for all widgets open functions ...<br>        Fb.openWidget();<br>    }<br>    close() {<br>        Fb.closeWidget();<br>        // ... 5  lines same for all widgets close functions ...<br>    }<br>}<br><br>const Google = {<br>    init() {<br>        /// ... 5 lines same for all init functions<br>        Google.init();<br>    }<br>    open() {<br>        // ... 5 lines same for all widgets open functions ...<br>        Google.openWidget();<br>    }<br>    close() {<br>        Google.closeWidget();<br>        // ... 5  lines same for all widgets close functions ...<br>    }<br>}</pre><p>We can see here how we traded duplication for better handling of requirements and a more isolated (less abstract) approach. This implementation is at a better place handling any new requirements and changes (specific for each widget) in the future. Also the testing of these components would be easier as they are isolated (not composed as in the previous implementation).</p><p>Having said all that, I still believe that code abstraction and thinking in abstract terms when trying to solve a problem is really important and pretty fundamental in programming. But knowing <strong>when</strong> to apply the correct abstraction is even more important!</p><p>Catch you later! 😃</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/immature-abstractions"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24f9876ac01f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working from home: Pros & Cons]]></title>
            <link>https://medium.com/@tasoskakour/working-from-home-pros-cons-2e118122a2c1?source=rss-7cc6cee90c71------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e118122a2c1</guid>
            <category><![CDATA[remote-working]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[work-life-balance]]></category>
            <category><![CDATA[work]]></category>
            <category><![CDATA[home-working]]></category>
            <dc:creator><![CDATA[Tasos Kakouris]]></dc:creator>
            <pubDate>Tue, 09 Nov 2021 06:29:34 GMT</pubDate>
            <atom:updated>2021-11-09T06:29:34.768Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*RB4iTdEooW_THpqQ.jpg" /><figcaption>Shirt and a shorts is a way to go for meetings!</figcaption></figure><p>Hello!</p><p>Over the last two years I work exclusively from home. At the times we live in, I’m certain that many of you had to (or chose to) work remotely as well. In this article, I’ll analyze based on my personal opinion and experience, the advantages and disadvantages of working from home.</p><p>Be sure to check my website and blog <a href="https://tasoskakour.com/">https://tasoskakour.com</a> for more content like this!</p><h3>Pros</h3><h3>✔️ Increased Productivity</h3><p>Personally, when I work from home I feel more productive and there are almost no distractions at all. At my home office, there’s only me and my computer — there aren’t any people passing by or chatting/talks etc. I feel that my only task is just my work. Of course you could say that’s totally subjective as I’ve got some friends that they feel they’re more productive when they’re working from the office!</p><h3>✔️ Reduction of time wasted</h3><p>Due to the fact that my office stands a few meters away from my bedroom, the time and struggle needed to wake up earlier, get dressed 🙃 and then commute/walk/drive to work and back again, are completely eliminated. I can wake up at 8:59 and start working at 9:00. Combine this with a home-gym (or any kind of home work out) and by afternoon you’re able to complete your work and perform a workout session. Efficiency at its finest!</p><h3>✔️ Fits well with chores</h3><p>Depending on the workload of the day, I can take a break, go to the kitchen and cook/make something or just complete a chore that must get done. One example of how remote working fits well with chores and other tasks is when there was a plumber in my house to fix something I didn’t have to take the day off as I was already home!</p><h3>✔️ Digital Nomad 😎</h3><p>Remote working does not necessarily mean working from home. You can grab your laptop and work from anywhere in the world provided the fact there’s Internet. And by “anywhere in the world”, I mean some cafeteria, a restaurant, a hotel while you’re on vacation or some beach at Maldives (it’s not a joke, just google “remote working in Maldives” and you’ll find that there are packages and programs that are specialized just in this! 😄)</p><p>All jokes aside, the fact that I’m not physically bound to my work’s location is extremely helpful at many cases e.g when moving from one place to another. Personally I moved from Thessaloniki to Heraklion without the need to find another job!</p><h3>✔️ Home office and setup</h3><p>I can set up my home office exactly how I want to in terms of decoration and functionality. For example, I can try a different desk (e.g standing), another chair, add/remove monitors etc. Usually when we work at a professional setting inside a company, it’s harder to apply those kind of changes.</p><h3>Cons</h3><h3>❌ Lack of human connection</h3><p>In my opinion, one of the biggest disadvantages of working from home is the fact that complete interpersonal relationships and social connections are missing. When you get to see your colleagues only through video-calls, the social connection stops being 100% human and authentic. Actually seeing and meeting the other person and his/her body language plays an important role in human communication and bonding.</p><p>Furthermore, it’s impossible to crack a joke during work or just go for a coffee at the end of a workday or just have fun in any way outside of the digital world. Currently I work from home and I communicate with 5–10 colleagues that potentially could be 5–10 good friends if we were working together from the office.</p><h3>❌ Alienation</h3><p>Being inside a house for 8–10 hours a day for 5 days per week, combined with long-hour work in front of a monitor, can at times make me feel like an alienated robot. Especially when I don’t leave the house even after I finish my work; I feel like a zombie. Of course that’s a bit subjective as I know some people love spending the majority of their time inside their house (in Greece we call them housecats).</p><h3>❌ No personal-professional boundaries</h3><p>Having a home office and working from there is pretty convenient for many reasons as we explained above. However, at times I feel that I’d like to have a more strictly professional space where my mind would have it associated with just 100% professional work. Now and then when there’s confusion between my personal and professional space I feel some kind of lack of motivation.</p><h3>❌ Perks, Ιnternet etc</h3><p>Usually Internet at home (at least here in Greece!) is much slower than the Internet used insided companies’ offices. Moreover, there are usually some perks when working from the office like snacks/breakfast/coffee, better professional equipment, areas for entertainment (e.g table tennis) etc.</p><h3>Is it worth it after all?</h3><p>I believe that the fact that someone is able to work from home, provided the nature of work allows it, is a major advantage and a model that every modern company should adopt it or at least not prohibit it.</p><p>Personally, an ideal model is something that combines both remote and in-house working. For example, some companies follow a hybrid model of 3 days working from home and 2 days working from the office, combining in this way the benefits of both models!</p><p>What’s your thoughts? 🙂</p><p><em>Originally published at </em><a href="https://tasoskakour.com/blog/remote-working-props-and-cons"><em>https://tasoskakour.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e118122a2c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>