<?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 Mykyta Prus 🇺🇦 on Medium]]></title>
        <description><![CDATA[Stories by Mykyta Prus 🇺🇦 on Medium]]></description>
        <link>https://medium.com/@nikitaprus98?source=rss-5d54bd1420c3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dp6-BHzSZ-F0mYBwzVVQQg.jpeg</url>
            <title>Stories by Mykyta Prus 🇺🇦 on Medium</title>
            <link>https://medium.com/@nikitaprus98?source=rss-5d54bd1420c3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:43:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikitaprus98/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[Train Smarter: Avoid This Beginner’s Mistake. What Injuries Taught Me About Health & Training.]]></title>
            <link>https://medium.com/@nikitaprus98/train-smarter-avoid-this-beginners-mistake-6dc20f58bd32?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/6dc20f58bd32</guid>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[fitness]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[running]]></category>
            <category><![CDATA[wellness]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 09:08:29 GMT</pubDate>
            <atom:updated>2025-11-20T09:12:44.449Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bI8shwfIZnakytEuOkJ1rA.jpeg" /></figure><p>I wrote this article for people who love to work out as much as I do. I’m not a doctor, coach, or fitness expert, but I’d like to share my experience on why recovery is important even if you’re not an elite athlete.</p><h3>Beginner’s mistake</h3><p>I mention that we amateurs have a common mistake. We tend to focus more on workouts and separate them from the rest of our lives. Because of that, we have a lot of stress that leads us to injuries.</p><h3>My painful experience</h3><p>I have trained for most of my life; my first competition was when I was 7. Since then, I have always been involved in some way in physical activity. After I turned 21, I got hooked on running and ran a lot, making many mistakes because of the “no pain, no gain” mindset. My last spinal injury (protrusion) forced me to rethink my attitude toward training and my body.</p><h3>Holistic training approach</h3><p>I stopped looking at workouts as a separate part of my life. Instead, I look at them as part of my life. I started asking questions like — will this workout make me healthier? Now, when I plan my workouts, I always include recovery and mobility exercises in my routine. If I have poor sleep or too much stress at work or in my personal life, I do an easier workout or even skip it rather than force myself to stick to the plan.</p><p>I always remind myself that what really matters is not how I perform from day to day, but whether I can consistently train and grow for months or even years — that’s what really matters. Usually, we overestimate what we can do in a day and underestimate what we can do in a month or year. The power of small, consistent habits is bigger than you think.</p><h3>My advice to myself in the past</h3><p>There are no shortcuts. There is no best workout, diet, or other thing that will transform your life. It’s all about changing your habits. Always ask yourself: Can I stick to this routine or diet for the rest of my life? If the answer is no, you probably need to search for a better option.</p><p>This is a very complicated topic. That’s why I want to recommend one book and one YouTube channel that changed my attitude toward training and fitness.</p><p>First is the book called <a href="https://www.amazon.com/Built-Move-Essential-Habits-Freely/dp/0593534808">Built to Move: The Ten Essential Habits to Help You Move Freely and Live Fully</a>. This book is a practical guide on how to transform your life and be a more active and healthier person. It’s not easy; it’s all about small habits that really pay off in the future.</p><p>Second is the YouTube channel <a href="https://www.youtube.com/@BreatheAndFlow">Breathe and Flow</a>. Their channel has a lot of exercises, as well as meditation and other useful videos. I always do some of their videos as part of my mobility and recovery routine.</p><p>Thank you for reading this far. I hope you learned something useful.</p><p>Train smarter, not harder.</p><p>Peace ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6dc20f58bd32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Tried Intermittent Fasting for 30 Days]]></title>
            <link>https://medium.com/@nikitaprus98/i-tried-intermittent-fasting-for-30-days-ec32989ad04f?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec32989ad04f</guid>
            <category><![CDATA[fitness]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[intermittent-fasting]]></category>
            <category><![CDATA[personal-development]]></category>
            <category><![CDATA[nutrition]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 08:48:48 GMT</pubDate>
            <atom:updated>2025-10-19T08:48:48.231Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lh-khvtZjpJj_6_F" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=medium&amp;utm_medium=referral">charlesdeluvio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Intermittent fasting has become increasingly popular lately. As someone interested in health and fitness, I decided to see what the hype was about and tried it for 30 days.</p><h3>What Is Intermittent Fasting?</h3><p>Intermittent fasting, or time-restricted eating, is a pattern where you alternate between periods of eating and fasting.</p><p>The two most common approaches are (in my opinion):</p><ol><li><strong>16/8:</strong> Eating within an 8-hour window and fasting for 16 hours — for example, eating between 10 a.m. and 6 p.m.</li><li><strong>12/12:</strong> Eating within a 12-hour window and fasting for the other 12 — for example, between 8 a.m. and 8 p.m.</li></ol><h3>My Experience with Intermittent Fasting</h3><p>I first learned about intermittent fasting from a podcast by Dr. Andrew Huberman, who explained its science and practical benefits.</p><p>Here’s the link if you’d like to listen:<br><a href="https://youtu.be/D61jJJPIQeo?si=wQMvdZEpPpB0t8L-">Dr. Huberman Podcast on Intermittent Fasting</a></p><p>My main takeaways were:</p><ul><li>Avoid consuming calories for at least one hour after waking up.</li><li>Stop eating at least three hours before bedtime.</li></ul><p>Since I train regularly, I chose the 12/12 schedule — the 16/8 version felt too restrictive for my energy needs.</p><p>My typical day looked like this:</p><ul><li>Wake up between 7 and 7:30 a.m.</li><li>Train from 8 to 9:30 a.m.</li><li>First meal around 10–11 a.m.</li><li>Last meal between 7 and 8 p.m.</li></ul><h3>After 30 Days</h3><p>The 30 days went by quickly. It didn’t change my life, but I liked it, — here’s why:</p><ul><li><strong>Better sleep</strong>. Finishing my last meal three hours before bed helps me fall asleep faster and sleep more deeply.</li><li><strong>Easier mornings</strong>. With better sleep, I wake up more easily and rarely feel the need to nap during the day.</li></ul><p>The only downside is the strict schedule. Sometimes, I break it when I’m out with friends or having dinner with my wife. I didn’t include those days in the experiment — I prefer flexibility over being a slave to a routine.</p><p>Overall, intermittent fasting works well for me, so I’ve kept following 12/12–14 hours version, adjusting it to fit my lifestyle.</p><p>Thanks for reading! I hope you found it interesting.</p><p>Peace ✌️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec32989ad04f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a login form with react-hook-form package]]></title>
            <link>https://blog.stackademic.com/create-a-login-form-with-react-hook-form-package-ab1634a206c9?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1634a206c9</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react-hook-form]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[validation]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Mon, 15 Jan 2024 08:00:36 GMT</pubDate>
            <atom:updated>2024-01-17T01:11:59.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-ww571U7IPOmqcqJ" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Almost all websites have forms, there are a bunch of different types of forms and approaches to handle form validation and submission, so in this series of articles I’m going to show you how to work with forms using the <a href="https://react-hook-form.com/get-started">react-hook-form</a> library. We’ll look at three examples of different forms, that is <em>login form</em>, <em>registration form</em>, and <em>checkout form</em>, hopefully, it will be interesting and helpful for you, so enough said, let’s get down to business.</p><h3>Table of contents</h3><ul><li>Create a Login form</li><li>Setup react-hook-form</li><li>Handle form submission and validation</li><li>Conclusion</li><li>Resources</li></ul><h3>Login Form</h3><p>For this project, I’ll use <a href="https://vitejs.dev/guide/#scaffolding-your-first-vite-project">vite + react-ts</a> template. I won’t show you how to set up the project because I want to focus on the form functionality. I’ll leave a link to GitHub in the resources section at the end of this article, so you can find all the code there.</p><p>All right, here is what our login form will look like:</p><figure><img alt="Login form" src="https://cdn-images-1.medium.com/max/741/1*EPEIbULdh5zn2jidTPiNMg.png" /><figcaption>Login form design</figcaption></figure><p>As you can see, there is a simple login form with two inputs (I use <a href="https://tailwindcss.com/">tailwindcss</a> for styling). Now it’s time to add react-hook-form.</p><h3>Setup react-hook-form</h3><p>Install react-hook-form:</p><pre>npm install react-hook-form</pre><p>Let’s use it in our form. The first step is to import <a href="https://react-hook-form.com/docs/useform">useForm</a> hook which gives us all the tools to manage our form.</p><pre>/// &lt;reference types=&quot;vite-plugin-svgr/client&quot; /&gt;<br>import ReactLogo from &quot;../../assets/react.svg?react&quot;;<br><br>import { useForm } from &quot;react-hook-form&quot;;<br><br>const LoginForm = () =&gt; {<br>  const { register } = useForm();<br><br>  return (<br>    &lt;&gt;<br>      &lt;div className=&quot;flex min-h-full flex-1 flex-col justify-center px-6 py-12 lg:px-8&quot;&gt;<br>        &lt;div className=&quot;sm:mx-auto sm:w-full sm:max-w-sm&quot;&gt;<br>          &lt;ReactLogo className=&quot;mx-auto h-10 w-auto&quot; /&gt;<br><br>          &lt;h2 className=&quot;mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900&quot;&gt;<br>            Sign in to your account<br>          &lt;/h2&gt;<br>        &lt;/div&gt;<br><br>        &lt;div className=&quot;mt-10 sm:mx-auto sm:w-full sm:max-w-sm&quot;&gt;<br>          &lt;form className=&quot;space-y-6&quot;&gt;<br>            &lt;div&gt;<br>              &lt;label<br>                htmlFor=&quot;email&quot;<br>                className=&quot;block text-sm font-medium leading-6 text-gray-900&quot;<br>              &gt;<br>                Email address<br>              &lt;/label&gt;<br>              &lt;div className=&quot;mt-2&quot;&gt;<br>                &lt;input<br>                  id=&quot;email&quot;<br>                  name=&quot;email&quot;<br>                  type=&quot;email&quot;<br>                  autoComplete=&quot;email&quot;<br>                  className=&quot;block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;div className=&quot;flex items-center justify-between&quot;&gt;<br>                &lt;label<br>                  htmlFor=&quot;password&quot;<br>                  className=&quot;block text-sm font-medium leading-6 text-gray-900&quot;<br>                &gt;<br>                  Password<br>                &lt;/label&gt;<br>              &lt;/div&gt;<br>              &lt;div className=&quot;mt-2&quot;&gt;<br>                &lt;input<br>                  id=&quot;password&quot;<br>                  name=&quot;password&quot;<br>                  type=&quot;password&quot;<br>                  autoComplete=&quot;current-password&quot;<br>                  className=&quot;block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6&quot;<br>                /&gt;<br>              &lt;/div&gt;<br>            &lt;/div&gt;<br><br>            &lt;div&gt;<br>              &lt;button<br>                type=&quot;submit&quot;<br>                className=&quot;flex w-full justify-center rounded-md bg-indigo-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600&quot;<br>              &gt;<br>                Sign in<br>              &lt;/button&gt;<br>            &lt;/div&gt;<br>          &lt;/form&gt;<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    &lt;/&gt;<br>  );<br>};<br><br>export default LoginForm;</pre><p>Next thing I’ll write types and set default values:</p><pre>type FormValues = {<br>  email: string;<br>  password: string;<br>};<br><br>const { register } = useForm&lt;FormValues&gt;({<br>  defaultValues: {<br>    email: &quot;&quot;,<br>    password: &quot;&quot;,<br>  },<br>});</pre><p>Now we are ready to start handling form validation and submission.</p><h3>Handle form submission and validation</h3><p>There are different ways to validate forms, you can explore all of them in <a href="https://react-hook-form.com/docs">react-hook-form docs</a>, I’ll start with the basic one. For that, we need <a href="https://react-hook-form.com/docs/useform/register">register</a> function from useForm hook.</p><pre>const { register } = useForm&lt;FormValues&gt;({<br>  defaultValues: {<br>    email: &quot;&quot;,<br>    password: &quot;&quot;,<br>  },<br>});</pre><p>The register function has different props like onChange, onBlur, name, and ref which we need to manage our input.</p><p>Here is how we can use the register function to validate the email input field:</p><pre>   &lt;input<br>      id=&quot;email&quot;<br>      type=&quot;email&quot;<br>      autoComplete=&quot;email&quot;<br>      className=&quot;block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6&quot;<br>      {...register(&quot;email&quot;, {<br>        required: {<br>          value: true,<br>          message: &quot;Email is required&quot;,<br>        },<br>      })}<br>    /&gt;</pre><p>Let’s do the same with our password:</p><pre>&lt;input<br>  id=&quot;password&quot;<br>  type=&quot;password&quot;<br>  autoComplete=&quot;current-password&quot;<br>  className=&quot;block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6&quot;<br>  {...register(&quot;password&quot;, {<br>    required: {<br>      value: true,<br>      message: &quot;Password is required&quot;,<br>    },<br>  })}<br>/&gt;</pre><p>The default form submission behavior is to send request to the server and reload the page, so let’s prevent it and add <a href="https://react-hook-form.com/docs/useform/handlesubmit">handleSubmit</a> function from useForm hook.</p><pre>  const { register, handleSubmit } = useForm&lt;FormValues&gt;({<br>    defaultValues: {<br>      email: &quot;&quot;,<br>      password: &quot;&quot;,<br>    },<br>  });<br><br><br>  const onSubmit = (formData: FormValues) =&gt; {<br>    console.log(formData);<br>  };<br><br> &lt;form className=&quot;space-y-6&quot; onSubmit={handleSubmit(onSubmit)}&gt;<br>  //... rest of the form</pre><p>By doing this now we can log the form state and see errors when we submit our form with empty values.</p><pre>  const { register, handleSubmit, formState } = useForm&lt;FormValues&gt;({<br>    defaultValues: {<br>      email: &quot;&quot;,<br>      password: &quot;&quot;,<br>    },<br>  });<br><br>  const { errors } = formState;<br><br>  console.log(errors);</pre><figure><img alt="Console form errors" src="https://cdn-images-1.medium.com/max/1024/1*RZ-3XoL5ImNGXY6MpqDLQA.png" /><figcaption>Form errors</figcaption></figure><p>In the console you can see our error message, but if you enter some values and submit the form it should log your input to the console.</p><figure><img alt="Console form data" src="https://cdn-images-1.medium.com/max/1024/1*R9j0nwut2QgxpA8KU_Ny1g.png" /><figcaption>Form values</figcaption></figure><p>Not let’s validate email and password fields.</p><p>Register function has validate property that accepts and object where you can write function for checking different cases, see below how it looks like:</p><pre> &lt;input<br>    id=&quot;email&quot;<br>    type=&quot;email&quot;<br>    autoComplete=&quot;email&quot;<br>    className=&quot;block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6&quot;<br>    {...register(&quot;email&quot;, {<br>      required: {<br>        value: true,<br>        message: &quot;Email is required&quot;,<br>      },<br>      validate: {<br>        isValidEmail: (value) =&gt;<br>          /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(<br>            value<br>          ) || &quot;Email is not valid&quot;,<br>      },<br>    })}<br>  /&gt;</pre><p>Here I add prop isValidEmail where I check if user input matches to email regex, if not I return an error message.</p><p>Let’s do the same for the password field, but change the rules. Here is a list of rules which password should meet to pass validation:</p><ul><li>Have more than 8 characters</li><li>Contains a capital letter</li><li>Contains a lowercase</li><li>Contains a number</li></ul><pre>&lt;input<br>  id=&quot;password&quot;<br>  type=&quot;password&quot;<br>  autoComplete=&quot;current-password&quot;<br>  className=&quot;block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6&quot;<br>  {...register(&quot;password&quot;, {<br>    required: {<br>      value: true,<br>      message: &quot;Password is required&quot;,<br>    },<br>    validate: {<br>      minLength: (value) =&gt;<br>        value.length &gt;= 8 ||<br>        &quot;Password should has more than 8 characters&quot;,<br>      isCapitalLetter: (value) =&gt;<br>        /[A-Z]/.test(value) ||<br>        &quot;Password should has at least one capital letter&quot;,<br>      isLowerCaseLetter: (value) =&gt;<br>        /[a-z]/.test(value) ||<br>        &quot;Password should has at least one lower case letter&quot;,<br>      isContainNumber: (value) =&gt;<br>        /\d/.test(value) ||<br>        &quot;Password should has at least one number&quot;,<br>    },<br>  })}<br>/&gt;</pre><p>Looks nice now, I’ll add some styles to display an error message to the user. For this, we need to install the package:</p><pre>npm install @hookform/error-message</pre><p>After installing error-message package I’ll add error messages and style them:</p><pre>// ...code above<br>&lt;ErrorMessage<br>  errors={errors}<br>  name=&quot;email&quot;<br>  render={({ message }) =&gt; (<br>    &lt;p className=&quot;text-red-500&quot;&gt;{message}&lt;/p&gt;<br>  )}<br>/&gt;<br>// ...code below<br>&lt;ErrorMessage<br>  errors={errors}<br>  name=&quot;password&quot;<br>  render={({ message }) =&gt; (<br>    &lt;p className=&quot;text-red-500&quot;&gt;{message}&lt;/p&gt;<br>  )}<br>/&gt;</pre><p>Now when I have some errors we can see a nice error message:</p><figure><img alt="Login form with error messages" src="https://cdn-images-1.medium.com/max/960/1*6-D1_HI4jvQc7lmdskuSeA.png" /><figcaption>Form with error messages</figcaption></figure><p>That is for this article.</p><h3>Conclusion</h3><p>Let us recap what we have done in this article. First we created a login form, next we added basic validation, also we added more advanced validation for both email and password fields, and we added a nice error message to inform users. So, hope it will be helpful to you!</p><h3>Resources</h3><ul><li><a href="https://github.com/AgentPrus/rhf-tutorial/tree/login-form">GitHub repo with code</a></li><li><a href="https://react-hook-form.com/">React-hook-form official docs</a></li><li><a href="https://youtube.com/playlist?list=PLC3y8-rFHvwjmgBr1327BA5bVXoQH-w5s&amp;si=ztLp_64rUUgJaGAv">Good react-hook-form tutorial for beginners</a></li><li><a href="https://tailwindcss.com/">Tailwind docs</a></li></ul><h3>Stackademic</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a><strong> |</strong> <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a></li><li>Visit our other platforms: <a href="https://plainenglish.io/"><strong>In Plain English</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1634a206c9" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/create-a-login-form-with-react-hook-form-package-ab1634a206c9">Create a login form with react-hook-form package</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keyboard Navigation for List in React]]></title>
            <link>https://blog.stackademic.com/keyboard-navigation-for-list-in-react-c8adb8f4257d?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8adb8f4257d</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 10:44:19 GMT</pubDate>
            <atom:updated>2023-12-07T01:40:08.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dkNoTi20iTPSOHPe" /><figcaption>Photo by <a href="https://unsplash.com/@emtm17?utm_source=medium&amp;utm_medium=referral">Marissa&amp;Eric</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Intro</h3><p>I have an interesting task to create a suggestion list with keyboard navigation. The most difficult part of this task was to give the user the ability to navigate through the list using the arrow keys. So in this article, I will show you how to create a list with arrow key navigation.</p><h3>TL;DR</h3><blockquote>useRoveFocus — this custom hook is all you need for navigation</blockquote><pre>import { useMemo, useState } from &#39;react&#39;;<br><br>import { useKeyPressEvent } from &#39;react-use&#39;;<br><br>const useRoveFocus = (size: number) =&gt; {<br>  const [currentFocus, setCurrentFocus] = useState(0);<br><br>  useKeyPressEvent(&#39;ArrowDown&#39;, () =&gt; setCurrentFocus(currentFocus === size - 1 ? 0 : currentFocus + 1));<br>  useKeyPressEvent(&#39;ArrowUp&#39;, () =&gt; setCurrentFocus(currentFocus === 0 ? size - 1 : currentFocus - 1));<br><br>  return useMemo(() =&gt; [currentFocus, setCurrentFocus] as const, [currentFocus]);<br>};<br><br>export default useRoveFocus;</pre><h3>Table of contents</h3><ul><li>Project setup</li><li>Project Overview</li><li>Implement arrow key list navigation</li><li>Conclusion</li><li>Resources</li></ul><h3>Project setup</h3><p>I will use <a href="https://vitejs.dev/guide/#scaffolding-your-first-vite-project">Vite + React TS</a> template for this example. You can check their docs, for setup instructions. Also, for styles, I’ll use tailwindCSS. This is tailwind <a href="https://tailwindcss.com/docs/guides/vite">setup guide</a> for Vite.</p><h3>Project Overview</h3><p>I’ve made a basic project with a list of users.</p><figure><img alt="List of users" src="https://cdn-images-1.medium.com/max/1024/1*XaJ2BTn2FC_QqBpnbo-Sbw.png" /><figcaption>List of fake users</figcaption></figure><p>I have a List component:</p><pre>const List = () =&gt; {<br><br>  return (<br>    &lt;ul role=&quot;list&quot; className=&quot;divide-y divide-gray-100&quot;&gt;<br>      {directory.map((person, index) =&gt; (<br>        &lt;ListItems<br>          {...person}<br>          key={person.email}<br>        /&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default Lis</pre><p>And ListItem component:</p><pre>const ListItem = ({<br>  email,<br>  imageUrl,<br>  name,<br>}: {<br>  email: string;<br>  imageUrl: string;<br>  name: string;<br>}) =&gt; {<br><br>  return (<br>    &lt;li<br>      className=&quot;flex gap-x-4 px-3 py-5 hover:bg-gray-100 focus:bg-gray-100 outline-none&quot;<br>    &gt;<br>      &lt;img<br>        className=&quot;h-12 w-12 flex-none rounded-full bg-gray-50&quot;<br>        src={imageUrl}<br>        alt=&quot;&quot;<br>      /&gt;<br>      &lt;div className=&quot;min-w-0&quot;&gt;<br>        &lt;p className=&quot;text-sm font-semibold leading-6 text-gray-900&quot;&gt;{name}&lt;/p&gt;<br>        &lt;p className=&quot;mt-1 truncate text-xs leading-5 text-gray-500&quot;&gt;{email}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/li&gt;<br>  );<br>};<br><br>export default ListItem;</pre><p>That all components on which we will work.</p><h3>Implement arrow key list navigation</h3><p>First of all, I start with creating useRoveFocus custom hook:</p><pre>import { useMemo, useState } from &quot;react&quot;;<br><br>import { useKeyPressEvent } from &quot;react-use&quot;;<br><br>const useRoveFocus = (size: number) =&gt; {<br>  const [currentFocus, setCurrentFocus] = useState(0);<br><br>  useKeyPressEvent(&quot;ArrowDown&quot;, () =&gt;<br>    setCurrentFocus(currentFocus === size - 1 ? 0 : currentFocus + 1)<br>  );<br>  useKeyPressEvent(&quot;ArrowUp&quot;, () =&gt;<br>    setCurrentFocus(currentFocus === 0 ? size - 1 : currentFocus - 1)<br>  );<br><br>  return useMemo(<br>    () =&gt; [currentFocus, setCurrentFocus] as const,<br>    [currentFocus]<br>  );<br>};<br><br>export default useRoveFocus;</pre><p>Let’s overview what happens here:</p><ol><li>The size argument refers to the length of the list of items.</li><li>The currentFocus state refers to the item that should be in focus.</li><li>useKeyPressEvent hook subscribe on keyboard events which is in our case ArrowUp/ArrowDown and when the user presses one of these buttons it will execute callback function which we passed as a second argument.</li><li>The callback function decreases or increases value based on the button pressed by the user</li></ol><p>Now it’s time to use this hook. I’ll start with the List component:</p><pre>import { directory } from &quot;../assets/data&quot;;<br>import useRoveFocus from &quot;../hooks/useRoveFocus&quot;; // import hook<br>import ListItem from &quot;./ListItem&quot;;<br><br>const List = () =&gt; {<br>  const [focus, setFocus] = useRoveFocus(directory.length ?? 0); // use hook<br><br>  return (<br>    &lt;ul role=&quot;list&quot; className=&quot;divide-y divide-gray-100&quot;&gt;<br>      {directory.map((person, index) =&gt; (<br>        &lt;ListItem<br>          {...person}<br>          key={person.email}<br>          index={index}<br>          focus={focus === index}<br>          setFocus={setFocus}<br>        /&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );<br>};<br><br>export default List;</pre><p>Here I import the hook and pass length of the array of users as an argument.</p><p>Also, you can see that I provide new props to ListItem component. Let’s add these props as well:</p><pre>import { useEffect, useRef } from &quot;react&quot;;<br><br>const ListItem = ({<br>  email,<br>  imageUrl,<br>  name,<br>  index,<br>  focus,<br>  setFocus,<br>}: {<br>  email: string;<br>  imageUrl: string;<br>  name: string;<br>  index: number;<br>  focus: boolean;<br>  setFocus: (index: number) =&gt; void;<br>}) =&gt; {<br>  const focusRef = useRef&lt;HTMLLIElement | null&gt;(null);<br><br>  useEffect(() =&gt; {<br>    if (focus &amp;&amp; focusRef?.current) {<br>      focusRef?.current.focus();<br>    }<br>  }, [focus]);<br><br>  const handleKeyDown = () =&gt; {<br>    setFocus(index);<br>  };<br><br>  return (<br>    &lt;li<br>      className=&quot;flex gap-x-4 px-3 py-5 hover:bg-gray-100 focus:bg-gray-100 outline-none&quot;<br>      onKeyDown={handleKeyDown}<br>      tabIndex={index}<br>      ref={focusRef}<br>    &gt;<br>      &lt;img<br>        className=&quot;h-12 w-12 flex-none rounded-full bg-gray-50&quot;<br>        src={imageUrl}<br>        alt=&quot;&quot;<br>      /&gt;<br>      &lt;div className=&quot;min-w-0&quot;&gt;<br>        &lt;p className=&quot;text-sm font-semibold leading-6 text-gray-900&quot;&gt;{name}&lt;/p&gt;<br>        &lt;p className=&quot;mt-1 truncate text-xs leading-5 text-gray-500&quot;&gt;{email}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/li&gt;<br>  );<br>};<br><br>export default ListItem;</pre><p>Let’s go over our newly added changes:</p><ol><li>I’ve added a focus prop which shows us if the current item is in focus</li><li>index prop we pass as <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex">tabIndex</a> argument to make our items focusable</li><li>The setFocus function updates the index which is the position of the item when the user presses the arrow keys.</li><li>The useEffect moves an element into the view when it’s focused</li></ol><p>That’s all now we can test how it works 🤠.</p><p>(I urge you to debug the following code on your own, to have a better understanding.)</p><h3>Resources</h3><ul><li>The original <a href="https://dev.to/rafi993/roving-focus-in-react-with-custom-hooks-1ln">article</a> where I found this hook, and adjusted it.</li><li><a href="https://github.com/AgentPrus/arrow-keys-navigation">GitHub</a> repo with code example (don’t forget to give me a star 🤩)</li></ul><h3>Conclusion</h3><p>When you look at this the first time it can seem tricky, but when you start implementing this it will “click”.</p><p>I hope it helps someone, also, don’t be afraid to try to change this code, maybe you come up with a better solution for this problem, so please share it in the comments.</p><p>Happy coding 👋</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8adb8f4257d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/keyboard-navigation-for-list-in-react-c8adb8f4257d">Keyboard Navigation for List in React</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Effective Way to Solve Conflict Between Classes in Tailwind CSS]]></title>
            <link>https://blog.stackademic.com/the-effective-way-to-solve-conflict-between-classes-in-tailiwnd-css-3c9b6a604b2d?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c9b6a604b2d</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 13:11:56 GMT</pubDate>
            <atom:updated>2023-11-23T00:57:49.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Tailwind CSS logo" src="https://cdn-images-1.medium.com/max/500/1*wMYPWGWLeYYL67cE8SlKZw.jpeg" /></figure><h3>Intro</h3><p>All we deal with CSS classes, especially when we use utility first library for styling our apps like Bootstrap, Tailwind CSS. When we use a tool like Tailwind for styling our app we are going to have a lot of classes, and sometimes we need to apply classes conditionally, sometimes we may have conflict between classes when we want to change class that already exists, that what happen to me time to times and I found a great tool that helped me solve this problem.</p><h3>TL;DR</h3><p>Use <a href="https://github.com/dcastil/tailwind-merge">tailiwnd-merge</a> utility function to solve conflicts between classes.</p><p>Here is a small example:</p><pre>import { twMerge } from &quot;tailwind-merge&quot;;</pre><pre>const Button = ({ classes, text }: { classes?: string; text: string }) =&gt; {<br>  const buttonCls = twMerge(<br>    &quot;rounded bg-green-500 px-2 py-1 text-xs font-semibold text-white shadow-sm hover:bg-green-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500&quot;,<br>    classes<br>  );<br>  return (<br>    &lt;button type=&quot;button&quot; className={buttonCls}&gt;<br>      {text}<br>    &lt;/button&gt;<br>  );<br>};<br>export default Button;</pre><h3>Table of Contents</h3><ul><li>Problem</li><li>Solution</li><li>Caution</li><li>Conclusion</li><li>Resources</li></ul><h3>Problem</h3><p>According to their documentation, the main purpose of the tailwind-merge is to resolve conflicts between similar classes.</p><p>Here is what that means:</p><p>We have a Button component where I already have color class:</p><pre>const Button = ({ classes, text }: { classes?: string; text: string }) =&gt; {<br>  const buttonCls =<br>    &quot;rounded bg-green-500 px-2 py-1 text-xs font-semibold text-white shadow-sm hover:bg-green-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500 &quot; +<br>    classes;</pre><pre>  return (<br>    &lt;button type=&quot;button&quot; className={buttonCls}&gt;<br>      {text}<br>    &lt;/button&gt;<br>  );<br>};</pre><pre>export default Button;</pre><p>I want to reuse this button and change color to pink, I can achieve this by passing through props:</p><pre>&lt;Button text=&quot;Create&quot; classes=&quot;bg-pink-500 focus:outline-pink-500 hover:bg-pink-400&quot; /&gt;</pre><p>If we inspect the button we see the next picture:</p><pre>&lt;button type=&quot;button&quot; class=&quot;rounded bg-green-500 px-2 py-1 text-xs font-semibold text-white shadow-sm hover:bg-green-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500 h-fit bg-pink-500 py-2 px-5 focus:outline-pink-500 hover:bg-pink-400&quot;&gt;Create&lt;/button&gt;</pre><p>We see at the bottom these classes that we have added, and if we run project our button will remain green and not pink as we expected to see. This is what tailwind-merge is for.</p><h3>Solution</h3><p>So let’s see how tailwind merge can help us solve this problem:</p><pre>import { twMerge } from &quot;tailwind-merge&quot;;</pre><pre>const Button = ({ classes, text }: { classes?: string; text: string }) =&gt; {<br>  const buttonCls = twMerge(<br>    &quot;rounded bg-green-500 px-2 py-1 text-xs font-semibold text-white shadow-sm hover:bg-green-400 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-green-500&quot;,<br>    classes<br>  );<br>  return (<br>    &lt;button type=&quot;button&quot; className={buttonCls}&gt;<br>      {text}<br>    &lt;/button&gt;<br>  );<br>};<br>export default Button;</pre><p>We just need to add twMerge function which will check if classes already exist and if they do, it will replace them with classes which we provide. So, classes that are last in order take precedence.</p><h3>Caution</h3><p>tailwind-merge is a great and robust tool, but all great tools come with their costs and this one is no exception. Here I want to say that tailwind-merge has a large bundle size, so, that is why you should think twice before implementing it in your project.</p><p>I urge you to read their <a href="https://github.com/dcastil/tailwind-merge/blob/v2.0.0/docs/when-and-how-to-use-it.md">docs</a> before adding this tool to your project!</p><h3>Resources</h3><ul><li>Great <a href="https://youtu.be/tfgLd5ZSNPc?si=wBYdEXZveBtYJJbq">video</a> about tailwind merge</li><li><a href="https://github.com/dcastil/tailwind-merge#get-started">Official docs</a></li></ul><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c9b6a604b2d" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-effective-way-to-solve-conflict-between-classes-in-tailiwnd-css-3c9b6a604b2d">The Effective Way to Solve Conflict Between Classes in Tailwind CSS</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Як працюють браузери]]></title>
            <link>https://medium.com/@nikitaprus98/%D1%8F%D0%BA-%D0%BF%D1%80%D0%B0%D1%86%D1%8E%D1%8E%D1%82%D1%8C-%D0%B1%D1%80%D0%B0%D1%83%D0%B7%D0%B5%D1%80%D0%B8-0862c5e2ab6b?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/0862c5e2ab6b</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Tue, 24 Oct 2023 17:38:22 GMT</pubDate>
            <atom:updated>2023-10-24T17:38:22.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6Dy7rBafAHYu78EKY6BnA.png" /></figure><p>Ця стаття буде цікава тим хто займається веб розробкою або кому просто цікаво як працюють браузери у середині.</p><h3>Зміст</h3><ol><li>Задачі браузера</li><li>Компоненти браузера</li><li>Відображення контенту в браузері</li><li>Корсині посилання</li></ol><h3>Задачі браузера</h3><p>На мою думку основні задача браузера, це відображати (render) отримані від сервера ресурси і давати можливітсь клієнту з ними взаємодіяти.</p><p>Це дуже узагальнене пояснення, давайте спробуємо піти трохи далі.</p><h3>Компоненти браузера</h3><p>У браузера є компоненти кожен з яких має певне призначення. Давайте розглянемо кожен з них.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*k_zXav1un-t7eNTn1KhD_g.png" /><figcaption>Browser components</figcaption></figure><ol><li><strong>User Interface</strong> — це компонент який дає вам можливість взаємодіяти з усіма візуальними елементами на сторінці (адресний рядок, кнопки назад/вперед, додому і тд.)</li><li><strong>Browser Engine</strong> — це сердце кожного веб-браузера. Двигун функціонує як посередник/міст між користувацьким інтерфейсом і механізмом відображення.</li><li><strong>Rendering Engine</strong> — цей компонент відповідає за відображення на екрані веб-сторінки, запитуваної користувачем. Він інтерпритує (перетворює) HTML, XML, СSS і інші формати в те, що ви бачите на екрані. Кожен браузер має свій власний двигун, це може впливати на вигляд сторінки. Тому існує <a href="https://developer.mozilla.org/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Introduction">кросс браузерне тестування</a>.</li><li><strong>Networking</strong> — Цей компонент відповідає за керування мережевими запитами за допомогою стандартних протоколів, таких як HTTP або FTP. Він також відповідає за безпеку.</li><li><strong>JavaScript Interpreter</strong> — цей компонент відповідає за парсинг (аналіз) і виклик JS коду який належить веб-сайту. Після того як код проаналізований і згенерований він відображається для користувача.</li><li><strong>UI Backend</strong> — Цей компонент використовує методи інтерфейсу користувача (<strong>user interface</strong>) для взаємодії з операційною системою. Тобто це свого роду міст між браузером і вашою операційною системою.</li><li><strong>Data Storage/Persistence</strong> — веб-браузеру необіхдно локально зберігати різні данні, наприклад файли cookie і тд.. Отож цей компонент відповідає за збереження даних в браузері.</li></ol><p>Я не буду заглиблюватись у кожен компонент, якщо вам дуже цікаво я залишу посилання на <a href="https://web.dev/articles/howbrowserswork">статтю</a>, де це гарно описано.</p><h3>Відображення контенту в браузері</h3><p>Я виділив 5 кроків які браузер проходить, щоб відобразити контент. Давайте поглянемо на них.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqSRlZ2lCclvgHi5IhkonA.png" /><figcaption>Rendering engine basic flow</figcaption></figure><ol><li><strong>Resource gathering</strong> — браузер обєднює усі отримані ресурси з сервера.</li><li><strong>Parse HTML &amp; create DOM Tree</strong> — Наш HTML файл перетворюється в DOM дерево зрозуміле для браузера.</li><li><strong>Rendering</strong> — одна з основних задач цього кроку це узяти увесь CSS і JS і застосувати його до нашого DOM дерева. Щоб краще зрозуміти різницю між 2-м і 3-м кроками я можу застосувати стиль display: hidden на якийсь HTML елемент і користувач його не буде бачити, але цей елемент ми бачитимемо у DOM дереві.</li><li><strong>Layout</strong> — на цьому кроці двигун браузера розміщає елементи по екрану.</li><li><strong>Painting</strong> — на цьому кроці двигун браузера комунікує з вашим компʼютером і говорить, що йому потрібно намалювати на екрані</li></ol><h3>Корисні посилання</h3><ul><li><a href="https://web.dev/howbrowserswork/">How browsers work (web.dev)</a></li><li><a href="https://www.youtube.com/watch?v=WjDrMKZWCt0&amp;ab_channel=DaveXiang">Відео яке коротко оглядає статтю вище</a> ☝️</li><li><a href="https://www.browserstack.com/guide/browser-rendering-engine">Understanding the Role of Rendering Engine in Browsers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0862c5e2ab6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Простими словами про Доменні імена і хостинг.]]></title>
            <link>https://medium.com/@nikitaprus98/%D0%BF%D1%80%D0%BE%D1%81%D1%82%D0%B8%D0%BC%D0%B8-%D1%81%D0%BB%D0%BE%D0%B2%D0%B0%D0%BC%D0%B8-%D0%BF%D1%80%D0%BE-%D0%B4%D0%BE%D0%BC%D0%B5%D0%BD%D0%BD%D1%96-%D1%96%D0%BC%D0%B5%D0%BD%D0%B0-%D1%96-%D1%85%D0%BE%D1%81%D1%82%D0%B8%D0%BD%D0%B3-8a7ce4f4aca6?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7ce4f4aca6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[domain-names]]></category>
            <category><![CDATA[hosting]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Mon, 25 Sep 2023 07:32:49 GMT</pubDate>
            <atom:updated>2023-09-25T07:32:49.082Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RH8m6AWr8995Pnv7" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>В цій статті я спробую простими словами пояснити, що таке доменне імʼя і хостинг.</p><h3>Зміст</h3><ul><li>Що таке доменне імʼя</li><li>Як отримати доменне імʼя</li><li>Що таке хостинг</li><li>Типи хостингів</li><li>Порівняння типів хостингів</li></ul><h3>Що таке доменне імʼя</h3><p>Доменне імʼя — це людино-зрозуміла адреса веб-сайту. Тобто у кожного компʼютера(сервера) є IP-адреса, але через те, що шукати веб-сайти по IP-адресі не дуже зручно створили доменне імʼя.</p><figure><img alt="Basic url structure" src="https://cdn-images-1.medium.com/max/1024/1*ct50qo_3gpQOw0mT9hM5jQ.png" /><figcaption>Basic URL structure</figcaption></figure><p>На картинці ви можете побачити де в URL розташоване доменне імʼя.</p><p>Для закріплення і кращого розуміння того, що таке доменне імʼя приведу аналогію:</p><p><em>Ви живете у будинку або квартирі яка знаходиться за певною адресою. Також і вебсайти “живуть” за певними адресами, і цю адресу називають </em><strong><em>доменним іменем</em></strong><em>. Ваш веб сайт також має IP-адресу. Про IP-адресу ми можемо думати як про координати, тобто ми можемо знайти ваш будинок/квартиру по координатам, що є не дуже зручно, а можемо за назвою вулиці також і веб сайти. Доменне імʼя зроблено для того, щоб спростити життя нам людям.</em></p><p>Ось картинка яка ілюструє як відбувається пошук веб-сайту за допомогою доменного імені.</p><figure><img alt="Process of searching website by domain name" src="https://cdn-images-1.medium.com/max/1024/1*xHoFU37EyEHVOtEG-SW62A.png" /><figcaption>Process of searching website</figcaption></figure><h3>Як отримати доменне імʼя</h3><p>Отримати доменне імʼя досить просто. Перед тим як пояснювати процес отримання доменного імені, хочу звернути увагу на те, що доменне імʼя не купується, а орендується. Тобто ви орендуєте доменне імʼя на певний період часу (зазвичай це 1 рік). І потім хтось може його переорендувати.<br>Процес оренди доменного імені досить простий, я використовую сайт <a href="https://www.namecheap.com/">https://www.namecheap.com/</a> де можна орендувати доменне імʼя дуже зручно і також за вигідною ціною.</p><p>Я прикріплю відео опис того як це робиться:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAgmOUicbDjo%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAgmOUicbDjo&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAgmOUicbDjo%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/673d31a5b02774345221f225add6fb8b/href">https://medium.com/media/673d31a5b02774345221f225add6fb8b/href</a></iframe><h3>Що таке хостинг</h3><p>Хостинг — це компʼютер (сервер) на якому зберігається ваш сайт. Для кращого розуміння приведу аналогію:</p><p><em>Наприклад ви хочете побудувати будинок, вам спочатку потрібно купити ділянку, потім вже будувати будинок і у вашого будинку повинна бути адреса. З цієї аналогії земля де буде стояти ваш будинок — це хостинг, будинок — це ваш сайт, а адреса будинку це доменне імʼя.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aka1DqQWr4PvTljY1cN7vA.png" /><figcaption>Web hosting analogy</figcaption></figure><h3>Види хостингів</h3><p>Виділяють 4 основних види хостингів:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yvo8Lo628ng7F3Xuf_4CRg.png" /><figcaption>Hosting types</figcaption></figure><p>Давайте розберемо кожен з них більш детально:</p><ul><li><strong>Shared</strong> — Це коли ти ділиш компʼютер (сервер), де лежить твій сайт з іншими людьми, де також лежать їхні сайти. <br>Приведу аналогію:<em> Shared hosting — це як кооворкінг, тобто ви орендуєте місце і працюєте з усіма, але якщо в кооворкінгу пропаде світло то це буде проблемою не тільки інших але й вашою.</em></li><li><strong>VPS (Virtual Private Server)</strong> — Це дуже подібно до Shared hosting, бо ви також зберігаєте ваш сайт на одному компʼютері(сервері) з іншими. Але його перевага в тому, що він виділяє під вас окремі ресурси, і в залежності того скільки ви готові заплатити стільки ви отримаєте ресурсів. Більше платиш більше маєш. Посуті це компʼютер (сервер) на якому під кожного користувача виділена віртуальна машина.</li><li><strong>Cloud hosting</strong> або <strong>Хмарний хостинг</strong> — дає можливість зберігати вебсайт у так званій “хмарі”. “Хмара” — це мережа фізичних і віртуальних компʼютерів. Один з переваг хмарного хостингу, це те що ти платиш за те скільки споживаєш, тобто тут як комуналка скільки використав стільки заплатив. Але також в цьому є і недолік, якщо забути виставити платіжні обмеження то може прийти солідний рахунок. Також один з недоліків <strong>Сloud хостингу,</strong> це те що в ньому потрібно розбиратись, не так просто його налаштувати, особливо якщо мова йде про складніші аплікації де у вас є бекенд і база данних, вам доведеться помучатись з конфігурацією.</li><li><strong>Dedicated</strong> — Тут все просто увесь компʼютер(сервер) повністю ваш. Тобто ви маєте повний контроль над усім, що відбувається, ви завжди маєте можливість підняти і опустити потужність, і розподіляти ресурси під ваші потреби.</li></ul><h3>Висновок</h3><p>Сподіваюсь тепер вам краще зрозуміло, що таке доменне імʼя для чого воно потрібно і як його отримати. Також ви тепер маєте базове поняття того, що таке хостинг і які є його типи.</p><p>Дякую, за увагу! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7ce4f4aca6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Що таке HTTP/HTTPS?]]></title>
            <link>https://medium.com/@nikitaprus98/%D1%89%D0%BE-%D1%82%D0%B0%D0%BA%D0%B5-http-c49f1edc0829?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c49f1edc0829</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[internet]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 08:21:05 GMT</pubDate>
            <atom:updated>2023-09-17T08:22:30.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SGbyF3Y9nePosIPJ" /><figcaption>Photo by <a href="https://unsplash.com/@diesektion?utm_source=medium&amp;utm_medium=referral">Robert Anasch</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Я продовжую серію сттатів про те, що таке інтернет і сьогодні ми поглянемо на проткол, з яким на мою думку найчастіше працюють веб розробники а саме HTTP/HTTPS.</p><h3>Що таке HTTP</h3><p>HTTP або <strong>H</strong>yper <strong>T</strong>ext <strong>T</strong>ransfer <strong>P</strong>rotocol це протокол для обміну данними між клієнтом і сервером. Тобто його основна задача це обмін данними між браузером (клієнт) і віддаленим компʼютером (сервер). Обмін данними проходить у формі запитів Request/Response, що буквально значить запит/відповідь. Тобто для завантаження сторінки в браузері ми використовуємо тип протоколу HTTP.</p><h3>Що таке HTTPS</h3><p><strong>H</strong>yper <strong>T</strong>ext <strong>T</strong>ransfer <strong>P</strong>rotocol <strong>S</strong>ecure — це той самий тип протоколу тільки він є безбечним, безбека досягається з допомогою SSL/TLS сертефікатів і також шифрування данних. Це звучить слкадно але добрий комікс який це поясню ось <a href="https://howhttps.works/uk/why-do-we-need-https/">посилання</a>.</p><h3>Методи HTTP</h3><p>В HTTP існує декілька методів і кожен з них має своє призначення.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*MAInu7b5KjN7TVqQFd2nKg.png" /><figcaption>HTTP Methods</figcaption></figure><p>На картинці ви бачите найпоширеніші HTTP методи і для простоти їх запамʼятовування є аббревіатура CRUD. Нижче я коротко опишу, функцію кожного з цих методів.</p><ul><li><strong>GET</strong> — Отримує данні з сервера</li><li><strong>POST </strong>— Відправляє данні на сервер</li><li><strong>PUT </strong>— Оновлює данні на сервері</li><li><strong>DELETE </strong>— Видаляє данні на сервері</li></ul><h3>HTTP статус коди</h3><p>HTTP запити мають певний статус який позначається числом яке називають код. Статус коди несуть інформативне значення про як ви могли догадатись статус нашого HTTP запиту. Нижче буде картинка де перераховано основні категорії статус кодів і їх значення.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FztL61jsqL0Kgfzpw7G8Q.png" /><figcaption>HTTP Status Code cheat sheet</figcaption></figure><h3>HTTP Headers</h3><p>HTTP headers — відповідають за зберігання мета інформації запиту. Їх можна побачити в кожному запиті якщо відкрити нетворки в chrome:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-dXdOqBLn0EwYMCeq276-g.png" /><figcaption>HTTP Headers in Chrome network Tab</figcaption></figure><p>Вони поділяються на 3 частини це як ви бачите General, Response Headers і Request Headers і кожин з цих розідлів має поля з інформацією про запит. Полів там багато, тому якщо ви хочете більш детально почитати про це, лишу вам <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers">посилання</a>.</p><h3>Висновоки</h3><p>Ми коротко оглянули, що таке HTTP і пройшлись по основним його розділам. Ця стаття дуже поверхнева і її ціль є ознайомити вас з HTTP/HTTPS нижче я залишу ресурси де ви зможете самостійно заглибитись у цю тему.</p><h3>Корисні посилання</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP">HTTP MDN Docs</a></li><li><a href="https://howhttps.works/uk/">Як працює HTTPS в коміксах</a></li><li><a href="https://cs.fyi/guide/http-in-depth">Усе що вам потрібно знати про HTTP</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c49f1edc0829" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Що таке інтернет і як він працює?]]></title>
            <link>https://medium.com/@nikitaprus98/%D1%89%D0%BE-%D1%82%D0%B0%D0%BA%D0%B5-%D1%96%D0%BD%D1%82%D0%B5%D1%80%D0%BD%D0%B5%D1%82-%D1%96-%D1%8F%D0%BA-%D0%B2%D1%96%D0%BD-%D0%BF%D1%80%D0%B0%D1%86%D1%8E%D1%94-59c3057461fc?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c3057461fc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 08:17:54 GMT</pubDate>
            <atom:updated>2023-09-04T12:39:45.643Z</atom:updated>
            <content:encoded><![CDATA[<p>У нашому сучасному світі я вважаю інтернет став невідʼємною частиною нашого життя. Тож на мою думку нам важливо мати загальне розуміння того як працює інтернет. А особливо це буде корисно тим хто хоче будувати карʼєру веб програміста.</p><h3>Зміст</h3><ul><li>Знайомство з <strong>інтернетом</strong></li><li>Як працює <strong>інтернет</strong>: Загальний огляд</li><li>Типи інтернет <strong>протоколів</strong></li><li><strong>IP address </strong>&amp; <strong>Domain name</strong></li><li>Знайомство з <strong>HTTP</strong> &amp; <strong>HTTPS</strong></li><li>Висновок</li><li>Корисні посилання</li></ul><h3>Знайомство з інтернетом</h3><p>Перш ніж ми розглянемо, що таке Інтернет, давайте розберемось, що таке мережа. Мережа — це група комп’ютерів або інших пристроїв, з’єднаних між собою. Наприклад, у вас є декілька компʼютерів і з них можна зробити одну мережу зʼєднавши їх кабелем. Якщо ви трохи старші то певно памʼятаєте компʼютерні клуби де всі грали ігри по мережі. Тобто усі ці компʼютери з’єднані разом в одну мережу і утворюють Інтернет.</p><p>Тобто:</p><blockquote>Інтернет — це мережа мереж</blockquote><p>Ось фото як виглядає частина світової мережі:</p><figure><img alt="Photo of global network" src="https://cdn-images-1.medium.com/max/937/1*ln2VFLafL6kN-UFm7MS8yg.png" /></figure><p>Інтернет був розроблений наприкінці 1960-х років Міністерством оборони США як засіб створення децентралізованої комунікаційної мережі, яка могла б витримати ядерну атаку. З роками він перетворився на складну і витончену мережу, яка охоплює весь світ.</p><p>Сьогодні інтернет є невід’ємною частиною сучасного життя, яким користуються мільярди людей по всьому світу для доступу до інформації, спілкування з друзями та родиною, ведення бізнесу та багато іншого. Для розробника важливо мати глибоке розуміння того, як працює Інтернет, а також різних технологій і протоколів, які лежать в його основі.</p><h3>Як працює інтернет: Загальний огляд</h3><figure><img alt="example of data flow in internet" src="https://cdn-images-1.medium.com/max/900/1*xXi-cbpWXT6XnSMuUjQcoA.png" /></figure><p>На високому рівні інтернет працює, з’єднуючи пристрої та комп’ютерні системи разом за допомогою набору стандартизованих протоколів. Ці протоколи визначають, як відбувається обмін інформацією між пристроями, і забезпечують надійну та безпечну передачу даних. Типи протоколів ми розглянемо згодом.</p><h3>Типи інтернет протоколів</h3><p>Нижче я перерахую основні типи інтернет протоколів і їх короткий опис:</p><ul><li><strong>Packet:</strong> Невелика одиниця даних, яка передається через інтернет.</li><li><strong>Router:</strong> Пристрій, який спрямовує пакети даних між різними мережами.</li><li><strong>IP-адреса:</strong> Унікальний ідентифікатор, присвоєний кожному пристрою в мережі, який використовується для маршрутизації даних до правильного місця призначення.</li><li><strong>Domain Name:</strong> Читабельне ім’я, яке використовується для ідентифікації веб-сайту, наприклад, <a href="http://google.com/">google.com</a>.</li><li><strong>DNS:</strong> Система доменних імен, що відповідає за перетворення доменних імен в IP-адреси.</li><li><strong>HTTP:</strong> протокол передачі гіпертексту використовується для передачі даних між клієнтом (наприклад, веб-браузером) і сервером (наприклад, веб-сайтом).</li><li><strong>HTTPS:</strong> зашифрована версія HTTP, яка використовується для забезпечення безпечного зв’язку між клієнтом і сервером.</li><li><strong>SSL/TLS:</strong> протоколи безпеки на рівні захищених сокетів і транспортного рівня використовуються для забезпечення безпечного зв’язку в Інтернеті.</li></ul><h3>Роль протоколів в інтернеті</h3><p>Протоколи відіграють важливу роль у забезпеченні зв’язку та обміну даними в Інтернеті. Протокол — це набір правил і стандартів, які визначають, як відбувається обмін інформацією між пристроями та системами.</p><p>Існує багато різних протоколів як, що використовуються в інтернет-зв’язку. Кожен з цих протоколів має свою роль.</p><p>IP відповідає за маршрутизацію пакетів даних до правильного місця призначення, тоді як <strong>TCP</strong> і <strong>UDP</strong> забезпечують надійну та ефективну передачу пакетів. <strong>DNS</strong> використовується для перетворення доменних імен в <strong>IP</strong>-адреси, а <strong>HTTP</strong> — для передачі даних між клієнтами і серверами.</p><p>Однією з ключових переваг використання стандартизованих протоколів є те, що вони дозволяють пристроям і системам від різних виробників і постачальників безперешкодно взаємодіяти один з одним. Наприклад, веб-браузер, розроблений однією компанією, може взаємодіяти з веб-сервером, розробленим іншою компанією, якщо вони обидва дотримуються протоколу <strong>HTTP</strong>.</p><p>Щоб краще розуміти, що таке протокол приведу вам аналогію:</p><p>Уявіть собі інтернет як величезну міжнародну поштову систему. Коли ви надсилаєте лист (дані) зі свого дому (пристрій) до дому друга (інший пристрій) в іншій країні, вони не з’являються там просто так, як за помахом чарівної палички. Натомість він проходить через низку чітко визначених кроків і перевірок.</p><p><strong>Адресація:</strong> Ви вказуєте на конверті адресу вашого друга (IP-адресу) і свою зворотну адресу (IP-адресу вашого пристрою). Це схоже на те, як пристрої в Інтернеті мають IP-адреси, що їх ідентифікують.</p><p><strong>Пакування:</strong> Ви вкладаєте свій лист у конверт (пакет). Так само ваші дані розділяються на пакети для полегшення їх обробки та передачі.</p><p><strong>Маршрутизація:</strong> Ви віддаєте лист у місцеве поштове відділення (ваш маршрутизатор), і вони визначають найкращий спосіб відправити його в країну вашого друга. Дорогою лист може пройти через багато поштових відділень (маршрутизаторів), поки не досягне місця призначення.</p><p><strong>Збирання:</strong> Коли лист прибуває до країни вашого друга, місцеве поштове відділення (маршрутизатор) збирає всі частини вашого листа (пакети), розташовує їх у правильному порядку і доставляє додому (на пристрій) вашого друга.</p><p><strong>Підтвердження:</strong> Ваш друг отримує лист і надсилає вам листівку (підтвердження), щоб підтвердити, що він його отримав. Якщо він не надішле листівку, ви можете припустити, що лист загубився, і надіслати його ще раз.</p><p>У цій аналогії:</p><p><strong>“Адреса”</strong> — це <strong>IP-адреса</strong>, яка ідентифікує пристрої в Інтернеті. <strong>“Конверт”</strong> — це як <strong>пакет</strong>, тобто невеликий фрагмент даних. <strong>“Поштові відділення”</strong> — це маршрутизатори, які допомагають спрямовувати дані до місця призначення. На етапі <strong>“збирання”</strong> пакети знову збираються разом у правильному порядку. <strong>“Підтвердження”</strong> — це спосіб для пристроїв переконатися, що дані дійшли до адресата.</p><p>Отже, <strong>інтернет-протоколи</strong> — це правила і процедури, які регулюють надсилання, отримання та управління даними під час їхньої подорожі Інтернетом, так само, як поштові правила допомагають листам досягти місця призначення.</p><p>У цьому відео ви зможете побачити як це праює:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAYdF7b3nMto%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAYdF7b3nMto&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAYdF7b3nMto%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ff98553e73dee403e72ca0977f02a5d/href">https://medium.com/media/5ff98553e73dee403e72ca0977f02a5d/href</a></iframe><h3>IP Addresses &amp; Domain Names</h3><p><strong>IP</strong>-адреса — це унікальний ідентифікатор, який присвоюється кожному пристрою в мережі. Вона використовується для маршрутизації даних до правильного місця призначення, гарантуючи, що інформація буде надіслана саме тому, кому вона призначена. IP-адреси зазвичай представлені у вигляді серії з чотирьох чисел, розділених крапками, наприклад, “192.168.1.1”.</p><figure><img alt="IP-address example" src="https://cdn-images-1.medium.com/max/671/1*pdlw5I24J64C6uA2o7kFUg.png" /></figure><p>Доменні імена, — це людино читабельні імена, які використовуються для ідентифікації веб-сайтів та інших інтернет-ресурсів. Зазвичай вони складаються з двох або більше частин, розділених крапками. Наприклад, “<a href="http://google.com/">google.com</a>” — це доменне ім’я. Доменні імена перетворюються на <strong>IP</strong>-адреси за допомогою системи доменних імен (<strong>DNS</strong>).</p><p><strong>DNS</strong> — або Domain name system — це структура яка відповідає за перетворення доменних імен в <strong>IP</strong>-адреси. Коли ви вводите доменне ім’я у веб-браузері, ваш комп’ютер надсилає <strong>DNS</strong>-запит на <strong>DNS</strong>-сервер, який повертає відповідну <strong>IP</strong>-адресу. Потім ваш комп’ютер використовує цю <strong>IP</strong>-адресу для підключення до веб-сайту або іншого ресурсу, який ви запросили.</p><p>Щоб зрозуміти, краще що таке <strong>DNS </strong>приведу одну аналогію<strong>:</strong></p><p>У вас на телефоні є контактна книга, і кожен ваш контакт має імʼя і номер телефону. Щоб знайти контакт ви вводите його імʼя і вам підтягує усю інформацію по контакту який ви шукали.</p><p>Якщо розібрати цю аналогію в контексті DNS то:</p><p><strong>ІP</strong>-адреса — це номер телефону</p><p><strong>Domain name</strong> — це імʼя вашого контакту</p><p>Ось дуже спрощена візуалізація того як це працює:</p><figure><img alt="DNS resolution process" src="https://cdn-images-1.medium.com/max/600/1*9RWY4ACYwLmKMHuvgjR8dA.png" /></figure><h3>Знайомство з HTTP &amp; HTTPS</h3><p><strong>HTTP</strong> (Hypertext Transfer Protocol — протокол передачі гіпертексту) і <strong>HTTPS</strong> (HTTP Secure — захищений протокол) — це два найпоширеніші протоколи, які використовуються в інтернет-додатках і сервісах.</p><p><strong>HTTP</strong> — це протокол, який використовується для передачі даних між клієнтом (наприклад, веб-браузером) і сервером (наприклад, веб-сайтом). Коли ви відвідуєте веб-сайт, ваш веб-браузер надсилає <strong>HTTP</strong>-запит на сервер із запитом на веб-сторінку або інший ресурс, який ви запросили. Потім сервер надсилає клієнту <strong>HTTP</strong>-відповідь, що містить запитувані дані.</p><p><strong>HTTPS</strong> — це більш безпечна версія <strong>HTTP</strong>, яка шифрує дані, що передаються між клієнтом і сервером, за допомогою шифрування <strong>SSL/TLS</strong> (Secure Sockets Layer/Transport Layer Security). Це забезпечує додатковий рівень безпеки, допомагаючи захистити конфіденційну інформацію, таку як облікові дані для входу, платіжна інформація та інші персональні дані.</p><p>Коли ви відвідуєте веб-сайт, який використовує <strong>HTTPS</strong>, ваш веб-браузер відображає в адресному рядку піктограму замка, що означає, що з’єднання <strong>захищене</strong>. Ви також можете побачити літери “<strong>https</strong>” на початку адреси веб-сайту замість “<strong>http</strong>”.</p><figure><img alt="difference between HTTP and HTTPS" src="https://cdn-images-1.medium.com/max/675/1*bwXvRvnTLg8T_Wx2YLVoeA.png" /></figure><h3>Висновок</h3><p>Я вважаю, що починати свій шлях як веб розробника потрібно не з HTML &amp; CSS, а саме з хоча б загального розуміння того як працює веб. Не намагайтесь одразу зрозуміти усі деталі, радше старайтесь намалювати собі загальну картин того як усе поєднюється, а розуміння деталей прийде як результат постійної роботи.</p><h3>Корисні посилання</h3><ul><li><a href="https://roadmap.sh/guides/what-is-internet">Як працює інтернет — серія кортких відео</a>.</li><li><a href="https://cs.fyi/guide/how-does-internet-work">Хороша стаття про те як працює інтернет.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c3057461fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code splitting in React]]></title>
            <link>https://medium.com/@nikitaprus98/code-splitting-in-react-4fe7c5d655d8?source=rss-5d54bd1420c3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fe7c5d655d8</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code-splitting]]></category>
            <dc:creator><![CDATA[Mykyta Prus ]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 08:31:28 GMT</pubDate>
            <atom:updated>2023-08-18T08:31:28.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IP6xcosCmXoLgFjQ" /><figcaption>Photo by <a href="https://unsplash.com/@michaelrfenton?utm_source=medium&amp;utm_medium=referral">Michael Fenton</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the world of SPA(single-page-applications) code splitting became an essential thing. However, like any enhancement, it’s not without its challenges. So, let’s look into code splitting in React apps.</p><h3>Table of contents</h3><ul><li>Code splitting</li><li>Lazy loading</li><li>The problem with React.lazy</li><li>Solution</li><li>Conclusion</li><li>Resources</li></ul><h3>Code splitting</h3><p>In the world of single-page applications, it’s common to have a single JS file that controls your entire app. This means that users always load one JS file, which can include unnecessary code. For example, when a user opens the /about page, it also loads the code for the /dashboard page. Here is an example of SPA without lazy loading.</p><pre>const router = createBrowserRouter([<br>  {<br>    path: &quot;/&quot;,<br>    element: &lt;App /&gt;,<br>    children: [<br>      {<br>        path: &quot;about&quot;,<br>        element: &lt;About /&gt;,<br>      },<br>      {<br>        path: &quot;dashboard&quot;,<br>        element: &lt;Dashboard /&gt;,<br>      },<br>      {<br>        path: &quot;settings&quot;,<br>        element: &lt;Settings /&gt;,<br>      },<br>    ],<br>  },<br>]);<br><br>ReactDOM.createRoot(document.getElementById(&quot;root&quot;)!).render(<br>  &lt;React.StrictMode&gt;<br>    &lt;RouterProvider router={router} /&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>We have an app with three pages. Let’s build our app and run it to see what happens.</p><figure><img alt="screenshot of app build output" src="https://cdn-images-1.medium.com/max/1024/1*KbbTlHYkH0ivXMfgyyw9bA.png" /><figcaption>App built output</figcaption></figure><p>index-[chunk-id] - it is this one JS file that consists of all our pages.</p><p>Let’s execute our build by running the command yarn preview and then opening the network tab to see what happens.</p><figure><img alt="Screenshot of network tab of our app" src="https://cdn-images-1.medium.com/max/1024/1*0COzftZf-5qpJbssIw1YXw.png" /><figcaption>Browser network</figcaption></figure><p>If you look at the URL, you’ll see you’re on the home page, but the code for all our pages gets loaded. This might be fine for small apps but think about a scenario with a big app that has thousands of lines of code. So, what can you do about this?</p><h3>Lazy loading</h3><p><em>Lazy loading</em> involves breaking down a large chunk into smaller parts and loading them only when the user requires them. For implementing <em>lazy loading</em>, you require two things:</p><ol><li><a href="https://react.dev/reference/react/lazy">React.lazy</a> — <em>lets you defer loading the component’s code until it is rendered for the first time.</em></li><li><a href="https://react.dev/reference/react/Suspense">Suspense</a> — <em>lets you display a fallback until its children have finished loading.</em></li></ol><p>The first step, you need to update your imports to look like this:</p><pre>const About = React.lazy(() =&gt; import(&quot;./pages/About&quot;));<br>const Dashboard = React.lazy(() =&gt; import(&quot;./pages/Dashboard&quot;));<br>const Contact = React.lazy(() =&gt; import(&quot;./pages/Contact&quot;));</pre><p>The next step is to wrap your components within a Suspense component, which has fallback property for displaying a loader until your component is ready to render.</p><pre>// App.tsx<br><br>const router = createBrowserRouter([<br>  {<br>    path: &quot;/&quot;,<br>    element: (<br>      &lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>        &lt;Root /&gt;<br>      &lt;/Suspense&gt;<br>    ),<br>    children: [<br>      {<br>        path: &quot;about&quot;,<br>        element: &lt;About /&gt;,<br>      },<br>      {<br>        path: &quot;dashboard&quot;,<br>        element: &lt;Dashboard /&gt;,<br>      },<br>      {<br>        path: &quot;contact&quot;,<br>        element: &lt;Contact /&gt;,<br>      },<br>    ],<br>  },<br>]);</pre><p>You can wrap only your parent component in Suspense since the other routes are nested. Therefore, there&#39;s no need to wrap each one individually in Suspense.</p><p>Let’s rebuild your app once more and observe what has changed.</p><figure><img alt="Screenshot of app build output after code splitting" src="https://cdn-images-1.medium.com/max/1024/1*UHOrlwQlZv_x74ARbo6O7g.png" /><figcaption>App build output after code splitting</figcaption></figure><p>You can observe that there are now three chunks for each page. Run the app and examine the network tab to identify the changes.</p><p>As you can see below each chunk loads only when the user clicks on the respective page.</p><figure><img alt="Gif which show how each chunk upload" src="https://cdn-images-1.medium.com/max/600/1*OMziSUigRp7Qxd5WBRMUpA.gif" /></figure><p>As you can see above that each chunk loads only when the user clicks on the respective page.</p><h3>The problem with React.Lazy</h3><p>But what happens if the user is unable to download the required chunk? The app will crash because react fails to import the chunk.</p><p>When it can happen?</p><p>This can occur due to network connection issues. It can also happen when you release a new build, but the user has an older version cached in the browser. If the user attempts to load a chunk using an old id, it leads to an error.</p><h3>The solution</h3><p>The solution is quite straightforward. You need to create a wrapper around React.lazy, and in case an error occurs, you attempt to load the chunk again. I came across a helpful <a href="https://medium.com/@alonmiz1234/retry-dynamic-imports-with-react-lazy-c7755a7d557a">article</a> that provided the solution, so I won’t delve into the details; I’ll just provide the code:</p><pre>export const lazyWithRetries: typeof React.lazy = (importer) =&gt; {<br>  const retryImport = async () =&gt; {<br>    try {<br>      return await importer();<br>    } catch (error: any) {<br>      // retry 5 times with 2 second delay and backoff factor of 2 (2, 4, 8, 16, 32 seconds)<br>      for (let i = 0; i &lt; 5; i++) {<br>        await new Promise((resolve) =&gt; setTimeout(resolve, 1000 * 2 ** i));<br>        // this assumes that the exception will contain this specific text with the url of the module<br>        // if not, the url will not be able to parse and we&#39;ll get an error on that<br>        // eg. &quot;Failed to fetch dynamically imported module: https://example.com/assets/Home.tsx&quot;<br>        const url = new URL(<br>          error.message<br>            .replace(&quot;Failed to fetch dynamically imported module: &quot;, &quot;&quot;)<br>            .trim()<br>        );<br>        // add a timestamp to the url to force a reload the module (and not use the cached version - cache busting)<br>        url.searchParams.set(&quot;t&quot;, `${+new Date()}`);<br><br>        try {<br>          return await import(url.href);<br>        } catch (e) {<br>          console.log(&quot;retrying import&quot;);<br>        }<br>      }<br>      throw error;<br>    }<br>  };<br>  return React.lazy(retryImport);<br>};</pre><p>If you’re using strict mode in TypeScript, you might encounter an error like this:</p><blockquote><em>Unexpected any. Specify a different type. eslint(</em><a href="https://typescript-eslint.io/rules/no-explicit-any"><em>@typescript-eslint/no-explicit-any</em></a><em>)</em></blockquote><p>This situation can be tricky since the error object can be different depending on the context. Therefore, it’s necessary to create a helper function that can be reused in other try catch blocks.</p><p>Here is what I found:</p><pre>type ErrorWithMessage = {<br>  message: string;<br>};<br><br>function isErrorWithMessage(error: unknown): error is ErrorWithMessage {<br>  return (<br>    typeof error === &quot;object&quot; &amp;&amp;<br>    error !== null &amp;&amp;<br>    &quot;message&quot; in error &amp;&amp;<br>    typeof (error as Record&lt;string, unknown&gt;).message === &quot;string&quot;<br>  );<br>}<br><br>function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {<br>  if (isErrorWithMessage(maybeError)) return maybeError;<br><br>  try {<br>    return new Error(JSON.stringify(maybeError));<br>  } catch {<br>    // fallback in case there&#39;s an error stringifying the maybeError<br>    // like with circular references for example.<br>    return new Error(String(maybeError));<br>  }<br>}<br><br>export function getErrorMessage(error: unknown) {<br>  return toErrorWithMessage(error).message;<br>}</pre><p>don’t get into details here. If you’re interested in how it works, I recommend reading this <a href="https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript">article</a>.</p><p>Here is the refactored version of lazyWithRetries the function:</p><pre>export const lazyWithRetries: typeof React.lazy = (importer) =&gt; {<br>  const retryImport = async () =&gt; {<br>    try {<br>      return await importer();<br>    } catch (error) {<br>      // retry 5 times with 2 second delay and backoff factor of 2 (2, 4, 8, 16, 32 seconds)<br>      for (let i = 0; i &lt; 5; i++) {<br>        await new Promise((resolve) =&gt; setTimeout(resolve, 1000 * 2 ** i));<br>        const errorMessage = getErrorMessage(error);<br>        // this assumes that the exception will contain this specific text with the url of the module<br>        // if not, the url will not be able to parse and we&#39;ll get an error on that<br>        // eg. &quot;Failed to fetch dynamically imported module: https://example.com/assets/Home.tsx&quot;<br>        const url = new URL(<br>          errorMessage<br>            .replace(&quot;Failed to fetch dynamically imported module: &quot;, &quot;&quot;)<br>            .trim()<br>        );<br>        // add a timestamp to the url to force a reload the module (and not use the cached version - cache busting)<br>        url.searchParams.set(&quot;t&quot;, `${+new Date()}`);<br><br>        try {<br>          return await import(url.href);<br>        } catch (e) {<br>          console.warn(&quot;retrying import&quot;);<br>        }<br>      }<br>      throw error;<br>    }<br>  };<br>  return React.lazy(retryImport);<br>};</pre><p>And now you can use it for your lazy imports:</p><pre>const About = lazyWithRetries(() =&gt; import(&quot;./pages/About&quot;));<br>const Dashboard = lazyWithRetries(() =&gt; import(&quot;./pages/Dashboard&quot;));<br>const Contact = lazyWithRetries(() =&gt; import(&quot;./pages/Contact&quot;));</pre><p>That’s all, and congratulations! 🥳</p><p>I hope this guide helps you in crafting error-free applications!</p><h3>Conclusion</h3><p>In summary, here’s what we’ve accomplished:</p><ul><li>We split our routes using React.lazy and Suspense</li><li>We create lazyWithRetries wrapper around React.lazy to help us avoid errors when the user couldn’t load the required chunk.</li></ul><h3>Resources</h3><ul><li>Thanks, <a href="https://medium.com/@alonmiz1234"><strong>Alon Mizrahi</strong></a> for an insightful <a href="https://medium.com/@alonmiz1234/retry-dynamic-imports-with-react-lazy-c7755a7d557a">article</a> about lazyWithRetries; I highly recommend giving it a read.</li><li>An excellent <a href="https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript">article</a> covering catch block error message with TypeScript.</li><li><a href="https://github.com/AgentPrus/code-split-sandbox">GitHub repo</a> with the code related to this article.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fe7c5d655d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>