<?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 Ricciuti Paolo on Medium]]></title>
        <description><![CDATA[Stories by Ricciuti Paolo on Medium]]></description>
        <link>https://medium.com/@ricciutipaolo?source=rss-942765cc793c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*klyV_e9v4nto1H23110fmw.jpeg</url>
            <title>Stories by Ricciuti Paolo on Medium</title>
            <link>https://medium.com/@ricciutipaolo?source=rss-942765cc793c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 12:25:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ricciutipaolo/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[How to be original on the web. SPOILER: you can’t!]]></title>
            <link>https://medium.com/@ricciutipaolo/how-to-be-original-on-the-web-spoiler-you-cant-b347bf805c43?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b347bf805c43</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 09:38:33 GMT</pubDate>
            <atom:updated>2022-07-05T09:43:42.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*Kr6DXb2fgRfWxefx2Zfxxg.png" /></figure><p>While writing this Medium ask me to “Write my story” and today that’s exactly what i want to tell you: a story.</p><p>This might not be the latest, saviest article on the newest and coolest bleeding edge, blazingly fast technology but in my humble opinion it’s a cool story and it’s worth reading. Also it wont probably rob you of more than a couple of minutes so why not jump in and read?</p><p>Let’s start from the beginning: i’m browsing twitter (while you are at it, follow <a href="https://twitter.com/PaoloRicciuti">me</a> if you want) and someone wrote a simple comment under one of the WesBos tweet. I can’t remember the precise wording and i can’t really seem to find that comment again but it mention something that catch my attention. Is the hex color #BADA55. My first tought wass “Wow…thats cool, i might use it in some project just for a little swag inside my code”. My second tought was “Wait a minute maibe there are more words like this”. My third tought was “It could be very easy to build something where you could search about hex color that are similar to words”.</p><p>As i often do, knowing THE INTERNET, whenever i have an idea for something i try to search if there’s already something similar. So i hopped on google and i tryed to search without finding much. That’s cool i can build it!</p><p>The website is fairly simple but i nontheless needed to decide on a stack: i went for my favourite framework (Svelte) and my favourite hosting (Netlify). Given the simplicity of the website i didn’t needed much more: no database, no server. And so <a href="https://hexwords.netlify.app/">https://hexwords.netlify.app</a> was born.</p><p>I published it on twitter and on some subreddits. It started to gain traction and here it is the first glimpse of unoriginality: someone post on reddit a website that did something fairly similar. However their website was very slow and much more unneedlessly complicated (in my opinion). But than something happened: someone posted on Hacker News the web-app and it quickly went up to the frontpage and there in the top comment there was a link to the website that made me write this article: <a href="https://hex-colours.netlify.app/">https://hex-colours.netlify.app/</a></p><p>Looking at the website and their relative github page had my mind blown: the same title, the same concept, the same inspiration (it was still insired by WesBos #BADA55 usage), the same framework, the same hosting…heck it was even using the same sticky searchbar that i’ve come up with indipendently.</p><p>All of this really made me think about how can someone be original on the web when even the stupidest ideas are out there being developed and published every day.</p><p>I hope you liked this little story and let me know what you think about it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b347bf805c43" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useCallbackState: the hook that let you run code after a setState operation finished.]]></title>
            <link>https://medium.com/geekculture/usecallbackstate-the-hook-that-let-you-run-code-after-a-setstate-operation-finished-25f40db56661?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/25f40db56661</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Fri, 21 Jan 2022 09:27:59 GMT</pubDate>
            <atom:updated>2022-01-22T09:13:10.019Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EU5ECPbg5FD8PvQnSg7CWA.png" /></figure><p>The state in functional component in React is managed by the useState hook. This hook returns a tuple (an array with two elements, but you know tuple seems more technical), in which the first element is the state variable and the second element is a setter for this state.</p><p>This is unavoidable because that’s how React handles reactivity. React can know that it needs to rerender because you’ve used the setState function to mutate the state and if you try to directly mutate the state variable it wont re-render.</p><p>Another caveat of the setState fucntion is that it’s asynchronous: if you are running a function and you are setting the state you can’t access the updated value inside the same function. More importantly if you have to run some code after the variable has been set you have no way of doing it from inside that function. What you would have to do is create an useEffect that depends on the state variable that you are setting and do your logic inside the useEffect.</p><p>This is not only far less readable, it also has a small caveat that, in some specific cases might not be desiderable. You have no way to run the code only when that specific setState is runned. Using the useEffect your code will be runned every time that variable changes, no matter who changes it.</p><p>So let’s say you have to buttons that can set your state, and you only want to run code after button A setted the state but not when button B setted the state. You can’t do this with the useEffect approach.</p><p>Well, <strong>that changes today!</strong></p><h3>The useCallbackState hook</h3><p>I’ve created a custom hook that solve exactly this problem. The initial api is the same as the useState hook from react, with the only difference that the setState function can also take a callback as input. This callback is guaranteed to be called after the state has been updated and the new state is also passed as input.</p><p>Let’s take a look at the code and than we can comment about what it does.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e03ee44b1b9cef58bf5c2929eb3cb7e0/href">https://medium.com/media/e03ee44b1b9cef58bf5c2929eb3cb7e0/href</a></iframe><p>The first thing it does is create a state variable passing the initialValue. It then create a callbackQueue in a ref that start as an empty array.</p><p>Then we found the core of the hook: there’s an useEffect hook that runs again every time the state changes, loop over the array of callbacks and call each callback passing the new state. After looping over it it flush the queue.</p><p>Then there’s setState function that in the end get’s returned to the user: it takes the newValue and the callback as input, set the new state and if there’s a callback and it’s a function add the callback to the queue. This ensure that when the useEffect runs only the setState that did set a callback will get his code executed.</p><p>In the end we return the tuple to the user.</p><p>The usage is fairly simple:</p><pre>import useCallbackState from &quot;./hooks/useCallbackState&quot;;</pre><pre>import &quot;./styles.css&quot;;</pre><pre>export default function App() {</pre><pre>const [test, setTest] = useCallbackState&lt;boolean&gt;(true);</pre><pre>return (<br>    &lt;&gt;<br>        &lt;button onClick={() =&gt; { setTest((prev) =&gt; !prev,<br>            (newVal) =&gt;{<br>                console.log(&quot;The value changed&quot;, newVal);<br>            });}}&gt;<br>                Change<br>        &lt;/button&gt;<br>        &lt;button onClick={() =&gt; { setTest((prev) =&gt; !prev);}}&gt;<br>                Change noCallback<br>        &lt;/button&gt;<br>    &lt;/&gt;<br>);}</pre><p>The first button will fire the console log after the change, the second one will not.</p><p>I’ve also prepared a TypeScript version of the hook if you want a Type safe hook to work with your wonderful Typescript project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8db7bc4e27879c75c87d073c6c31288a/href">https://medium.com/media/8db7bc4e27879c75c87d073c6c31288a/href</a></iframe><p>And if you want to rapidly play with the hook here’s a code sandbox for your using pleasure.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F8ep4w&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F8ep4w&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8ep4w%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda755e2ffffe0163f19ba850bd50107/href">https://medium.com/media/cda755e2ffffe0163f19ba850bd50107/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25f40db56661" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/usecallbackstate-the-hook-that-let-you-run-code-after-a-setstate-operation-finished-25f40db56661">useCallbackState: the hook that let you run code after a setState operation finished.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to check for media queries in svelte with useMediaQuery]]></title>
            <link>https://medium.com/@ricciutipaolo/how-to-check-for-media-queries-in-svelte-with-usemediaquery-604f14190035?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/604f14190035</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[media-queries]]></category>
            <category><![CDATA[svelte]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Mon, 20 Dec 2021 17:52:02 GMT</pubDate>
            <atom:updated>2021-12-20T17:52:02.840Z</atom:updated>
            <content:encoded><![CDATA[<p>Media queries are a very useful tool in css. They let you define styles based on certain media characteristics like screen width, screen resolution and even preferred color scheme.</p><p>Using them in css is cool but sometimes, especially in declarative JS (like React, Vue or svelte) we might want to use a media query to show a different kind of information or to set different values. Luckily for us Javascript comes to the rescue.</p><p>Using <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia?retiredLocale=it"><strong>window.matchMedia</strong></a> we can pass a media query as string and get an object back where the property matches is true if the media query is true, false otherwise (you don’t say).</p><p>But this is a one time only value and it doesen’t combine well with the reactive world of JS frontend frameworks. But we are in luck again: we can set an event listener to the object that returns from matchMedia to get a callback everytime the media query changes value.</p><p>But this is a lot of code to write in every component we need this. So why not extrapolate this logic outside? In React we would make a custom hook but how about svelte?</p><p>We can make a <strong>store</strong>!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb20634730a28a7f95cfa27de665c4d9/href">https://medium.com/media/fb20634730a28a7f95cfa27de665c4d9/href</a></iframe><p>And here we go. If you have any question feel free to ask in the comment section and feel free to use this simple code in you svelte project!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=604f14190035" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlock the power of CTRL+Z in React state with useHistoryState]]></title>
            <link>https://medium.com/geekculture/unlock-the-power-of-ctrl-z-in-react-state-with-usehistorystate-7f93b7b62924?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f93b7b62924</guid>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Sun, 21 Nov 2021 18:44:24 GMT</pubDate>
            <atom:updated>2021-11-22T07:23:06.437Z</atom:updated>
            <content:encoded><![CDATA[<p>CTRL+Z is the developer best friend. You screwed your code at the point it’s no longer recognizable? Just CTRL+Z a bunch of times and you’ll be back on track.</p><p>CTRL+Z is also a basic shortcut for every major application at the point that the user almost expect to be able to CTRL+Z if it want’s to undo some mistake.</p><p>Most react application (and web applications in general) doesn’t care about this, if the state changed they don’t keep track of previous states. The logic to unlock this power is very very simple tho: just keep an array of all the states, a pointer and you are ready to go.</p><p>However re-write this logic in every component can become very tedious. This seems like the perfect candidate for a <strong>custom hook!</strong></p><h3>Custom hooks</h3><p>React has a set of <a href="https://reactjs.org/docs/hooks-overview.html">basic hooks</a> that can hook into the state and lifecycle of a functional component. For example the useState hook let you create a state variable, the useEffect let you run code when a dependency change etc etc.</p><p>You can combine those basic hooks into more complex ones simply by writing a function (it’s recommended to start those functions with the verb “use” so that react can check that all the <a href="https://reactjs.org/docs/hooks-rules.html">rules of the hooks</a> can apply).</p><h3>useHistoryState</h3><p>So let’s take a look at our own custom hook. We need a hook that contains a state hook for the value, a state hook for the history of states and a state hook for the pointer. Than we just need to write some functions (that we will define inside some useCallback for performance) that will handle setting the state from outside, undo-ing and redo-ing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*guJbUGb1qLnjdAHmLj6siA.png" /></figure><p>Let’s comment on those functions just to understand what we are doing:</p><p><strong><em>setState: </em></strong>takes the value the user want’s to set as input, if it’s of type function the function get’s called passing the old state value, that we add this value to the array of the history (we are slicing it to the current pointer so that if i went back in the history and than modified it again it will override all the future history), we increase the pointer by one and we set the actual state with _setState (a function that we never return)</p><p><strong><em>undo: </em></strong>pretty simple…if the pointer is lesser or equal to 0 we just return since there’s nothing left to undo. Otherwise we set the state with _setState to history at pointer-1 and decrease the pointer.</p><p><strong><em>redo: </em></strong>just like undo…if the pointer is greater or equal to the array lenght we just return since there’s nothing left to redo. Otherwise we set the state with _setState to history at pointer+1 and increase the pointer.</p><p>Here’s the code in a non-image format if you want to copy it for your personal use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7de12a3963509d27c40ccd687e594ae/href">https://medium.com/media/a7de12a3963509d27c40ccd687e594ae/href</a></iframe><p>I also wrote a Typescript version if you want to use it in your Typescript project</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a1a27533adb5643026cc9c3b9c4af42/href">https://medium.com/media/3a1a27533adb5643026cc9c3b9c4af42/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f93b7b62924" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/unlock-the-power-of-ctrl-z-in-react-state-with-usehistorystate-7f93b7b62924">Unlock the power of CTRL+Z in React state with useHistoryState</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Run code on component unmount with the custom hook “useOnUnmount”]]></title>
            <link>https://medium.com/geekculture/run-code-on-component-unmount-with-the-custom-hook-useonunmount-5355bd99e11e?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5355bd99e11e</guid>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[custom-hook]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Wed, 20 Oct 2021 11:22:20 GMT</pubDate>
            <atom:updated>2021-10-20T11:39:37.768Z</atom:updated>
            <content:encoded><![CDATA[<p>React Hooks: a cool addition to React since version 16.8.0.</p><p>Since then you can write functional components while still having class components state management functionalities. And since codng with hooks become the standard way of React-ing.</p><p>Each hook add a small functionality to functional components, for example useState is for the state (as you may guess from the name) and useRef replace createRef (again, the naming is on point).</p><p>Regarding the lifecycle events componentDidMount, componentDidUpdate, componentWillUnmount they all combine in a single hook: useEffect.</p><p>useEffect takes a callback function as input, that can return a function and an array of dependencies. Every time a dependency changes the return value from the previous callback get’s called and the callback get’s run again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRjTtjolWUkWuTUG86tdwA.png" /></figure><p>So for example: the first line get’s logged as soon as the Component mount, every time count get’s updated it will log the clearing (with the old value) and will re-run the useEffect. When the component is than unmounted a final “Clearing” get’s logged.</p><p>This seems to be pretty similar to componentWillUnmount right? Well not so fast. There’s a small caveat here: if you need to run some code only when the component is being unmounted and this code depends on some variable a problem emerges. To avoid running the code every single time a dependency changes you should omit that dependency from the array of dependencies but then the value used inside the clearing function is not the last one!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-VB-nnK0QA6Oc2gbLDCABw.png" /></figure><p>I’ve added the second use effect just to show you that count did in fact changed. But the clearing does not registered the change. And this could be a problem.</p><h3>The solution</h3><p>The solution to this problem is simple: we need to create a ref (that does not trigger a re-render) and set the initial value to false. We can than add the value as a dependency and check if the current value of the ref is false inside the return value of the useEffect and run the code only if it’s not false. Than we will set the value of the ref to true in a separate useEffect without the dependency.</p><p>Wrapping everything we’ve said in a custom hook produces this cool and easy to use hook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*mdtoLprzKUj1vkl7JTna4g.png" /></figure><p>Using this hook will result in code execution with updated dependencies only when the component will really unmount.</p><p>I’ll leave a link to the code sandbox if you want to experimenti with this or simply if you want to copy the hook.</p><p><a href="https://codesandbox.io/s/useonunmount-xfcwp?file=/src/useOnUnmount.js">https://codesandbox.io/s/useonunmount-xfcwp?file=/src/useOnUnmount.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5355bd99e11e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/run-code-on-component-unmount-with-the-custom-hook-useonunmount-5355bd99e11e">Run code on component unmount with the custom hook “useOnUnmount”</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Abstract layouts with Higher Order Components (HOC) in React.]]></title>
            <link>https://medium.com/geekculture/abstract-layouts-with-higher-order-components-hoc-in-react-da8379f18c9a?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/da8379f18c9a</guid>
            <category><![CDATA[higher-order-components]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[abstract]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 16:26:05 GMT</pubDate>
            <atom:updated>2021-10-20T11:39:48.588Z</atom:updated>
            <content:encoded><![CDATA[<p>Back in the days it was very difficult to create a website with a consistent layout. If you wanted you would need to use iframes in the best case scenario, frameset in the worst.</p><p>In those days javascript was something that most people feared on the web and almost everyone even had it disabled (crazy to think these days).</p><p>But the ability to have a fixed and a dynamic part of the layout was something that web developers and web designers always covet. It’s a common design pattern to have a lateral menù that let the user to access various parts of the website from whenever he is, and having a top bar that shows the name of the website is a branding choice that almost everyone follows.</p><p>Luckly for use we are not back in the days anymore: javascript compose like 90% of the web, and with it comes a series of capabilities that a lot of libraries and frameworks take advantage of.</p><h3>The modern days: React</h3><p>React as you may know if you clicked on this article is a javascript libraries that let you specify your design in a declarative way: you describe your design just like you would do with HTML but you can sprinkle javascript variables inside of it and React will do the magic and will render this to the DOM for you.</p><p>But how can you achieve this composite layout with react?</p><p>Presenting you: react-router.</p><p>react-router is the “<em>de facto</em>” library to handle routes in a react application. It looks at the pathname of the page you are in and you can specify programmatically which component needs to render in a specific moment.</p><p>But that’s enaugh talking, let’s see and example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*kpYDGdteDLpDsXv7mGTUhA.png" /></figure><p>This is a simple React App…BrowserRouter is the provider for the route and the Switch (both components are from the <em>react-router-dom </em>library) takes care to check which route we are on and display either the Home component or the About component.</p><p>The result speaks for itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fh8Rmh2SExXlu6yY-ZS_kQ.png" /></figure><p>But this does not help with our situation. Let’s create some Navigation component and an AppBar component and let’s stile this application a bit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*ZhxGJVDYiAkrl8iR8CQsCQ.png" /></figure><p>The Navigation is just a ul with some Link (the a tag of react-router-dom) component inside that points to various pages. The appbar is just a div with the name of out fabolous webapp. Everything is wrapped inside a container that position those elements with grid and here we have our common webapp layout:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5VbNt1akmYvLZfeb0n1-w.png" /><figcaption>The layout in the home page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xnb9wUcW-BzIe6k-Pngdg.png" /><figcaption>The layout in the about page</figcaption></figure><p>That’s pretty cool. And you can definitely tell that i’m a developer and not a designer. But than let’s say an actual designer comes and say “Hey…you know what would be cool? The central area could have a white background with a slight shadow to better focus on the content. Could you do it?”.</p><p>You can bet your favourite IDE that i can. I just need to add the styles to the content class right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQ_QEYL4lQ030d5sHsVN9g.png" /></figure><p>“Here we go” said the proud developer to the designer. But than the designer said something that terrified the inexperienced developer: “Mmm…it’s cool but…can’t we add the title of the page on top of this border?”.</p><p>Well that changes something. The container doesen’t know what page is being rendered. There are different solution that one can develop to solve this problems but many have bad designs that would require a lot of work to be mantained:</p><ol><li>You could simply move the border inside every component and write the title directly inside of the component. But this means every time you write a new component you have to write the whole code to put the title and the border and if you ever want to change the layout you have to go through every single component to update it.</li><li>You could create a new component that takes the component and the title as props and render them correctly. But this means that in the main page of the app you have to remember to not render the actual component but this wrapper component with the correct props. It doesn’t help with readability.</li><li>You could add a state variable in the App.js and pass down the setter as a props to every component and then call this setter inside of a useEffect in the component. Still not a wonderful readability.</li></ol><p>But then our developer remembered of something that it read in an awesome article on Medium.</p><h3>HOC (Higer order Components)</h3><p>Javascript it’s a cool language. And it’s a functional language. What does it means? It means you can store functions in variables and pass them around even as argouments for others functions.</p><p>There’s a specific sub category of functions called Higher Order Functions. Those are functions that either take functions as input or return functions. Some examples of those function are the map function for arrays or the useState function in React.</p><p>And given that React components are just functions that take props as input and returns a render function we can combine those knowledge and create our first Higher Order Component.</p><p>As the name suggest those component are actually functions that take a Component and whatever args you want as input and returns a function that return a render function (so basically a new component)…let’s take a look at how can we use it in out application:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*e354oXx4yILIdm75hCXidA.png" /></figure><p>This is our HOC: it takes a Component and the title as input args and returns a function that takes props as input and return a render function. This render function render a titled container (a simple grid to lay the title and the content one under the other) a span for the title and the component in the args passing all the props down.</p><p>We than need to modify the old css in App.js to remove the box we added (since it’s now a responsability of this HOC to render the box around the view) and we need to modify the Home and About page as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*dYcKqX39uSDcMxBs2yRsEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*wwO_Ucfb4KtuRUi86z03Yw.png" /></figure><p>Notice how the only thing i had to change is the export value. Instead of just exporting the component i’ve exported the component wrapped in the withTitle function and i’ve passed the title that has to be rendered.</p><p>I’ve also added a new Component, a Dashboard that needs to be rendered without the title and without the box just to show how easy is to decide wether or not i want a titled component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*T6a5kLx2Vpeb0A_Kx8iz1g.png" /></figure><p>And the best thing is…in App.js i don’t need to change anything…i’ll just have the same, good and readable code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*ydUs6N6pubb3saJ7SQkr4g.png" /></figure><p>And now for the final reveal here’s how the webapp looks with all those changes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vk3_Ql6P2GcQjdPRSUzjvQ.png" /><figcaption>The Home page with the title Home and the box around</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_nm1bLxiSR80yCTxbRAxw.png" /><figcaption>The About page with the title About and the box around</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jn-71zyBWhD8rxqw-qzp0g.png" /><figcaption>The Dashboard page without border and title</figcaption></figure><p>So here we go. We’ve made a developer friendly way to mantain a consistent design and the only thing we have to do if we want to change how the title appears is change one single file.</p><p>This whole Higher Order Components things can be useful even with something other than layouts. For example you could add a check on the user authentication to perform before rendering a private view, or do an api call that get’s passed down as props to every components that uses the HOC.</p><p>I’ll leave here a link to the code sandbox if you want to experiment with my code so far.</p><p>If you have any question feel free to ask them in the comments section.</p><p><a href="https://codesandbox.io/s/hoc-dnx9e">https://codesandbox.io/s/hoc-dnx9e</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da8379f18c9a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/abstract-layouts-with-higher-order-components-hoc-in-react-da8379f18c9a">Abstract layouts with Higher Order Components (HOC) in React.</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lazy Loading images with React.js and IntersectionObserverApi]]></title>
            <link>https://medium.com/geekculture/lazy-loading-images-with-react-js-and-intersectionobserverapi-6cd7bbe97969?source=rss-942765cc793c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cd7bbe97969</guid>
            <category><![CDATA[observer]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ricciuti Paolo]]></dc:creator>
            <pubDate>Fri, 02 Jul 2021 13:56:48 GMT</pubDate>
            <atom:updated>2021-07-05T16:54:11.695Z</atom:updated>
            <content:encoded><![CDATA[<p>The web is fast. Like superfast. I mean you can literally talk with the other end of the world in a matter of (depending on your connection) seconds.</p><p>But as usual, the faster something goes the faster an user will want it to go.</p><p>Unfortunately the nicest pieces of a website are also the slowest to load: <strong>images</strong>.</p><p>Web Developers have devevoped (HA…did you got it?) various way to vastly imporve the user experience regarding loading images. The most used one is <strong>Lazy loading.</strong></p><h3>What is Lazy Loading?</h3><p>An image is, as we’ve said, really important for a website. But it’s not very important until it actually is in the viewport. If there was an image at the end of this article most of you would probably never seen that image (clever way to auto-criticize my boring write style) so most of you should not spend the time to download that image. Lazy loading is exactly this: an image is not downloaded unless it is actually in the viewport.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqJ_t-jmwRcJucrrBVsDEQ.png" /></figure><p>In the old days developer added listeners on the scroll event to check if an image was in the viewport or not but nowdays we have something way better: <strong>IntersectionObservers!</strong></p><h3>How Intersection Observer works?</h3><p>This new API let you <em>observe</em> an element and will trigger a callback everytime it’s intersection with the viewport will change (yeah, you get an event also when the element leave the viewport). How it works? It’s very simple:</p><p>We first declare a new intersection observer. Here we have to specify the callback and some options:</p><pre>const options = {};<br>const observer = new IntersectionObserver((entries, obs) =&gt; {<br>    for (const entry of entries) {<br>        //entry.boundingClientRect<br>        //entry.intersectionRatio<br>        //entry.intersectionRect<br>        //entry.isIntersecting<br>        //entry.rootBounds<br>        //entry.target<br>        //entry.time<br>    }<br>}, options);</pre><p>we can skip over the options for the moment and take a look at the callback. It takes two parameters in:</p><p><strong>Entries</strong>: this is the list of every element of the dom observer by this observer. Each entry will have the following properties:</p><ul><li>boundingClientRect: the reactagle around the element visibile inside the viewport</li><li>intersectionRatio: how much of the component is visible inside the viewport</li><li>isIntersecting: pretty self-explanatory….true if the element is intersecting with the viewport, false otherwise</li><li>rootBounds: if a root element is declared inside the options the boundingClientRect with the root element</li><li>target: the element itself</li><li>time: the time at which the intersection was recorded</li></ul><p><strong>Obs: </strong>this is the observer itself, it can be used to change the behavior of the observer after one “observation” fired.</p><p>This API basically can help us run some code whenever an object comes into view or goes out of the view.</p><p><em>N.b. One small caveat of the intersection observer api is that the first time every observed element will fire the callback even if it’s outside the screen.</em></p><h3>Ok but how to apply this with react?</h3><p>Now that we have all this informations we can easily write a reusable component with React that will load an image only when it comes into the viewport. Let’s see the class and we will discuss how it works later:</p><pre>import React, { useEffect, useRef, useState } from &#39;react&#39;;<br>import placeholder from &#39;../imgs/placeholder.png&#39;;</pre><pre>const LazyImg = props =&gt; {<br>    const [inView, setInView] = useState(false);<br>    const placeholderRef = useRef();<br>    useEffect(() =&gt; {<br>        const observer = new IntersectionObserver((entries, obs) =&gt; {<br>        for (const entry of entries) {<br>            if (entry.isIntersecting) {<br>                setInView(true);<br>                obs.disconnect();<br>            }<br>        }<br>   }, {});<br>    observer.observe(placeholderRef.current);<br>    return () =&gt; {<br>        observer.disconnect();<br>    }<br>}, []);</pre><pre>return (<br>    inView ? &lt;img {...props} alt={props.alt || &quot;&quot;} /&gt; : &lt;img {...props} ref={placeholderRef} src={placeholder} alt={props.alt || &quot;&quot;} /&gt;<br>)<br>};<br>export default LazyImg;</pre><p>Let’s how it works: this component will use a single state variable: inView. Will also use a ref to reference a placeholder imgs (that’s just a transparent image we will have in our assets). Being initialized to false when the component is first mounted it will show the placeholder image with the same props of the you would pass to an img tag. The useEffect will then run and will create an IntersectionObserver that will observe the placeholder image. The callback is also very simple: whenever the callback is called it will loop through every entries (we can be sure it will be just one, the placeholder element) and check if it’s intersecting with the viewport. If it is will set the state inView to true and than disconnect the observer (so that it will never fire again). Finally the use effect will return a function (that will be called onUnmount to disconnect the observer.</p><p>If you use this component instead of a simple &lt;img &gt; tag you can easily inspect the network tab in you browser to see that it actually do the request to download the image only when it comes into view.</p><h3>Conclusions and a small extra tip</h3><p>Feel free to use this component if you want to save load time and mobile data to your users without affecting the user experience at all.</p><p><em>Extra tip: you can use the options passed to the intersection observer to fine tune how the intersection observer should work. One of the possible options if ‘rootMargin’…by setting a negative bottom margin you can start to load the images a little bit before they comes into view so that whenever the user will reach the image it will probably already be loaded.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cd7bbe97969" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/lazy-loading-images-with-react-js-and-intersectionobserverapi-6cd7bbe97969">Lazy Loading images with React.js and IntersectionObserverApi</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>