<?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 Sveta Slepner on Medium]]></title>
        <description><![CDATA[Stories by Sveta Slepner on Medium]]></description>
        <link>https://medium.com/@sveta-slepner?source=rss-9fbbda39eb22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tX9IxDMfkvYEVqA1l-I4QA.jpeg</url>
            <title>Stories by Sveta Slepner on Medium</title>
            <link>https://medium.com/@sveta-slepner?source=rss-9fbbda39eb22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:41:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sveta-slepner/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[GitHub Actions: A Beginner’s Guide to Automating Your Development Process]]></title>
            <link>https://levelup.gitconnected.com/github-actions-a-beginners-guide-to-automating-your-development-process-81e27b4d4952?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/81e27b4d4952</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 14:43:13 GMT</pubDate>
            <atom:updated>2023-02-07T14:43:13.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ydb0rNhspMZhDe2XLaOBxg.jpeg" /><figcaption>GitHub Actions</figcaption></figure><p>As a front-end developer, I was never really drawn to the “DevOps” side of my day-to-day work. The major reason is that up until now, in all of the places I have worked in, we’ve been using Jenkins. And while it’s a powerful tool no doubt, it sure is unwelcoming and hard to get started with.</p><p>But in recent years GitHub has stepped into the game and in 2018 released “GitHub Actions”, a platform for creating custom, automated development workflows directly within the GitHub ecosystem.</p><p>Whether you want to create a CI/CD pipeline or automate GitHub-related flows like opening a PR, adding automated comments, or sending a Slack notification each time someone merges a commit to master, GitHub Actions can help you create these processes and save you time and effort. And the best part is <strong>how straightforward it is</strong>!</p><p>In this guide, we’ll cover the basics of GitHub Actions and show you how to get started with them. We’ll go through the process of setting up a simple workflow and explain some of the key concepts you need to know. By the end, you’ll be able to use GitHub Actions to automate your own workflow and take your productivity to the next level!</p><h3>First, some GitHub Actions terminology</h3><p>Well, the name might be GitHub <strong>Actions</strong>, but let’s put that aside for one second. What we’re actually running are <strong>workflows. </strong>A workflow is a collection of jobs that are triggered by an event.</p><p>Here’s an example of a simple workflow’s structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Ti_fcmaFU0Fi0qWyETEcOA.jpeg" /></figure><p>As you can see, this workflow is running two jobs. A <strong>job</strong> is a set of steps that are executed in sequence. Each step of a job can be an action. An <strong>action</strong> is an individual step within a job that can perform a variety of tasks such as running a script, building an application, deploying code, or running tests.</p><h3>Setting up a workflow</h3><p>GitHub actions and workflows are written in YAML, a language that is a superset of JSON and is considered easier on the eye. You’ll notice that indentations are used instead of curly brackets.</p><p>For GitHub to recognize your .yml files as workflows you have to store them inside the following folder of your repository: .github/workflows/[workflow-name].yml</p><p>You can add a workflow manually by pushing your own files, or going to the “Actions” tab in your repo and either clicking on “set up a workflow yourself” or selecting one of the available templates GitHub suggests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*t_JpDfCmSSS726qFHZJoCw.png" /></figure><p>Once you have at least one workflow, you’ll be able to manage them from the same page, as well as dispatch, re-run failed jobs, and view the status of previous runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44XLTyMuwIfEAHpCqrOLxQ.png" /></figure><h3>Understanding the workflow’s structure</h3><p>Let’s examine this basic workflow that says hi to the person who initiated the run and then runs some tests, and understand the different parts that it’s constructed from.</p><pre>name: CI<br><br>on:<br>  push:<br>  pull_request:<br><br>jobs:<br>  unit-tests:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Install<br>        run: npm install  <br>      - name: Run unit tests<br>        run: npm test<br>  e2e-tests:<br>      runs-on: ubuntu-latest<br>      steps:<br>        - uses: actions/checkout@v3<br>        - name: Install<br>          run: npm install  <br>        - name: Run unit tests<br>          run: npm e2e        </pre><p>First, we need to define the workflow’s settings. We can see that this workflow has three properties: name, on, and jobs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*vAqLzDw8YwB7GYgcbzGFRA.png" /></figure><p>name is simply the workflow’s name. It’s not mandatory, however, I still recommend adding one, so it’ll be easier to manage your workflows in the “Actions” tab.</p><p>on defines the trigger of the workflow. You can set one or more. For instance, in the example shown above, the workflow will run whenever a pull request is opened or a push to any branch occurs.</p><p>If you want to make your trigger more specific, you can provide extra parameters. Each trigger event is different, so let&#39;s have a look at some examples.</p><ol><li><strong>A push to specific branches</strong></li></ol><pre>on:<br>  push:<br>    branches: <br>      [master, test]</pre><p>In this one, we want the workflow to run on a push event, but only when the branch name equals the ones we provide using the branches property. In this case, it’s “master” or “test”. If we push something to a branch named “test2”, nothing will happen.</p><p>By the way, in YAML arrays can be defined with square brackets or like so:</p><pre>on:<br>  push: <br>    branches:<br>      - master<br>      - test</pre><p>This is the exact same thing! You might see both styles in use, and it’s up to your preference.</p><p>Anyway, we can be even more specific, for instance, mention only branches that start with tests/:</p><pre>on:<br>  push: <br>    branches:<br>      - tests/**</pre><p>Or do the opposite and accept <strong>all </strong>branches but ignore everything that starts with tests/ by using branches-ignore instead of branches</p><pre>on:<br>  push: <br>    branches-ignore:<br>      - tests/** </pre><p>2. <strong>Scheduled workflow</strong></p><pre>on:<br>  schedule:<br>    - cron: &#39;0 6 * * *&#39;</pre><p>We can make our workflow run automatically on a scheduled basis, using the schedule trigger. In this example, the workflow will run every day at 6:00 AM. You can see that schedule receives an array, so you can add multiple <a href="https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule">cron settings</a> if you wish.</p><p>3. <strong>Manual workflow dispatch</strong></p><p>Another common trigger is workflow_dispatch which allows us to manually trigger the workflow directly from the GitHub Actions UI. It can even be configured to require parameters that can be later accessed by our actions.</p><pre>on:<br>  workflow_dispatch:<br>    inputs:<br>      name:<br>        type: string<br>        default: Sveta<br>        required: true<br>        description: &#39;A name passed from the caller workflow&#39;<br><br>jobs:<br>  print:<br>    runs-on: ubuntu-latest<br>    steps: <br>      - name: Print the name<br>        run: echo &quot;Hi there, ${{ inputs.name }}&quot;</pre><p>This is what it looks like inside the GitHub UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*EKS3jdQHxf4CgyfUiS4p0A.png" /></figure><p>There are many more possible triggers and configurations, so going to the <a href="https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#on">documentation</a> is the best place to learn more.</p><p>ℹ️ <strong>Note </strong>🛈<strong><br></strong>When you see an expression wrapped with ${{}} know that it’s a way to access a variable’s value, as seen in the example above. This is the way to get <a href="https://docs.github.com/en/actions/learn-github-actions/contexts#github-context">context</a> information (like which branch we’re on), <a href="https://docs.github.com/en/actions/learn-github-actions/contexts#secrets-context">secrets</a>, our workflow’s input values, and more.</p><pre> run: echo &quot;Hi there, ${{ inputs.name }}&quot;</pre><h3>Let’s get things running: the “jobs” property</h3><p>So up until now, we set up a trigger to our workflow, but now let’s get into what the workflows are actually doing — running jobs that trigger our actions!</p><p>When creating a workflow you can set it to run one or more jobs. <br><strong>Unless configured otherwise, jobs run in parallel and don’t depend on previous jobs to finish first.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*yuP2tymS4uWELZbghYxaVA.png" /></figure><p>In the scenario above, our workflow runs two jobs: “unit-tests” and “e2e-tests”, and while the workflow is activated, the jobs will run simultaneously. We will see later how we can create dependencies between jobs.</p><p>To define a job, we first give it an id (can be anything we like), and then we need to provide it with some configuration.</p><p>There are 2 mandatory parameters:</p><ol><li>runs-on : This configures the job’s runner. Runners are virtual machines (VMs) used to run the tasks defined in our jobs. GitHub provides hosted runners for each operating system (Linux, macOS, and Windows). You can see the full list of available runners <a href="https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources">here</a>, as well as their specifications.<br>If you require more granular control over your VM, you can self-host your own runners. One use case for using self-hosted runners is resource utilization. If you need to run your actions on stronger machines, <a href="https://docs.github.com/en/actions/hosting-your-own-runners">explore this option</a>.</li><li>steps — Here we list the array of actions the job will execute. The steps are executed one by one. We will go over actions in the next section.</li></ol><p>Some notable optional parameters:</p><ol><li>name — Just like with workflows, it is not mandatory to provide a name for your job, but it’s useful for visualization of your flow.</li><li>needs — Remember that we said that jobs don’t depend on each other, and run in parallel? But we can create this dependency by using the “needs” param. Let’s see the example below:</li></ol><pre>jobs:<br>  unit-tests:<br>    runs-on: ubuntu-latest<br>    steps:<br>      - uses: actions/checkout@v3<br>      - name: Install<br>        run: npm install  <br>      - name: Run unit tests<br>        run: npm test<br>  e2e-tests:<br>      runs-on: ubuntu-latest<br>      steps:<br>        - uses: actions/checkout@v3<br>        - name: Install<br>          run: npm install  <br>        - name: Run unit tests<br>          run: npm e2e<br>  send-slack-notification:<br>      needs: [unit-tests, e2e-tests]<br>      runs-on: ubuntu-latest<br>      steps:<br>        - uses: actions/checkout@v3<br>        - name: Send notification<br>          uses: rtCamp/action-slack-notify@v2<br>          env:<br>            SLACK_WEBHOOK: ${{ secrets.SLACK_WEBHOOK }}<br>            SLACK_CHANNEL: team-ci<br>            SLACK_TITLE: Finished running tests<br>            SLACK_MESSAGE: &#39;Hooray :rocket:&#39;</pre><p>We can see that the last job, send-slack-notification requires unit-test and e2e-tests to finish, since we want to send that slack notification only when both of these jobs are done executing.</p><p>3. if — We can add a condition to our job that will allow us to set it to run only if some condition/s are met. For instance, let’s say that our workflow can be triggered by both push and pull_request events, but we want to run a specific job in this flow that will only run if the trigger was specifically a “push” event.</p><pre>name: Test<br>on: <br>  push:<br>  pull_request:<br><br>jobs:<br>  print-something-on-push:<br>    if: github.event_name == &#39;push&#39;<br>    runs-on: ubuntu-latest<br>    steps:<br>      - name: Print<br>        run: echo &quot;This job runs on push only&quot;.<br>  print-always:<br>      runs-on: ubuntu-latest<br>      steps:<br>        - name: Print<br>          run: echo &quot;This job always runs&quot;.</pre><p>4. outputs — A job can produce an output that can later be accessed by other jobs (combined with needs of course, as we have to wait for that job to resolve first). The output is an object, so you can pass any number of parameters that you want.</p><pre>name: Job outputs test<br>on:<br>    workflow_dispatch:<br>        inputs:<br>            version:<br>                description: &quot;Version&quot;<br>                required: true<br>                type: string<br>jobs:<br>    prepare-version-id:<br>        runs-on: ubuntu-latest<br>        outputs:<br>            version_w_hyphens: ${{ steps.replace-string.outputs.replaced }}<br>        steps:<br>          - uses: frabert/replace-string-action@v2<br>            id: replace-string<br>            with:<br>              pattern: &#39;\.&#39;<br>              string: ${{ inputs.version }}<br>              replace-with: &#39;-&#39;<br>          - name: &quot;print&quot;<br>            run: echo ${{ steps.replace-string.outputs.replaced }}<br>    print-stuff:<br>        needs: [prepare-version-id]<br>        runs-on: ubuntu-latest<br>        steps:<br>          - name: &quot;print version id from another job&quot;<br>            run: echo ${{needs.prepare-version-id.outputs.version_w_hyphens}}</pre><p>In this example, we have a workflow that expects a string input called version on dispatch. <br>Then, let’s imagine that we need this version for multiple usages, and some of them require us to replace the dots in the string with hyphens.</p><pre>prepare-version-id:<br>    runs-on: ubuntu-latest<br>    outputs:<br>       version_w_hyphens: ${{ steps.replace-string.outputs.replaced }}</pre><p>We can see that prepare-version-id defines the outputs object, with one item — version_w_hyphens which returns the value of the step that was responsible for replacing the dots with hyphens. Actions can return output as well, but more on that later.</p><p>Then inside the other job called print-stuff we can access this value by calling needs.[job-id].outputs.[outpus-key] and in our case needs.prepare-version-id.outputs.version_w_hyphens.</p><h3>Now to the star of the show: Actions</h3><p>As we stated before, jobs run an array of steps, where each step executes an action, where an action is a set of commands or tasks. There are 3 kinds of actions you can work with.</p><ol><li><strong>Using open-sourced actions<br></strong>For the most part, there’s a high probability that someone already has created a solution for at least some of the tasks you wish to accomplish. For instance, if you need to send a slack notification, publish to GitHub pages, upload an artifact, and so on, the community has got you covered.</li></ol><pre>steps:<br>  - name: Checkout<br>    uses: actions/checkout@v3</pre><p>This is an example of one of the most useful public actions there are, that allows you to checkout to the branch that’s in the workflow’s context (or to another one if you wish). <br>All you have to do in order to use such an action is to create a step with the uses property and provide the action&#39;s location, ie [github-user]/[repo]@[version] .<br>You can specify a specific version, for example @v3 in that case, or simply refer to the latest possible version by using @master (though then you’re opening yourself to be affected by bugs or breaking changes).</p><p>That’s it. You don’t have to actually install or configure anything.</p><p>Some actions might expect some input parameters (or have some optional ones). In that case, all you have to do is to add thewith: property to the step and pass the required values.</p><pre>steps:<br>- uses: frabert/replace-string-action@v2<br>  name: Replace string<br>  id: replace-string<br>  with:<br>    pattern: &#39;\.&#39;<br>    string: ${{ inputs.version }}<br>    replace-with: &#39;-&#39;</pre><p>Some actions might also return some sort of output. For instance, in this example, we use this action to run some regex expression on a string, so naturally, we need the result.<br>To do that we will need to provide an id to the step, so we can access it later by calling steps.[step-id].outputs.[key]</p><pre>steps:<br>  - uses: frabert/replace-string-action@v2<br>    id: replace-string<br>    with:<br>      pattern: &#39;\.&#39;<br>      string: ${{ inputs.version }}<br>      replace-with: &#39;-&#39;<br>  - name: &quot;print replaced value from previous step&quot;<br>    run: echo ${{ steps.replace-string.outputs.replaced }}</pre><p>⚠️ You should use caution with 3rd party actions as they may contain malicious code or vulnerabilities that can compromise the security of your project and lead to a data breach or other negative consequences. Make sure to check if the action is properly maintained and has a community base.</p><p>2. <strong>Running shell commands</strong></p><p>We can also run our own code, by running shell commands. The default depends on the kind of runner you’re using. For instance, for Linux (ubuntu) it would use bash. You can change the shell type by providing an explicit one. See all the possible shells <a href="https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsshell">here</a>.</p><pre>steps:<br>  - name: Run install<br>    run: npm install<br>    shell: bash #an optional setting</pre><p>To run a multiline script, we can use a pipeline, like so:</p><pre>steps:<br>  - name: Run install and test<br>    run: |<br>        npm install    <br>        npm test</pre><p>In case we want our action to provide an output that can be accessed by other actions, we have to run the following command:</p><pre>- name: Set output<br>  run: echo &quot;{name}={value}&quot; &gt;&gt; $GITHUB_OUTPUT</pre><p>We can set as many as we want. Accessing the values from other steps follows the same convention as mentioned in the previous section.</p><pre>steps:<br>  - id: example<br>    run: |<br>      echo &quot;animal=&#39;Dog&#39;&quot; &gt;&gt; $GITHUB_OUTPUT  <br>      echo &quot;name=&#39;Fluffy&#39;&quot; &gt;&gt; $GITHUB_OUTPUT<br>  - name: Print<br>    run: |<br>      echo &quot;Animal type: ${{steps.example.outputs.animal}}&quot;<br>      echo &quot;Animal name: ${{steps.example.outputs.name}}&quot;</pre><p>3. <strong>Running an action from a file<br></strong>Let’s say we have a custom-made action that we use in multiple workflows and we don’t want to repeat writing. In that case, we can create an action.yml file and store it inside our repo inside the following path: .github/actions/[action-id]/action.yml</p><p>Here’s an example action that’s using the <a href="https://docs.github.com/en/actions/creating-actions/creating-a-composite-action">composite action</a> method where you can create an action with the regular YML syntax and run one or more steps:</p><pre>name: &#39;My Action&#39;<br>description: &#39;An example of a custom action&#39;<br>inputs:<br>  message:<br>    description: &#39;A message to print&#39;<br>    required: true<br><br>runs:<br>  using: composite<br>  steps:<br>    - run: echo Hello ${{ inputs.message }}.<br>      shell: bash</pre><p>Then we can refer to it by calling it like this:</p><pre>name: My Workflow<br>on: push<br>jobs:<br>  print-message:<br>    runs-on: ubuntu-latest<br>    steps:<br>    - name: Print message<br>      uses: ./.github/actions/my-action<br>      with:<br>        message: &#39;Hello, world!&#39;</pre><p>There are other methods to create actions, where you create the action.yml file just to set up the input and output params and the script itself is written in other languages of your choice (JS, python, shell, and more).<br>You can read about it <a href="https://docs.github.com/en/actions/creating-actions">here</a>.</p><h3>Some other action settings</h3><p>Actions have some other parameters that are worth mentioning. <br>Of course, the name parameter, which again will make it easier to follow in the log, but the most useful one is if . We already discussed it as a possible parameter for jobs, but actions can also be limited to running only on condition.</p><p>One of the useful conditions we can check for is the job’s status. For instance, send a failure message to Slack, but only when the job has failed. See the full list of status checks <a href="https://docs.github.com/en/actions/learn-github-actions/expressions#status-check-functions">here</a>.</p><pre>steps:<br>  ...<br>  - name: The job has succeeded<br>    if: ${{ success() }}<br>    run: # do something if all the previous steps have finished successfuly<br>  - name: The job has failed<br>    if: ${{ failure() }}<br>    run: # do something if the job has filed</pre><p>Another useful action property is continue-on-error . By default, if one step of a job failed, it will cause the entire job to end with the “failure” status. However, sometimes we might want to not count this failure as part of the whole job’s status. In that case, we can pass this property to make the run ignore this step’s status.</p><pre>steps: <br>  - name: Ignore my failure<br>    continue-on-error: true</pre><h3>Testing our workflow</h3><p>So now that we have a workflow, how do we actually test it?<br>Well, it’s simple and tricky at the same time. To be able to run a workflow its file must either exist on the master/main branch <strong>or</strong> use a trigger that occurs when pushing to the branch we’re writing our action on.</p><p>If the workflow happens to have a worflow_dispatch trigger and we want to try some changes, we can apply them to a branch, add initiate the workflow from our branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*B7yXKTCxx1u-S-deLOcsMA.png" /></figure><p>There is also another way that allows you to run actions locally on your machine, but it’s a little trickier to set up. You can read about it <a href="https://github.com/nektos/act">here</a>.</p><p><strong>And that’s it! These were the basics of what you need to know to get started with GitHub actions. Hope you will find it useful!</strong></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81e27b4d4952" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/github-actions-a-beginners-guide-to-automating-your-development-process-81e27b4d4952">GitHub Actions: A Beginner’s Guide to Automating Your Development Process</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started With Three.js]]></title>
            <link>https://medium.com/geekculture/getting-started-with-three-js-1c2d02e18330?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2d02e18330</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 17:03:31 GMT</pubDate>
            <atom:updated>2022-03-16T22:02:52.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="getting started with three.js" src="https://cdn-images-1.medium.com/max/1024/1*gpGc28Fet1z9ikx5ULB28Q.jpeg" /></figure><p>The ability to render 3D objects in the browser opens up many exciting possibilities for creating interactive experiences. Whether you’re looking for a new way to showcase products on your e-commerce site, creating stunning landing pages, or maybe even developing a game.</p><p>Since handling WebGL directly (JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser) can be complex, libraries, such as three.js, provide a simplified way to deal with rendering, animating, and interacting with 3D objects, while doing all the heavy lifting behind the scenes.</p><p>With that being said, three.js itself can still be a little overwhelming for developers who have never dealt with 3D before. Hopefully, this article will get you up to speed and present the necessary basis, that may assist you even if you’ll require more advanced features later on.</p><h3>What does it take to render a simple cube?</h3><p>The reason why working with 3D for a web developer might be confusing at first, is that even a simple task such as rendering a cube requires some knowledge in 3D jargon.</p><p>If for instance, someone tells you, the web developer, to render a red box, I bet what you have in mind is “ok, I’ll create a div, use some CSS to size, place, and color it”. Pretty straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3yZNYP1NCy7x3ca-3cxijQ.png" /></figure><p>However, to do the same in 3D will require you to:<br>A. Create something called a “scene”<br>B. Define a cube geometry<br>C. Create a material and attach it to the cube (to make it red)<br>D. Create a camera<br>E. Add lighting<br>F. Tell three.js to render all that</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F3z9rr&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F3z9rr&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F3z9rr%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/c79b96479abc62fff95ac02b9f88cdc9/href">https://medium.com/media/c79b96479abc62fff95ac02b9f88cdc9/href</a></iframe><h3>The scene</h3><p>In three.js, a scene is like a container that holds all the objects used to render our 3D image. Think about a theatre stage, where we place the actors, the set, and the lighting. <br>In the same manner, we assign 3D objects and lighting to a scene.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/978945f10fbdcef95ccf0b1dae5ee000/href">https://medium.com/media/978945f10fbdcef95ccf0b1dae5ee000/href</a></iframe><p>And just like we might have multiple stage sets in our theatre, each showing a different play, we can create multiple scenes and switch between them, or render them simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*N5fJqYgtB_9mGX_S" /><figcaption>Origin: <a href="https://threejs.org/examples/?q=camera#webgl_camera">https://threejs.org/examples/?q=camera#webgl_camera</a></figcaption></figure><h3>3D geometry</h3><p>A 3D geometry is basically a set of instructions for “how to create a 3D shape”. It consists of faces, edges, and vertices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5pgWxMhhvQyLTWMhFSTbQ.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Polygon_mesh">https://en.wikipedia.org/wiki/Polygon_mesh</a></figcaption></figure><p>Luckily, three.js provides us with some built-in geometry classes, such as BoxGeometry, SphereGeometry, CylinderGeometry, and so on.</p><p>For example, to create a simple box, all we need to do is to provide the width, height, and depth. We don’t need to delve into the complexities of defining all the faces <a href="https://github.com/mrdoob/three.js/blob/dev/src/geometries/BoxGeometry.js">ourselves</a>.</p><p>The size unit used in three.js represents meters, so 1 unit = 1 meter.</p><pre>const geometry = new THREE.BoxGeometry(10, 10, 10);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*v8sPdYuXFfEDvT6oddIDvA.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Shape">https://en.wikipedia.org/wiki/Shape</a></figcaption></figure><p>In case you’re not happy with the existing geometries or need to create your own geometry classes, it is very possible. You can see some examples provided by three.js <a href="https://github.com/mrdoob/three.js/tree/dev/examples/jsm/geometries">here</a>.</p><h3>Materials</h3><p>Imagine holding two cubes in your hands, one made from glass, and the other from concrete. Both maybe have the same shape, but they look different and have distinct physical attributes such as reflectiveness, surface, and opacity.</p><p>In the 3D world, we use materials to define such attributes for our 3D objects.</p><p>With three.js we can either create our own materials with the built-in Material classes (such as MeshMatcapMaterial or MeshLambertMaterial), each has its own attributes, or load materials externally using MaterialLoader.</p><pre>// A basic material, just coloring our cube red<br>const material = new THREE.MeshStandardMaterial({ color: 0xff0000 });</pre><p>Texture maps are also worth mentioning. These are image files that can be used to define much more detailed materials, and make them look real. There are many types of texture maps, such as “diffuse map” which defines the colors, or the “normal map” which defines the surface of our object. Typically multiple texture maps are applied together. <a href="https://conceptartempire.com/texture-maps/">This great article</a> explains each texture map in detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*u3IKdVptUBOL9kFm60jY0Q.png" /><figcaption>Multiple texture maps are used to define the realistic texture of a ball of grass and soil</figcaption></figure><h3>Mesh</h3><p>A mesh is an object representing part of the model. It contains a geometry and its material. A 3D model can be constructed from multiple meshes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*oxYC-s0TT2kHYYmOYoTWuQ.png" /><figcaption>Each highlighted part is a mesh. All meshes combined define the model.</figcaption></figure><pre>const geometry = new THREE.BoxGeometry(10, 10, 10);</pre><pre>const material = new THREE.MeshStandardMaterial({ color: 0xff0000 });</pre><pre>const cube = new THREE.Mesh(geometry, material);</pre><h3>Loaders</h3><p>Sometimes we would like to import 3D models from existing files created by 3D modeling programs, and not create them from scratch. For that, we can use loaders, which are functions that are responsible for loading such files and converting them into three.js objects.</p><p>There is a different loader for each separate type of 3D file. For instance, loading a GLTF file would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37ae53e30aa8b079bd3e3f57c7bd150b/href">https://medium.com/media/37ae53e30aa8b079bd3e3f57c7bd150b/href</a></iframe><p>Did you notice that the GLTFLoader class is not imported from the “three” packages directly but from some mysterious “examples” folder? This is because loaders are not part of the core three.js library, but an extension. Despite the misleading name (“examples”), this folder contains some official extensions, that are maintained together with the base package.</p><p>The idea is that if you’re not happy with one of them, or need some extra features, you can simply copy these files to your project and modify them as you see fit. Of course, you can also use loaders or other extensions made by other developers.</p><h3>Camera</h3><p>A camera is like a window to our scene. Without a camera defined, we simply see nothing. When defining a camera we create what is called a “frustum” — a mathematical term for a four-sided rectangular pyramid with the top cut off.</p><pre>const perspectiveCamera = new THREE.PerspectiveCamera(<br>  50, <em>// fov — Camera frustum vertical field of view.<br>  </em>width / height, <em>// aspect — Camera frustum aspect ratio.<br>  </em>1, <em>// near — Camera frustum near plane.<br>  </em>2000 <em>// far — Camera frustum far plane.<br></em>);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MVTs2C7BprzGKfDIhdkPqg.png" /><figcaption>A frustum</figcaption></figure><p>There are multiple types of cameras in three.js, but the two most useful ones are the perspective camera and the orthographic camera.</p><p><strong>Perspective camera — </strong>In this mode, depth perception is emulated in order to reflect the way the human eye perceives the world. For example, if one cube is positioned closer to us than the other, it will appear to be larger. This is the most common camera you’ll probably use.</p><p><strong>Orthographic camera — </strong>With the orthographic camera, there is no depth perception, so no matter where the object is placed in the scene, it will look the same size. This is useful for isometric games, for instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*MA2MPpCVQdparoFO" /><figcaption>An isometric video game using an orthographic camera</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Forthographic-and-perspective-fd99jm%3Ffontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ffd99jm&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ffd99jm%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/618af19bc4a742bddc3b553e493df377/href">https://medium.com/media/618af19bc4a742bddc3b553e493df377/href</a></iframe><h3>Lighting</h3><p>Just like in real life, without lights, our scene would become pitch black.</p><p>Three.js has multiple built-in light sources we can use and even combine to create the perfect setting.</p><p>It’s worth noting that some light classes support casting shadows, while some don’t, and it depends on their physics. For instance, “Dynamic Light” is a light that gets emitted in a specific direction. This light will behave as though it exists infinitely far away and the rays produced from it are all parallel. A common use case for this is to simulate daylight. Since it’s a one-directional light, it can emit shadows.</p><p>The AmbientLight on the other hand is a light that globally illuminates all objects in the scene equally. Since every spot in the scene receives the same amount of light, AmbientLight can’t be used to cast shadows.</p><p>When defining a light we would usually provide color and intensity.</p><pre>const directionalLight = new THREE.DirectionalLight(0xffffff, 1);</pre><pre>directionalLight.position.set(0, 2, 10);</pre><p>Lights can also come from external sources, like HDR files (An HDR is a 360-degree high dynamic range image wrapped around a 3D model.)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Feiomr5&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Feiomr5&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Feiomr5%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/a9e463eafc3c888b03f1d23cc07c3d80/href">https://medium.com/media/a9e463eafc3c888b03f1d23cc07c3d80/href</a></iframe><h3>Shadows</h3><p>Casting shadows is a pretty expensive calculation, so in three.js it’s turned off by default. In order to support it we will need to:</p><p>A. Turn on shadow support for the renderer (see next section about what a renderer is). We will also need to provide a type of shadow map, each provides a little different effect and calculation efficiency. See the details <a href="https://threejs.org/docs/#api/en/constants/Renderer">here</a> under “Shadow Types”.</p><pre>renderer.shadowMap.enabled = true;<br>renderer.shadowMap.type = THREE.PCFSoftShadowMap;</pre><p>B. Tell each individual mesh if it should emit and/or receive shadows.</p><pre>cube = new THREE.Mesh(geometry, material);</pre><pre>cube.castShadow = true;<br>cube.receiveShadow = true;</pre><p>C. Allow the light source to cast a shadow. We also should provide the shadow map size and bias, which modifies the shadows pixelation.</p><pre>const spotLight = new THREE.SpotLight(0xffffff, 1);</pre><pre><em>// make it cast shadows<br></em>spotLight.castShadow = true;<br>spotLight.shadow.mapSize.width = 1024;<br>spotLight.shadow.mapSize.height = 1024;<br>spotLight.shadow.bias = -0.0001;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fvuulk9&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fvuulk9&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/aef80034272c2091e73976f0e52b705a/href">https://medium.com/media/aef80034272c2091e73976f0e52b705a/href</a></iframe><h3>Renderer</h3><p>The render class is used for… well… rendering all of the scene components into the canvas element. This one is pretty straightforward.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c253ad4a01e0467034968b6e7cecd05/href">https://medium.com/media/0c253ad4a01e0467034968b6e7cecd05/href</a></iframe><p>You will need to provide the desired canvas size using the setSize property, and the pixel density of the device. Note that in a case where the size of the canvas is responsive and depends on the page size, we should update the renderer and camera on window resize.</p><pre>function onWindowResize() {<br>  camera.aspect = window.innerWidth / window.innerHeight;<br>  camera.updateProjectionMatrix();</pre><pre>  renderer.setSize(window.innerWidth, window.innerHeight);<br>}</pre><h3>Animating</h3><p>More often than not, we’re not going to use three.js just to render one static 3D image. We would want the user to interact with the scene or create animations. To make three.js re-render the canvas, we would need to call renderer.render(scene, camera); each time.</p><p>If our changes are frequent, however, for instance when we add an auto rotation effect to our scene, we can simply do something like this:</p><pre>function animate() {<br>   // Schedual the next update<br>   requestAnimationFrame(animate);</pre><pre>   // Some other changes that should occur on animate<br>   // for instance, here we can rotate the cube a litle on every frame<br>   <em>cube.rotation.x += 0.01;<br>   cube.rotation.y += 0.01;</em></pre><pre><em>   </em>// re-render<br>   renderer.render(scene, camera);<br>}</pre><pre>animate();</pre><p>This is also required to support loaded 3D files which come with their own animation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*vy1SwNqvjC0h6hHxWSngPg.gif" /><figcaption>Animation loop from file</figcaption></figure><h3>Camera controls</h3><p>Camera control is another type of extension that adds a layer of interactivity to our scene, allowing the users to zoom in and out, rotate the scene or even navigate within it.</p><p>Let’s take as an example one of the more common camera controls: the orbit controls, which just by defining them lets the user rotate and zoom into the scene.</p><pre>const orbitControls = new OrbitControls(camera, renderer.domElement);</pre><p>Orbit controls have some other neat features out of the box, like adding autorotation to the scene.</p><p>Note that you will have to add orbitControls.update() to your animate function in order to support it.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fbqov8b&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fbqov8b&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fbqov8b%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/2e537b8a56d2a1ab2959367c10a6e3a1/href">https://medium.com/media/2e537b8a56d2a1ab2959367c10a6e3a1/href</a></iframe><h3>Mouse events</h3><p>Three.js essentially rendered a canvas, and as such, picking up mouse events is trickier than what you might be used to.</p><p>So what happens if you need to track clicks or hover over a 3d object? That’s what the Raycaster class is for. Raycasting is used for working out what objects in the 3d space the mouse is interacting with.</p><p>Here’s a basic example of how to pick up clicked on objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09025d85a4e99ea5ad9232990c12159a/href">https://medium.com/media/09025d85a4e99ea5ad9232990c12159a/href</a></iframe><p>And a demo, so you can see it in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ft72zu3&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ft72zu3&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ft72zu3%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/cf93782843369700139efdf80a2e6576/href">https://medium.com/media/cf93782843369700139efdf80a2e6576/href</a></iframe><p>And that should cover all the basics. Hopefully, three.js makes a little more sense now!</p><h3>Extra read</h3><ul><li><a href="https://discoverthreejs.com/">https://discoverthreejs.com/</a> — An amazing free online three.js book and guide. A great resource to learn from.</li><li><a href="https://threejs.org/examples">https://threejs.org/examples</a> — the three.js documentation is not beginner-friendly, but it does worth using the examples section to get ideas and learn about more complex topics.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2d02e18330" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/getting-started-with-three-js-1c2d02e18330">Getting Started With Three.js</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[React —  5 Things That Might Surprise You]]></title>
            <link>https://medium.com/geekculture/react-5-things-that-might-surprise-you-ddefd9fbac0f?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddefd9fbac0f</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 15:31:05 GMT</pubDate>
            <atom:updated>2021-06-10T14:55:08.998Z</atom:updated>
            <content:encoded><![CDATA[<h3>React — 5 Things That Might Surprise You</h3><p>The React library is pretty straightforward and is relatively easy to get into, especially with the wide variety of materials that exist to help you learn it. But every tool has its share of tricks or issues that these tutorials usually don’t cover. You get to learn them when someone reviews your code, or worse — when you’re facing a problem and are desperate to find a solution. Hopefully, with this article, I might reveal some of these things about React, and maybe even surprise you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ii44ETPS0c5dDsAmlvdXmA.jpeg" /></figure><h3>1. Setting the state by using the previous state is unpredictable.</h3><p>State management is the foundation of React, and while useStateis probably the most common hook, there might be some unawareness of its actual behavior.</p><p>Let’s have a look at the following component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c5cf2a9fb010abb0da9131de324a0ad/href">https://medium.com/media/1c5cf2a9fb010abb0da9131de324a0ad/href</a></iframe><p>What would you expect the value of the counter state to be, after a user clicks on the button?</p><p>A. 2<br>B. 1</p><p>Not sure? Try it out yourself:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fkkyix&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fkkyix&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fkkyix%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/0ca16354ec59bb20499b8a9137074a0f/href">https://medium.com/media/0ca16354ec59bb20499b8a9137074a0f/href</a></iframe><p>Well, whether you knew that, guessed correctly. or just tested the demo — the answer is B!</p><p>The reason is that during our state update we used the previous state value: setCounter(count + 1). Essentially, the state setter function is wrapped inside the functional component closure, so it is provided with the value that was captured in that closure. It means that when it will eventually be executed (the state setter function is asynchronous), it might hold a state value that is no longer relevant. On top of that, consecutive execution of setState might cause React’s scheduling algorithms to handle multiple very fast state updates using the same event handler.</p><p>The same problem might also occur when setting the state inside an asynchronous function:</p><pre>onClick={() =&gt; { <br>   setTimout(() =&gt; { setCounter(counter + 1); ), 1000);<br>}};</pre><p>But, no worries, React actually provides an easy solution to this problem — “<strong>functional updates</strong>”.</p><pre>setCounter((prevCounter) =&gt; prevCounter + 1);</pre><p>Instead of passing the value directly to setCounter, we pass a function. This function receives as a parameter the <strong>previous state.<br></strong>This way we can be sure that React provides us the correct value of the previous state, and avoid the scenarios that might cause the unexpected behavior.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fuhzze&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fuhzze&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fuhzze%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/88263eb78e726a5837f5d0c0b88f027c/href">https://medium.com/media/88263eb78e726a5837f5d0c0b88f027c/href</a></iframe><p><strong>Whenever your state update is relying on the previous state, be sure to use functional updates!</strong></p><p>Another benefit of this is to allow correct memoization of functions, since passing the value as a dependency would re-create the function on every state change.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ec94603529d26a3bc9d692250cc2f94/href">https://medium.com/media/4ec94603529d26a3bc9d692250cc2f94/href</a></iframe><h3>2. You can use useRef to store a static variable</h3><p>We are accustomed to using the ref mechanism in React as a means to access an element’s DOM node, whether because we need it to calculate its size, set a focus status, or basically do anything React can’t do naturally. But refs can also be used for a different purpose — something that we could achieve for free with class components, but we can’t with functional ones — keep a static variable that won’t be recreated on every render.</p><p>Why would we need to do so? Well, it really depends on the situation. For instance, let’s say we’re using some javascript library that was not written for React.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Flffhh&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Flffhh&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Flffhh%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/99e8ef008e28c2ec1315fc929c084b1b/href">https://medium.com/media/99e8ef008e28c2ec1315fc929c084b1b/href</a></iframe><p>In this example, we have a class Dog. Dog has two functions — one to set its name, and one to bark it.</p><p>If we tried to create the instance of this class using a simple variable, what would happen is that in case (for any reason) the component is re-rendered, a new instance will be created. So any changes we did so far will go away.</p><p>But by using a ref, we will be able to keep our instance alive, until we decide to override it by setting a new value to ref.current.</p><pre>someRef.current = newValue;</pre><h3>3. React can be forced to re-mount a component</h3><p>Writing to the DOM is one of the more costly actions that can be done by React. This is why we usually don’t want to remount components unless it’s absolutely necessary. Alas — sometimes we must, for various reasons. So on that occasion, how do we even tell react to unmount and immediately mount again a component? With a simple trick — by providing a key to our component, and changing its value.</p><p>The key prop is a special React property you most likely have learned about the first time you tried to render an array of components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*kYAzmHVqNQ5mcKOQbIj76w.png" /><figcaption>The famous React warning</figcaption></figure><p>A key is something that helps React keep track of an element, even if we’ve changed its position within our component’s structure or re-rendered the parent (Otherwise each render would cause the entire component array to be re-mounted, which is <strong>bad</strong> for performance).</p><p>Using this mechanism, we can trick React to think a component is not the same as its previous self and cause it to re-mount.</p><p>See for yourself:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgwr2p&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fgwr2p&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea32bc6e1d21999d1dc70972afee2ab9/href">https://medium.com/media/ea32bc6e1d21999d1dc70972afee2ab9/href</a></iframe><p>Why would we need that at all, by the way? Well, it’s a quick way to create a “reload” button for your app, for example. Another use case is mixing DOM handling with React, where we want React’s state to reflect updates that were made to the DOM from “outside”.</p><p>But it should still be avoided unless it&#39;s the last resort.</p><h3>4. Context doesn’t work the way you would expect it to</h3><p>Context API is a great built-in solution for sharing state between components and avoiding “prop drilling” — passing props multiple levels down — from one component to the other, sometimes just for the sake of passing them down where it&#39;s actually needed.</p><figure><img alt="“context” — You Keep Using That Word, I Do Not Think It Means What You Think It Means" src="https://cdn-images-1.medium.com/max/537/1*S2nLcy0D3Cfz5WYV-BlzCA.jpeg" /></figure><p>While it’s very useful, it also has its limitations.</p><p>When used for recurring or complex updates, it’s not that efficient. <a href="https://github.com/facebook/react/issues/14110#issuecomment-448074060">Quoting Sebastian Markbage</a>, a Facebook engineer:</p><blockquote><em>“My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It’s also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions.</em><strong><em> It’s not ready to be used as a replacement for all Flux-like state propagation.</em></strong><em>”</em></blockquote><p>Even the React-Redux team had to revert parts of the library re-written with context API in <a href="https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/#v7-0">version 6</a>, simply due to a significant performance hit compared to its previous version (Now React-Redux only uses context to pass down the store reference).</p><p>Another major issue is the incapability of components to subscribe only to <strong>part </strong>of a context (when a context value is an object, not a primitive).</p><p>Let’s have a look at the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfMhJHknRHezVrIilk6KNQ.gif" /><figcaption>Updating any subset of the context will cause a re-render to <strong>everything</strong> subscribed</figcaption></figure><p>In this example, the context stores <strong>an object</strong> containing two entries: name and age. We then have two components subscribed to this context. One is using just the age, and the other the name. But — when updating just one of the entries, either the name or the age, both &lt;Name&gt;and &lt;Age&gt; components are re-rendered. You can access this demo <a href="https://codesandbox.io/s/context-limitations-4jhqs?file=/src/App.js">here</a> and see how it works.</p><p>The fact that all components subscribed to a context holding a non-primitive type value are re-rendered is obviously inefficient, and on some occasions might cause a performance issue.</p><p>There are some native solutions to this issue, but most of them are cumbersome. You can also consider using a 3rd party library, such as <a href="https://github.com/dai-shi/use-context-selector">use-context-selector</a>, which makes dealing with this problem much easier.</p><h3>5. React has a whole API to deal with the children prop</h3><p>Passing children to a component is a very common pattern, whether you’re using composition, or just writing a reusable wrapper component.</p><p>But, did you know that instead of just rendering the children, React also provides you an API allowing you to do all sorts of things with it?</p><p>First of all — children can be a string, an object, or an array of any of these types. It makes it quite hard to iterate over the children like this, so we can call toArray to transform children to an array:</p><pre>React.Children.toArray(children)</pre><pre>// If you want to use map/forEach:<br>React.Children.map(children, fn)<br>React.Children.forEach(children, fn)</pre><p>We can also call count to know how many children there are, avoiding the same hassle:</p><pre>React.Children.count(children)</pre><p>If you need to enforce a single child in your component (I recently noticed formik does so), you can simply include the following line in your component, and React will run the check and error handling for you:</p><pre>React.Children.only(children)</pre><p>You can use the following sandbox to play around with it:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fi9vvw&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fi9vvw&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fi9vvw%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/5881a6882ba78bd340a84db9b9fe0c3d/href">https://medium.com/media/5881a6882ba78bd340a84db9b9fe0c3d/href</a></iframe><p>And that was it! I really hope some of these will be useful for you. Please feel free to share in the comments any other React tricks that you know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddefd9fbac0f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/react-5-things-that-might-surprise-you-ddefd9fbac0f">React —  5 Things That Might Surprise You</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[The Complete Guide to Front-end Developer Interviews]]></title>
            <link>https://levelup.gitconnected.com/the-complete-guide-to-front-end-developer-interviews-e2f0f611c91e?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2f0f611c91e</guid>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Sat, 02 Jan 2021 15:44:09 GMT</pubDate>
            <atom:updated>2021-01-06T17:02:08.719Z</atom:updated>
            <content:encoded><![CDATA[<p>Interviews are hard, especially technical interviews where you’re expected to think, solve, and analyze all while the interviewer stares at you. But what people don’t realize is that being interviewed is basically just another skill, and skills can be honed with the right information and practice.</p><p>So if you’re on your job hunt as a Front-end developer right now, you’ve come to the right article, as this one will tell you all you need to know to be prepared!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Acp2-iKTTMeBiDJehnYKA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/s/photos/interview?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>About a year and a half ago, the company I used to work for was shut down, and all 100 employees found themselves seeking a new place. I worked there for more than 9 years, so starting a job hunt was unsettling. I knew that my JS skills are (probably) fine, but I didn’t know what to expect during technical interviews.</p><p>So based on my own experience, the experiences of my colleagues who shared the same fate, as well as my current practice as an interviewer myself, I decided to write down this article. It is my hope that it will help you prepare, and take away some of the concerns you might have about what awaits you.</p><h3>What Kind of Questions Should You Expect?</h3><p>Each company has its own interviewing strategy, but in the end, most of them fall under the same categories, and it doesn’t matter if you’re interviewing to GAFAM or a small tech company. These are the most common topics you’ll be interviewed about:</p><h3><strong>Javascript Questions</strong></h3><p>Well, as a front-end developer you obviously should know Javascript already, but you’re also expected to understand how it works and behaves. It doesn’t matter if in your day-to-day you work with Angular/React/Vue, you <strong>are expected</strong> to know the basics.</p><p><strong>Some example questions could be:<br></strong>A. Explain what the event loop is<br>B. Explain what a Promise is<br>C. Closure and Context questions (what is “this”)<br>D. What is the difference between an arrow function and a regular function?<br>E. Implement Array.prototype.map/reduce<br>F. What is a debounce/throttle function? Implement them.<br>G. Javascript prototypal inheritance questions</p><p><strong>Some helpful resources:<br></strong><a href="https://www.sitepoint.com/5-typical-javascript-interview-exercises/">5 Typical JavaScript Interview Exercises</a><br><a href="https://johnresig.com/apps/learn/">Learning Advanced JavaScript</a><br><a href="http://bonsaiden.github.io/JavaScript-Garden/">Javascript Garden</a><br><a href="https://eloquentjavascript.net/">Eloquent Javascript</a></p><h3>Algorithms</h3><p>It is true that it’s unlikely you’ll ever need to traverse a binary tree while working as a Front-end developer (there are exceptions of course). But nonetheless, algorithm questions are very popular in interviews (especially if your goal is to work at GAFAM).</p><p>1. <strong>Array or Object related questions</strong></p><p>Example: <br>1. Reverse a string<br>2. Write a function that checks if a word is a palindrome<br>3. Given a string of characters, return the character that appears the most often.</p><p>2. <strong>BFS/DFS questions (traversing a tree)</strong></p><p>Example:<br>1. Write a function that solves a maze (the maze is a multidimensional array- with values of 0 — wall, 1 — floor, 2 — exit). The function receives a start coordinate and should return whether you can get out of the maze.</p><p>3. <strong>Linked List</strong></p><p>Example:<br>1. Reverse a linked list<br>2. Find the nth node from the end of the linked list</p><p>You should also probably refresh your knowledge about the <strong>difference between Recursion and Iteration</strong> and about <strong>Time and Space complexity.</strong></p><p><strong>Some helpful resources:<br></strong><a href="https://medium.com/siliconwat/algorithms-in-javascript-b0bed68f4038">40 Problems, Solutions, and Explanations<br></a><a href="https://www.udemy.com/course/js-algorithms-and-data-structures-masterclass/">JavaScript Algorithms and Data Structures Masterclass</a> —(Note: This one is no doubt the best Udemy course ever created, especially if you don’t have a degree in Computer Sciences, or if you need a refresher about algorithms and data structures).<br><a href="https://www.codewars.com/">Codewars</a> (or any other equivalent site, like HackerRank or LeetCode).</p><h3>What To Pay Attention To When Solving an Algorithm Question</h3><p>A. Don’t rush to solve, it’s ok to ask for a few minutes to think.</p><p>B. When you do start solving, it is highly recommended that you talk about what you’re doing, even if you’re not sure about your thoughts. The examiner usually looks to understand your process of thinking. It is not always necessary to reach a perfect and working solution. If you’re not comfortable talking aloud, or just not used to it, practice at home by solving some example questions.</p><p>C. If you can, you should first write your plan of action in words or pseudo-code. This will show the interviewer that you do not rush to solve things and that you can plan.</p><p>D. If you get stuck at the beginning, don’t panic! Start with the simple things. Think about input and output. Solve edge cases.</p><p>E. Pay attention to the code effectiveness of your solution. If you understand that the complexity is not really good, say it out loud, and try together with the examiner to reach a better solution.</p><p>F. It’s totally fine to ask questions. A good examiner will try to help you reach a solution.</p><p>G. You’re usually expected to solve these type of questions on a whiteboard/piece of paper. Since it’s not how we usually write code, you may find it’s harder to think like this. This is again something that worth practicing beforehand!</p><h3>React/Angular/Vue (Home) Assignment</h3><p>Some places will require you to build some sort of a simple app using a specific framework/library. Depending on the company, it can either be a home assignment, or you’ll have to do so while in the companies office. If it’s the latter, bring your own laptop, so you can use your own familair IDE and operating system.</p><p>In most cases, you’ll be given some sort of public API and be required to work with it in some way.</p><p>This is done to see the way the candidate writes actual code, so here are some things to pay attention to:</p><p>A. Keep your code clean. Use indentation, provide meaningful variable names, remove unused code.</p><p>B. Use best practices of the given framework.</p><p>C. Think about things like:<br>1. Debounce requests sent to the server.<br>2. Prevent server calls when &lt; 3 characters are typed.<br>3. Take care of edge cases like missing information from the API.</p><p>D. Your CSS skills are important too! Be comfortable with using Flexbox (don’t use float to align containers 😉).</p><h3>Logic Questions</h3><p>I admit. I really dislike this type of question myself. I don’t understand how they can help anyone evaluate your value as a developer. But some companies still ask them…<br>You can’t <strong>really</strong> prepare for these ones (maybe read about some common questions?), but just know that they do exist.</p><p><strong>Example:</strong><br>You are standing in a room with three light switches. The switches all correspond to three different light bulbs in a nearby room that you cannot see into, but you can go in one time only. With all the light switches starting in the off position, how can you find out which switch connects to which light bulb?</p><h3>Talking About Yourself</h3><p>Last but not least, there’s a part where you need to talk about your past experience.</p><p>If you’re applying to your first job as a developer, make sure to have some project you’re passionate about or maybe contribute to some open-source library.</p><p>Be ready to discuss the nitty-gritty. For example, why did you choose library A instead of B?</p><p>If this isn’t your first rodeo, you will need to talk about a feature or product that you were responsible for at work. <strong>In details</strong>. The Interviewer would also likely want to hear about your personal contribution to the team.</p><p>You should practice this conversation with a friend so that you have feedback! It would be so much easier for you if you come prepared.</p><h3>And Most Importantly: A Failed Interview does NOT Define You!</h3><p>Remember, a failed interview doesn’t say anything about how good a developer you are. As I mentioned in the beginning, <strong>interviewing is a skill of its own</strong>. In your day-to-day life, you have StackOverflow and co-workers at your disposal, and you’re not expected to write code on a piece of paper. Interviews are simply not something you’re used to doing, so <strong>you need </strong>to try it a few times to grasp how it’s done. Prepare and study, but <strong>don’t be</strong> hard on yourself if you don’t pass. Try to <strong>learn something</strong> from each interview, and eventually, you <strong>will succeed</strong>!</p><p>Good luck! :)</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! <a href="https://www.youtube.com/channel/UC3v9kBR_ab4UHXXdknz8Fbg?sub_confirmation=1"><strong>Subscribe to our YouTube channel</strong></a> or join the <a href="https://skilled.dev/"><strong>Skilled.dev coding interview course</strong></a>.</p><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2f0f611c91e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-complete-guide-to-front-end-developer-interviews-e2f0f611c91e">The Complete Guide to Front-end Developer Interviews</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the difference between useMemo and useCallback]]></title>
            <link>https://levelup.gitconnected.com/understanding-the-difference-between-usememo-and-usecallback-ec956adb2004?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec956adb2004</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 09:58:23 GMT</pubDate>
            <atom:updated>2021-06-14T05:53:21.706Z</atom:updated>
            <content:encoded><![CDATA[<p>React library provides us two built-in hooks to optimize the performance of our app: useMemo &amp; useCallback. At first glance, it might look like their usage is quite similar, so it can get confusing about when to use each. To clear that confusion, let’s dig in and understand the actual difference and the correct way to use them both.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-oaiaaoisECxNABVxeVbcg.jpeg" /><figcaption>useMemo or useCallback?</figcaption></figure><h3>Functional components have a problem</h3><p>Functional components are great. Their combination with hooks allows for much more code reusability and flexibility than Class components. However, they do have one problem: A functional component is the same as the render function we used to have in class components. It’s a function that is being re-run on any prop/state change.</p><p><strong>It means that:</strong></p><p>A. If a function is called inside the component, it will be re-evaluated, again and again, on every re-render.</p><p>B. If a function is created inside the component is passed to a child component, it will be recreated, meaning the pointer will change, causing the child to re-render or call the function unnecessarily (depending on the situation).</p><p>To tackle the problem and prevent the possible performance issue, React provides us with two hooks: useMemo and useCallback.</p><h3>useMemo</h3><p>Let’s start with the first problem and see how we can prevent evaluating functions unnecessarily.</p><p>In the following demo, we have a component with two states: one store a number, and the other one a boolean.<br>We need to do some calculation on the number we have in our state, so we call our plusFive function and render the result.</p><pre><strong>const plusFive = (num) =&gt; {<br>  console.log(&quot;I was called!&quot;);<br>  return num + 5;<br>};</strong></pre><pre>export default function App() {<br><strong>  const [num, setNum] = useState(0);<br>  const [light, setLight] = useState(true);<br>  const numPlusFive = plusFive(num);</strong><br>  return (<br>  ...</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fg959e&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fg959e&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fg959e%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/a666fcf1eab972a6ff1068db2988cd47/href">https://medium.com/media/a666fcf1eab972a6ff1068db2988cd47/href</a></iframe><p>If you open the console, you’ll see that plusFive is called whether we click on “Update Number” which sets a new number, or “Toggle the light” which updates the boolean state (and has nothing to do with numPlusFive).</p><p>So how can we prevent this from happening? By memoizing plusFive ! <br>Until we will receive a new number, the function will not be called. The calculation is skipped, and we will receive the result immediately.</p><p>We will do that by using useMemo , and it will look like this:</p><pre>const numPlusFive = useMemo(() =&gt; plusFive(num), [num]);</pre><p>useMemo receives two parameters: A function that returns our function call, and an array of dependencies. Only when one of the dependencies is changed, our function will be called again. useMemo returns the results of that function execution and will store it in memory to prevent the function from running again if the same parameters were used.</p><p>Go ahead and see for yourself (don’t forget to open the console):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftsc89&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ftsc89&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ftsc89%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/e0aa7c0cd69e5ab1158ddb1c4c4057d7/href">https://medium.com/media/e0aa7c0cd69e5ab1158ddb1c4c4057d7/href</a></iframe><h3>useCallback</h3><p>Now that we know how to prevent re-evaluating functions, let’s see how we can prevent functions created inside components from being recreated on every render.</p><p>In the demo below, we have a child component (&lt;SomeComp&gt;) that receives as a prop, a function we created inside the parent component (&lt;App&gt;). Note this function is being used inside a useEffect hook, and since it’s listed as useEffect’s dependency, it’s being called again. Yes, even when we change other states or receive props, not related to our “plusFive” function.</p><pre>const App = () =&gt; {<br><strong>  const [num, setNum] = useState(0);<br>  const [light, setLight] = useState(true);<br>  const plusFive = () =&gt; {<br>    console.log(&quot;I was called!&quot;);<br>    return num + 5;<br>  };</strong><br>  return (<br>    &lt;div className={light ? &quot;light&quot; : &quot;dark&quot;}&gt;<br>      &lt;div&gt;<br>        <strong>&lt;SomeComp someFunc={plusFive} /&gt;</strong><br>  &lt;button onClick={() =&gt; { setLight(!light); }}&gt; Toggle the light &lt;/button&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>const SomeComp = ({ <strong>someFunc </strong>}) =&gt; {<br>  const [calcNum, setCalcNum] = useState(0);<br>  useEffect(() =&gt; {<br>    // In this scenatio, someFunc will change on every render, so this useEffect will run.<br>     <strong>setCalcNum(someFunc());</strong><br>  }, [<strong>someFunc</strong>]);</pre><pre>return &lt;span&gt; Plus five: {calcNum}&lt;/span&gt;;<br>};</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fh6x4m&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fh6x4m&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fh6x4m%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/a66cbba6fba31978291739f6c34a45df/href">https://medium.com/media/a66cbba6fba31978291739f6c34a45df/href</a></iframe><p>To prevent our function from being recreated and change pointers on each render round, we can use useCallback . This React hook receives two parameters: A function and an array of dependencies:</p><pre>const plusFive = useCallback(() =&gt; {<br>  console.log(&quot;I was called!&quot;);<br>  return num + 5;<br>}, [num]);</pre><p>This hook lets us preserve the function, and it will be recreated only when one of its dependencies changes.</p><p>Here’s the working demo:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fymhyy&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fymhyy&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fymhyy%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/103e227443c253f42b949aefb25bcec8/href">https://medium.com/media/103e227443c253f42b949aefb25bcec8/href</a></iframe><h3>But Wait! Don’t misuse these hooks!</h3><p>While these two hooks provide a solution to a real problem, they may get misused very easily and even cause more harm.</p><p>For instance, there is no need to memoize a function that’s doing some basic calculation (like in the demo). Only use useMemo whenver you’re trying to prevent re-running expensive functions, that run a lot of time, or using a lot of resources. Why? Because useMemo keeps in memory the results of the functions execusion, and it might potentially grow big and ironically harm the performance of your App.</p><p>With useCallback things might get even worse: when not using useCallback, your old function will be garbage collected, but with useCallback it will stay in memory, in case one of the dependencies will be right again to return that old function version.</p><p>So when is it right to use useCallback ? When you actually see that not using it harms your performance, or will result in an unneccery heavy function execution (imagine in the useCallback demo, that this function performs an API call, and not just adding numbers. This is something worth preventing).</p><h3>To summarise:</h3><p><strong>useMemo </strong>keeps a function from being executed again if it didn’t receive a set of parameters that were previously used. It returns the results of a function. Use it when you want to prevent some heavy or costly operations from being called on each render.</p><p><strong>useCallback </strong>keep a function from being re-created again, based on a list of dependencies. It returns the function itself. Use it when you want to propagate it to child components, and prevent from a costly function from re-running.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec956adb2004" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-the-difference-between-usememo-and-usecallback-ec956adb2004">Understanding the difference between useMemo and useCallback</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recoil — Another React State Management Library?]]></title>
            <link>https://medium.com/swlh/recoil-another-react-state-management-library-97fc979a8d2b?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/97fc979a8d2b</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[recoiljs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 15:04:43 GMT</pubDate>
            <atom:updated>2020-06-02T20:02:41.926Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recoil — Another React State Management Library?</h3><p>There are many React state management libraries, and new ones pop up from time to time. But it is not every day that Facebook themselves introduce a state management solution. Is it any good? Does it bring anything new to the table? Let’s dive in and see if it’s worth your time (spoiler: yes, it does).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SkjAGdVWYe4ja5Qu4DeJg.jpeg" /><figcaption>Recoil.js — A state management library by Facebook</figcaption></figure><p>It was quite something, watching Dave McCabe, A Facebook software engineer, introduce a new state management library during the online React Europe 2020 event on Youtube. <br>Sure, as of May 2020, <a href="https://github.com/facebookexperimental/Recoil">Recoil</a> is still experimental (though assumably used in production in some of Facebook’s inner tools), and not quite official, but it’s still interesting to see what led McCabe and his co-workers at Facebook to write this library, which is now open-sourced.</p><p>While working on one of their tools with a complex UI and trying to find the best solution for global state management, they hit a performance and efficiency wall. They decided that the best way would be to write their own library.</p><h3>What’s wrong with Redux or Mobx?</h3><p>There is nothing wrong with the existing libraries, to be frank. But the thing is, they are not React libraries. The store is something that is handled “externally”, hence doesn’t have access to React’s inner scheduler. Why is it important? For now, it isn’t. But <a href="https://medium.com/swlh/what-is-react-concurrent-mode-46989b5f15da">concurrent mode</a> is around the corner, and we can assume that Facebook software developers are using it already. For them, it was important to write a solution that will feel and act React and will be able to easily support concurrency (Recoil is using react state under the hood, and concurrency support should be added in the following weeks).</p><p>Also, some libraries (Redux..), while providing robust tools, come with a high cost — to set up even the most basic store, you need to write a lot of boilerplate and verbose code. Furthermore, important features such as dealing with async data, or caching computed selector values, are not part of the base library and require even more third-party libraries solutions. And if God forbid, a selector needs to receive a dynamic prop, memoizing this one correctly is a pain.</p><h3>What about Context API?</h3><p>Context API, the native React state sharing solution, also has its limitations.</p><p>When used for recurring or complex updates, it’s not that efficient. <a href="https://github.com/facebook/react/issues/14110#issuecomment-448074060">Quoting Sebastian Markbage</a>, another Facebook engineer:</p><blockquote>“My personal summary is that new context is ready to be used for low frequency unlikely updates (like locale/theme). It’s also good to use it in the same way as old context was used. I.e. for static values and then propagate updates through subscriptions.<strong> It’s not ready to be used as a replacement for all Flux-like state propagation.</strong>”</blockquote><p>Even the React-Redux team had to revert parts of the library re-written with context API in <a href="https://blog.isquaredsoftware.com/2018/11/react-redux-history-implementation/#v7-0">version 6</a>, simply due to a significant performance hit compared to its previous version (Now React-Redux only uses context to pass down the store reference).</p><p>Let’s picture the following scenario. Say, we are rendering a master-detail view with a list of image components and a metadata info component. On an image click, its metadata should be displayed in the info component. We also want the ability to rename the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*jd9hhCED1hosJyjFTUev4A.png" /></figure><p>Upon rename, the best outcome would be if we could re-render just the selected image component and the metadata component.</p><p>Context API would not make it easy for us to achieve.</p><p>For starters, context API doesn’t let you subscribe to a subset of the data it contains.</p><blockquote>All consumers that are descendants of a Provider will re-render whenever the Provider’s <em>value</em> prop changes. (<a href="https://reactjs.org/docs/context.html#before-you-use-context">https://reactjs.org/docs/context.html#before-you-use-context</a>)</blockquote><p>If our provider’s value is an array or an object, changing any bit of this structure will cause <strong>everything</strong> subscribed to that context to re-render, even if your component uses just a part of that value. See <a href="https://codesandbox.io/s/global-state-using-react-context-only-gbipb">this demo</a> by <a href="https://github.com/fjcalzado">Javier Calzado</a>. This means we can’t store all images in a single context, since renaming one will cause everything to re-render (and, sure we can memoize, but it’s not a magic solution and comes with its own limitations).</p><p>So let’s say each image will have its own context. There is nothing wrong with that, as long as we know the exact number of images. But what if it is dynamic, and we can add more? We will have to add a Context Provider for each new image, re-shaping the components tree, <strong>causing the entire sub-tree to re-mount</strong>, which is even worse.<strong> </strong>See the GIF below for a visual representation of the issue:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*9fEPTka4XmZFrtp2HQNtYg.gif" /><figcaption>Adding a provider dynamically causes the entire sub-tree to re-mount</figcaption></figure><p>See how pushing this Context Provider in slide 3 causes everything underneeth to remount?</p><p>In addition to not being performant, it introduces tight coupling between the provider and the leaves of the tree.</p><h3>What does Recoil do differently?</h3><p>First of all, Recoil is very easy to learn. Its API is very simple and feels natural to people who are already accustomed to using hooks. Getting started is a matter of wrapping your app with RecoilRoot , declaring your data with a unit called atom and replacing useState with Recoil’s useRecoilState.</p><p>Secondly, it allows you to subscribe to the exact piece of data your component consumes, declare computed selectors, and it even provides a built-in solution for async data flow.</p><p>Creating atoms on the fly with dynamic keys, sending arguments to the selectors, and so on, is also easy peasy (lemon squeezy).</p><p>As for support for React concurrent mode, as said earlier, it’s a matter of weeks.</p><h3>Let’s begin with Recoil’s basics</h3><p><strong>Atom</strong> — An atom is simply put, a piece of state. Think of it like a regular react state, but one that any component can subscribe to. Changing the value of an atom will result in a re-render from all components subscribed to it.</p><p>To create an atom we need to provide a key, which should be unique across the application and a default value. The default value can be a static value, a function or even an async function (but on that later).</p><pre><em>export const</em> nameState = atom({<br>  key: &#39;nameState&#39;,<em><br>  default</em>: &#39;Jane Doe&#39;<em><br></em>});</pre><p><strong>useRecoilState</strong> — A hook that lets you subscribe to an atom’s value, and update it. Used the same way as you would with useState</p><p><strong>useRecoilValue</strong> — Returns just the value of the atom, without the setter function.</p><p><strong>useSetRecoilState </strong>— Returns just the setter function.</p><pre>import {nameState} from &#39;./someplace&#39;</pre><pre>// <strong>useRecoilState</strong><br>const NameInput = () =&gt; {<br>  <em>const</em> [name, setName] = useRecoilState(nameState);<br>  <em>const</em> onChange = (event) =&gt; {<br>   setName(event.target.value);<br>  };<br>  return &lt;&gt;<br>   &lt;input type=&quot;text&quot; value={name} onChange={onChange} /&gt;<br>   &lt;div&gt;Name: {name}&lt;/div&gt;<br>  &lt;/&gt;;<br>}</pre><pre>// <strong>useRecoilValue</strong><br>const SomeOtherComponentWithName = () =&gt; {<br>  <em>const</em> name = useRecoilValue(nameState);<br>  return &lt;div&gt;{name}&lt;/div&gt;;<br>}</pre><pre>// <strong>useSetRecoilState  <br></strong>const SomeOtherComponentThatSetsName = () =&gt; {<br>  <em>const</em> setName = useSetRecoilState(nameState);<br>  return &lt;button onClick={() =&gt; setName(&#39;Jon Doe&#39;)}&gt;Set Name&lt;/button&gt;;<br>}</pre><p><strong>selector </strong>— A selector represents a piece of derived state. It lets us build dynamic data that depends on other atoms. A selector in Recoil is a little different than what you would expect from the word “selector”. It has a mandatory “get” function which acts the same way as reselect with redux or @computed with MobX. But it can optionally accept a “set” function that can update one or more other atoms. We’ll tackle this part later, so for now let’s have a look only on the “selector” part.</p><pre><strong>// Animals list state<br></strong><em>const</em> animalsState = atom({<br>  key: &#39;animalsState&#39;,<br>  <em>default</em>: [{<br>    name: &#39;Rexy&#39;,<br>    type: &#39;Dog&#39;<br>  }, {<br>    name: &#39;Oscar&#39;,<br>    type: &#39;Cat&#39;<br>  }],<br>});</pre><pre><strong>// Animals filter state</strong><br>const animalFilterState = atom({<br> key: &#39;animalFilterState&#39;,<br> default: &#39;dog&#39;,<br>});</pre><pre><strong>// Derived filtered animals list</strong><br>const filteredAnimalsState = selector({<br> key: &#39;animalListState&#39;,<br> get: ({get}) =&gt; {<br>   const filter = get(animalFilterState);<br>   const animals = get(animalsState);<br>   <br>   return animals.filter(animal =&gt; animal.type === filter);<br> }<br>});</pre><pre><strong>// Component that consumes the filtered animals list<br></strong>const Animals = () =&gt; {<br>  const animals = useRecoilValue(filteredAnimalsState);<br>  return animals.map(animal =&gt; (&lt;div&gt;{ animal.name }, { animal.type    }&lt;/div&gt;));<br>}</pre><p><strong>Here’s a working demo:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fhik7u&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fhik7u&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fhik7u%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/99d4d5ccae2dcfa0c8d3686339b673ec/href">https://medium.com/media/99d4d5ccae2dcfa0c8d3686339b673ec/href</a></iframe><p>Pretty simple, isn’t it?</p><h3>Now let’s complicate stuff!</h3><p>Ok, so now let’s get back to the images app I was talking about earlier, and implement it with Recoil:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*jd9hhCED1hosJyjFTUev4A.png" /></figure><p><strong>The requirements for that app are:<br></strong>1. We should have the ability to add images dynamically,<br>2. When renaming, only the selected image and the metadata components should re-render,<br>3. Images and their data are loaded asynchronously.</p><p>To achieve the first two requirements, we are going to store each image in its own atom. For that purpose, we can use atomFamily</p><p><strong>atomFamily</strong> is the same as a regular atom, only it can receive a parameter differentiates one instance from another. These two are basically the same:</p><pre>// atom<br>const itemWithId = memoize(id =&gt; atom({<br>  key: `item-${id}`,<br>  default: ...<br>}))</pre><pre>//atomFamily<br>const itemWithId = atomFamily({<br>  key: &#39;item&#39;,<br>  default: ...<br>});</pre><p>The only differences are that atomFamily will do the memoization for you, and you don’t have to create a unique key for each instance, as again, it’s being done for you.</p><p>atom and atomFamily can also call another function to create their default. And same here, the only difference here is that atomFamily can pass over its received id.</p><pre>export const imageState = atomFamily({<br>  key: &quot;imageState&quot;,<br>  default: id =&gt; getImage(id)<br>});</pre><p><strong>The first time any component will call </strong><strong>imageState with that id, it will initiate the function call to create a default.</strong></p><p>This function can also be <strong>asynchronous</strong>, and Recoil will handle it for us, with some help from React’s Suspense</p><p>The store’s code:</p><pre>const getImage = async id =&gt; {<br>  return new Promise(resolve =&gt; {<br>    const url = `http://someplace.com<a href="https://res.cloudinary.com/dqsubx7oc/image/upload/w_149,h_104/g_auto/recoil-demo/$%7Bid%7D.png%60">/${id}.png`</a>;<br>    let image = new Image();<br>    image.onload = () =&gt;<br>      resolve({<br>        id,<br>        name: `Image ${id}`,<br>        url,<br>        metadata: {<br>          width: `${image.width}px`,<br>          height: `${image.height}px`<br>        }<br>      });<br>    image.src = url;<br>  });<br>};</pre><pre>export const imageState = atomFamily({<br>  key: &quot;imageState&quot;,<br>  default: async id =&gt; getImage(id)<br>});</pre><p>The components:</p><pre>// Images list<br>const Images = () =&gt; {<br>  const imageList = useRecoilValue(imageListState);<br>  return (<br>    &lt;div className=&quot;images&quot;&gt;<br>      {imageList.map(id =&gt; (<br>        &lt;Suspense key={id} fallback=&quot;Loading...&quot;&gt;<br>          &lt;Image id={id} /&gt;<br>        &lt;/Suspense&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>// Single image<br>const Image = ({ id }) =&gt; {<br>  const { name, url } = useRecoilValue(imageState(id));<br>  return (<br>    &lt;div className=&quot;image&quot;&gt;<br>      &lt;div className=&quot;name&quot;&gt;{name}&lt;/div&gt;<br>      &lt;img src={url} alt={name} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p><strong>Demo with the full code:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Ftmc9k&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Ftmc9k&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Ftmc9k%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/2dd316e13da94b20d30b88f5814fcc98/href">https://medium.com/media/2dd316e13da94b20d30b88f5814fcc98/href</a></iframe><h3>Before we’re done, Selectors can SET data? WHAT?</h3><p>When I talked about selectors I mentioned the fact that we pass a set function to a selector. This is weird, but just because the name is conffusing (and hopefuly, will change). Think of selectors like a state, but a derived one. It can get computed values from atoms, and affect multiple atoms as well.</p><p>In this example, the selector returns a derived state: A counter object of boxes with a certain color. <br>It’s setter function can affect all boxes from the box atomFamily and reset them:</p><pre>const colorCounterState = selector({<br>  key: &quot;colorCounterState&quot;,<br>  get: ({ get }) =&gt; {<br>    let counter = { [COLORS.RED]: 0, [COLORS.BLUE]: 0, [COLORS.WHITE]: 0 };<br>    for (let i = 0; i &lt; BOX_NUM; i++) {<br>      const box = get(boxState(i));<br>      counter[box] = counter[box] + 1;<br>    }<br>    return counter;<br>  },<br>  set: ({ set }) =&gt; {<br>    for (let i = 0; i &lt; BOX_NUM; i++) {<br>      set(boxState(i), COLORS.WHITE);<br>    }<br>  }<br>});</pre><p><strong>A full working demo:</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F082nu&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F082nu&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F082nu%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/c217e1c7f094396edfbc32f687f3690a/href">https://medium.com/media/c217e1c7f094396edfbc32f687f3690a/href</a></iframe><p>Obviously Recoil has many other neat features stored inside, but this at least should get you started.</p><h3>To summarize, is Recoil worth your time?</h3><p>We can always ask ourselves “Do we really need another state management library”? And my answer would be: YES!</p><p>Why? Because having a state management library that acts and feels like React is refreshing. It means the learning curve is minimal if you ever worked with hooks before. No need to learn new syntax or set tons of boilerplate code to get you going (and I’m aware the selectors get/set syntax is a bit weird, but it really is simple).</p><p>It also takes a lot of pain away when it provides solutions to handle async data, state persistency, and parameterized selectors from day one.</p><p>I obviously can’t tell you yet how this library scales on large projects, or if it even gets attention and not die, but I sure hope it will get more popular. We can only benefit from that.</p><h3>Extra reading</h3><ul><li><a href="https://recoiljs.org/docs">Recoil documentation</a></li><li><a href="https://www.youtube.com/watch?v=_ISAA_Jt9kI">Recoil: State Management for Today’s React — Dave McCabe at @ReactEurope 2020</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97fc979a8d2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/recoil-another-react-state-management-library-97fc979a8d2b">Recoil — Another React State Management Library?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is React Concurrent Mode?]]></title>
            <link>https://medium.com/swlh/what-is-react-concurrent-mode-46989b5f15da?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/46989b5f15da</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Fri, 03 Apr 2020 14:18:47 GMT</pubDate>
            <atom:updated>2020-04-05T06:45:54.058Z</atom:updated>
            <content:encoded><![CDATA[<p>For the past three years, the React core team has been working on a major feature that is going to significantly affect both user experience and development process: Concurrent Mode. While work is still in progress and most of its parts are not official yet, let’s dive in and see what awaits us in the near future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m2FjcoGVUGbBGNuwbFX_eg.jpeg" /><figcaption>What is React Concurrent Mode?</figcaption></figure><h3>First, What Does “Concurrency” Even Mean?</h3><p>As you probably know, Javascript is a single-threaded language. Each task you run blocks the thread from executing the next one until it’s done. However, it doesn’t mean we can’t make progress on more than one task at the same time. Confused? Let me try and explain it using a real-life example.</p><p>Say you’re a morning person and can’t start the day without a cup of tea and a raspberry jam spread toast.</p><p>If we go on with what we said earlier, it will mean we have to make the tea, and only when it’s done, prepare the toast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*qUkI3G9-AlNcAaKsNZG-bA.jpeg" /><figcaption>Tea-&gt;Toast</figcaption></figure><p>But it’s not very smart, is it? We do want that tea hot in the end.</p><p>So to be efficient and get both tea and toast hot and fresh, we should instead break both tasks into smaller micro-tasks, and reorder them as we see fit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hu7IAEhS-mOp2bcvLBMpiQ.jpeg" /><figcaption>Concurrency IRL</figcaption></figure><p>Tada! While being a single person handling 2 different tasks, we were able to make progress on two tasks “at the same time”.</p><p><strong>So what is Concurrency? It is a way to structure a program by breaking it into pieces that can be executed independently. This is how we can break the limits of using a single thread, and make our application more efficient.</strong></p><p>So now that we know the definition, let’s take a look at what this has to do with React.</p><h3>It’s All About Perfecting the User Experience</h3><p>The browser’s UI thread is responsible for applying all the changes initiated by CSS, User input and Javascript to the user’s screen. On modern machines, to provide the best user experience, we are expected to render 60 frames per second (fps). To achieve that, for each render cycle our code should run for no more than 16.67 milliseconds, and realistically even less: somewhere around 10 ms (since, as said previously, the browser has also to deal with other UI tasks).</p><p>React is javascript and thus bound by the same limits. Up until now, once React started the reconciliation phase, it could no longer be stopped until it’s done. The browser’s main UI thread would then be unable to execute any other tasks, such as receiving user input. Even if React’s reconciliation algorithm is amazingly efficient — when a web application grows big and its dom tree grows, it’s easy to understand how causing frame drops which lead to <a href="https://developer.mozilla.org/en-US/docs/Glossary/Jank">jank</a> or even unresponsive applications is a common problem.</p><p>Here’s a working example of an app that renders a grid of 100X100 randomly colored pixels on every keypress. Try typing something down:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F4nd67&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F4nd67&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F4nd67%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/292f97cf9eb0d89ed9c75608f0ea00de/href">https://medium.com/media/292f97cf9eb0d89ed9c75608f0ea00de/href</a></iframe><p>Annoying, isn’t it? It might be a bit of an exaggeration, rendering 10,000 dom nodes, but it’s just a quick way to demonstrate the problem.</p><p>And while most developers will use techniques, such as memoization and debounce, to make the experience feel better, they will just delay the main problem:<strong> rendering is still a truck blocking the road</strong>.</p><p>But improving user experience is not all about fixing performance problems, but also thinking about what users will consider a <strong>better</strong> experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*pqB6QmwTTQtrKaLAoG4eDQ.jpeg" /></figure><p>Spinners, skeletons, placeholders — you can’t run away from them whether you have a high-end machine or a low budget phone. While they provide a good indication that something is going on, when you put too many of them together or show them unnecessarily, it degrades the experience instead of improving it. If the data can load fast enough on your machine, why do you have to see these spinners in the first place? Wouldn’t it be a nicer experience to let you wait for an extra second and move you right on to a fully rendered and ready page?</p><h3>Interpretive Rendering To the Rescue</h3><p>Remember what I told you about how concurrency is all about breaking tasks to smaller pieces, which allows us to progress on multiple tasks? This is exactly what React now does: the rendering process is being broken down into smaller tasks, and a scheduler allows us to even prioritize them based on importance (also called “time-slicing”). This lets Concurrent React:</p><ul><li>Not to block the main thread;</li><li>To work on multiple tasks at a time and switch between them according to priority;</li><li>To partially render a tree without committing the result.</li></ul><p>The rendering process is no longer blocking the thread, it’s <strong>interpretative </strong>and can be put aside if something of higher importance comes along, such as a user pressing a key.</p><p>If you’re interested in the nitty-gritty and how does React Fiber (the new reconciliation algorithm) does that, I highly recommend you to watch <a href="https://www.youtube.com/watch?v=ZCuYPiUIONs">this video</a> by Lin Clark.</p><p><strong>So now let’s put the theory in use, with some of the concurrent mode’s new features!</strong></p><p>But a quick note before that: as said, the following features are not yet part of the official React library. They might change in the future, so it’s not advised to use them in production. Also, to enable them you’ll need to:</p><p>A. Use the ‘experimental’ package of react and react-dom.<br>B. Change your initial render call to:</p><pre><em>// Concurrent Mode<br></em>const rootElement = document.getElementById(&quot;root&quot;);<br>ReactDOM.createRoot(rootElement).render(&lt;App /&gt;);</pre><h3>useDeferredValue</h3><p>Remember the demo from earlier, where the UI would get stuck on every keypress? To fix the user experience, we need a way to prioritize user inputs, and only then care about rendering the huge grid. Luckily we now have a way to do so: <strong>useDeferredValue</strong>.</p><p><strong>useDeferredValue </strong>is a hook that wraps a prop/state value and receives the maximum defer time. This lets us tell React: “It’s ok for components depending on this value to be rendered at a later time”.</p><pre>import { useState, useDeferredValue } from &#39;react&#39;;</pre><pre>const [value, setValue] = useState(&#39;&#39;);<br>const deferredValue = useDeferredValue(value, {<br>  timeoutMs: 5000<br>});</pre><p>Note that this functionality <strong>does not</strong> debounce the render! React will still render the components “on the side”, and, if ready before the provided time, it will flush the changes to the DOM.</p><p><strong>Note: </strong>Using this feature might cause an inconsistency in the view since we’re prioritizing showing one piece of the UI over the other.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F8l52r&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F8l52r&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F8l52r%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/e8155dc5210d36271b2df5c0bda8f5c6/href">https://medium.com/media/e8155dc5210d36271b2df5c0bda8f5c6/href</a></iframe><h3>Suspense for Data Fetching</h3><p>Another awesome new feature (and the one I’m personally most excited about) is Suspense for data fetching. If you’re familiar with React’s newest features, you might already know about Suspense for data fetching, which comes hand to hand with React.lazy introduced in version 16.8. Suspense allows us to show a placeholder while waiting for a code split part of our application.</p><p>Suspense for Data fetching has the same idea behind it, but it works on basically anything using promises.</p><pre>import Spinner from &#39;./Spinner&#39;;</pre><pre>&lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>   &lt;SomeComponent /&gt;<br>&lt;/Suspense&gt;</pre><p>To see how powerful it is, let’s look at a simple application without Suspense:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F19591&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F19591&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F19591%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/34c8cfe3e49e3e488234b624e6eecef0/href">https://medium.com/media/34c8cfe3e49e3e488234b624e6eecef0/href</a></iframe><p>This application loads a list of tv shows. When pressing on a tv show, it’ll load a details page with a comments section.</p><pre>const [tvData, setTvData] = useState(null);</pre><pre>useEffect(()=&gt;{<br>   setTvData(null);<br>   tvDataApi(id).then(value =&gt;{<br>     setTvData(value);<br>   })<br>}, [id]);</pre><pre>if (tvData === null) return &lt;Spinner /&gt;;</pre><pre>return &lt;div className=&quot;tvshow-details&quot;&gt;<br>  &lt;div className=&quot;flex&quot;&gt;<br>   &lt;div&gt;<br>     &lt;h2&gt;{tvData.name}&lt;/h2&gt;<br>     &lt;div className=&quot;details&quot;&gt;{tvData.description}&lt;/div&gt;<br>    &lt;/div&gt;<br>   &lt;div&gt;<br>     &lt;img src={`${id}.jpg`} alt={tvData.name} /&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>  {/* comments section */<br>  &lt;Comments id={id} /&gt;<br>&lt;/div&gt;</pre><p>If we look closely at the way we load the data here, we can see that:<br>A. There’s currently no unified way to display a placeholder while the data is loading. Each developer has to implement it for himself.<br>B. We create a waterfall of API calls since we can only render the comments component when details are ready and rendered. There are other ways to handle this of course, but none are simple or intuitive.</p><p>Suspense solves both since it now provides a simple syntax for displaying placeholders. Also, using the concurrent mode features, it can actually start rendering the component on the side, thus initiating the API calls, and show the placeholder in the meanwhile. This is a huge feature which takes away a lot of pain when working with data.</p><pre>export const TvShowDetails = ({ id }) =&gt; {<br>  return (<br>   &lt;div className=&quot;tvshow-details&quot;&gt;<br>      &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>          &lt;Details id={id} /&gt;<br>          &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>             &lt;Comments id={id} /&gt;<br>          &lt;/Suspense&gt;<br>      &lt;/Suspense&gt;<br>   &lt;/div&gt;<br>  );<br>};</pre><p>To work with Suspense for data fetching, we need to wrap our promises with a function (see wrapPromise in the demo below), which returns different values based on what Suspense is expecting on each step of the process. The React team is working on a library called react-cache, which will provide this function, but nothing is final yet.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fqdquy&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fqdquy&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fqdquy%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/9b9184f74fed17dd862aae00ddd88627/href">https://medium.com/media/9b9184f74fed17dd862aae00ddd88627/href</a></iframe><p>Anyhow, using this syntax simplifies our component. We can dropuseEffect and no longer worry about what will happen if the data is not ready. We can treat the component as if the data is there, and let Suspense do the rest.</p><pre>const detailsData = detailsResource(id).read();</pre><pre>return &lt;div&gt;{detailsData.name} | {detailsData.score}&lt;/div&gt;</pre><p>But now we are facing another problem. What if the API call inside the comments component finishes first? It would look weird to show it first, right? Thankfully, we now have a way to coordinate the view order of components using Suspense.</p><h3>SuspenseList</h3><p>SuspenseList is a component we can wrap other Suspense components with. it receives two props: revealOrder and an optional tail prop, with which we can tell react the order to display the child Suspense wrapped components (See the <a href="https://reactjs.org/docs/concurrent-mode-reference.html#suspenselist">documentation</a> for all the options).</p><pre>const [id, setId] = useState(1);</pre><pre>&lt;SuspenseList revealOrder=&quot;forwards&quot;&gt;<br>  &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>    &lt;Details id={id} /&gt;<br>  &lt;/Suspense&gt;<br>  &lt;Suspense fallback={&lt;Spinner /&gt;}&gt;<br>    &lt;Comments id={id} /&gt;<br>  &lt;/Suspense&gt;<br>&lt;/SuspenseList&gt;</pre><p>Note that it has nothing to do with rendering or API order call, it simply tells react when to display a loaded component.</p><h3>useTransition</h3><p>We previously talked about spinners, and how a better experience would be to maybe not display them at all, for users with a fast internet connection.</p><p>We can now do that with a new hook called <strong>useTransition. <br>useTransition </strong>lets us wait for the data to be ready before flushing the dom, so basically we see nothing until the change actually happens. It receives the amount of time we want to wait before falling back to a spinner or some other fallback component.<br> <br>It also returns two things:</p><p>startTransition — A function that tells React <em>which</em> state update we want to defer.</p><p>isPending — A boolean which tells us if a transition is ongoing at the moment.</p><pre>const [id, setId] = useState(1);</pre><pre>const [startTransition, isPending] = useTransition({ timeoutMs: 3000 });</pre><pre>const onClick = id =&gt; {<br>  startTransition(() =&gt; {<br>    setId(id);<br>  });<br>};</pre><p>Naturally, using this hook comes hand-to-hand with using Suspense for data fetching.</p><p>See the demo here:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fxz6nc&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fxz6nc&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fxz6nc%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/c0fbee84c34754e3f0e4f104719ce050/href">https://medium.com/media/c0fbee84c34754e3f0e4f104719ce050/href</a></iframe><p>As you can see, React’s concurrent mode is packed with awesome features which both takes away the headache of common use-cases, and also lets us create a better user experience for our users. There is no official release date, but hopefully, we won’t have to wait too long!</p><h3>Some extra reading:</h3><ul><li><a href="https://reactjs.org/docs/concurrent-mode-intro.html">Introducing Concurrent Mode</a></li><li><a href="https://www.youtube.com/watch?v=ByBPyMBTzM0">Concurrent Rendering in React — Andrew Clark and Brian Vaughn — React Conf 2018</a></li><li><a href="https://indepth.dev/inside-fiber-in-depth-overview-of-the-new-reconciliation-algorithm-in-react/">A dive down to React Fiber Architecture</a></li><li><a href="https://github.com/facebook/react/issues/7942?source=post_page---------------------------">Fiber Principles</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46989b5f15da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/what-is-react-concurrent-mode-46989b5f15da">What is React Concurrent Mode?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Web Accessibility is Far More Important Than You Think]]></title>
            <link>https://medium.com/swlh/why-web-accessibility-is-far-more-important-than-you-think-831d9bfdf9af?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/831d9bfdf9af</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[wcag]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Sun, 02 Jun 2019 19:08:25 GMT</pubDate>
            <atom:updated>2019-06-04T07:17:16.239Z</atom:updated>
            <content:encoded><![CDATA[<p>Web Accessibility is a relatively new topic web developers and commercial websites have to tackle. It takes effort and might even be a costly process, but the advantages of a web-accessible page are far greater than you would think (and not just because it’s the morally right thing to do, or because of accessibility laws). Let’s dig into these benefits and also learn some ways to make your website a better place to visit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r6Gsvcw8pDmAL5KvZkartA.jpeg" /><figcaption>Web Accessibility</figcaption></figure><p>The first time I came face to face with <strong>web accessibility</strong> was a few years ago, when I was working for a SaaS company called Webcollage, which provided a rich content distribution solutions for vendors. I returned to the office from a nice summer vacation in Europe and thought I was going to have a quiet “the day after a vacation” day, just sorting my inbox and catching up. Boy was I wrong. Apparently, the day before, one of the company’s major partners sent a requirement to now make our product accessible. This partner was kind enough to provide a list of 98 accessibility issues we had to fix in order to meet the required standard.</p><p>And let me tell you, this was not easy. The real problem is that web accessibility is a huge topic. And since, as said, it’s relatively new, most of the time the issues you stumble upon are not something you can find a solution to on Stack Overflow. The longer you dig into it, you figure out just HOW MANY people it actually affects, how there are disabilities you never even thought about.</p><h3>So how many people can’t use your site?</h3><p>When ignoring web accessibility you’re potentially alienating <strong>one billion</strong> people, or <strong>15% of the world’s population</strong>, who experience some form of disability, whether auditory, cognitive, neurological, physical or visual. This includes your grandparents who no longer can read the tiny font your site use or maybe hear the video’s audio. Maybe a girl who went on a ski trip, broke her arm, and now can’t use a mouse for a month. Even a perfectly healthy guy watching a video in the subway could use accessibility aid. Let’s say the train is so loud, he can’t hear your video properly (or maybe he forgot his headphones, so being polite he’s watching the video on mute).</p><p>By making your site accessible, you automatically <strong>increase the target audience</strong> and add new groups for which it did not provide any service before. Subsequently, you get <strong>increased traffic </strong>and thus <strong>the number of conversions increases</strong> as well.</p><p>Moreover, making these adjustments usually means it makes the site simpler and easier to use for the general public as well. As a result, users often tend to make more extensive use of the site, which leads to more conversions.</p><p>It can even make search engines robots happier! A simpler, better-structured site means search engines will treat your site better as they can get more information. Better SEO means more traffic from search engines, and again -&gt; More users -&gt; More conversions.</p><h3>So why don’t all websites just fix their code?</h3><p>As my teammates and I experienced first hand, we had to re-learn how to build certain parts of our product to make them fit the Web Content Accessibility Guidelines (WCAG). We also, for the first time, experienced assistive tools in order to test the new accessibility features more authentically (And trust me, when you hear the screen reader yell the 350 characters of an image URL because it didn’t find a description parameter on the image, you start to understand what a cluttered mess a typical website might feel like for a visually impaired person).</p><p>Also, remember that fixing the product isn’t enough. We now had to take accessibility into account for <strong>each </strong>new feature, which takes more development time for us and added time for the QA team to test it.</p><p>Making a site accessible, like everything else, has a price. It requires substantial changes in the structure of the site, from all aspects — design, programming, and even content. This means many hours of work, which cost money. And in the commercial market, people are in no hurry to spend time and money to change “what’s already working when no one’s complaining”.</p><p>And while more and more countries are adding laws to ensure the web is a nicer place to <strong>all people, </strong>even if there is no such law in your country, you might consider the benefits stated above, even if it appears costly at first.</p><h3>Where do I begin?</h3><p>So let’s say you want to add accessibility aid to your site. “Where do I begin?”, you’re probably asking. First, there are tools online that can analyze your website for accessibility issues, such as <a href="https://wave.webaim.org/">this one</a>. Also, there’s an official guideline I mentioned before called “Web Content Accessibility Guidelines” or in short “<strong>WCAG</strong>”, which you access from <a href="https://www.w3.org/WAI/WCAG21/quickref/">here</a>. It categorizes the requirements into 3 levels, ranging from A — the lowest to AAA the strictest and most accessible. While it’s quite informative, it doesn’t always provide code examples, so sometimes you’ll have to figure it out.</p><p>However, here are some points to get you started:</p><ol><li><strong>Add Closed Captions to your videos</strong> — Is there a narration or people talking in your videos? Provide a closed caption file to complement the spoken text.</li><li><strong>Never ever use &lt;table&gt; tags for anything else then, well, tables </strong>— If you need to show a comparison between data, then sure, go ahead (but <a href="https://www.w3.org/WAI/tutorials/tables/">read how to</a> implement tables correctly to make it easier for screen readers to read the data off it).<br>This is obviously the correct practice anyhow (for years now…), so then again, if you did put things into tables just out of convenience, now you’ll have the chance to do things right!</li><li><strong>Use headers correctly</strong> — There’s a reason why there are 6 different header tags! While it doesn’t really matter for the average user, it’s really important for screen readers. When used correctly, the screen reader will be able to easily map interest spots in the page for the user. (And it’s also better for SEO!)</li><li><strong>Tab navigation </strong>— Some users can’t use a mouse, such as the visually impaired, or people with motoric disabilities. Make sure your site can be navigated using the Tab key, and links and buttons activated using the Enter keys. Also, active elements should be marked using a distinct color outline. Modern browsers do it for you (for the most part), but sometimes developers disable this CSS style because it appears on any focus event.</li><li><strong>Add an “alt” parameter to images</strong> — If you don’t explain what’s in the image, visually impaired people have no way of telling what information you’re trying to convey. Some images are fine with an empty alt, depending on the situation, but please add it to all of your images nonetheless (Use <a href="https://webaim.org/techniques/alttext/">this guide</a> to help you out). What happens to images without an “alt”? The screen reader will read the image’s URL instead. NOT FUN.</li><li><strong>Present a way to quickly pause videos and animations </strong>— People with Epilepsy need a fast way to close any moving animation/video that pops up to the screen. For example, if you trigger an overlay with a video, add an option to close it with the ESC key.</li><li><strong>Make sure the color contrast between a text and its background is high enough — </strong>Don’t put pink text over a red background element. It’s actually an inconvenience even for people with perfectly fine eyesight but for people with a visual disability its a real struggle. You can check the color contrast rate using <a href="https://webaim.org/resources/contrastchecker/">this tool</a>.</li><li><strong>Use buttons, not divs that simulate buttons</strong> — There’s really no real reason not to use a button when you need a button (other than it takes a few more styles to make it look the way you want). But if you do, please make sure that:<br>A. You use an aria attribute to state that this div is used as a button (role=” button”)<br>B. Make sure you can activate it using key presses, and not just mouse clicks.</li><li><strong>Learn about Aria attributes</strong>—Aria attributes are part of the Accessibility API available in all modern browsers, which allow assistive technologies to better understand the elements that reside in your page. For example, do you need to inform the user that an error occurred? Without the correct aria attribute, a screen reader won’t be able to detect that a new message popped up.</li><li><strong>Can color blind users see your images clearly?</strong> — It’s a bad idea to put text and numbers in images, which are the main cause of problems for people with color blindness. However, if you do, and you want to understand the problematic parts of the image, or even provide an alternative image (with no effort!), you can use <a href="https://cloudinary.com/documentation/image_transformations#colorblind_accessibility_effects">some out of the box tools</a>, from an asset management company called Cloudinary (Disclaimer: I work there! :)).</li></ol><p>To conclude, making your site accessible is not a simple task. It takes some thought, time and even money. However, your benefit from it is far greater than it looks on a first glance. Take your time, but do this change, to make the web a better place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=831d9bfdf9af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/why-web-accessibility-is-far-more-important-than-you-think-831d9bfdf9af">Why Web Accessibility is Far More Important Than You Think</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your Content Look More Interesting With CSS Shapes]]></title>
            <link>https://sveta-slepner.medium.com/css-shapes-website-layouts-re-imagined-250ae1fd340?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/250ae1fd340</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[css3]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[css-shapes]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Sat, 30 Mar 2019 20:03:14 GMT</pubDate>
            <atom:updated>2019-03-30T20:34:17.559Z</atom:updated>
            <content:encoded><![CDATA[<p>For the longest time newspapers, magazines and books had one advantage over content designed for websites. It’s rather a small feature, but one that makes content look so much better — the ability to wrap text around images and shapes other than a rectangle. But fear not, because with the help of a CSS feature called ‘CSS shapes’, you can now achieve that as well!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3rZaL8kLQJtdvN9LjwXZdw.jpeg" /></figure><p>Since the beginning of the internet, we were trained to see our web sites as a collection of boxes. Even when we got a native CSS solution for creating circles, triangles and even trapeze and stars (either by using CSS tricks or by the modern <strong>clip-path </strong>property) these were all a mere illusion, since they’re still part of a box. As you can see in the example below, I’ve create a floating circle, which is basically just a div with a border radius — alas, the content still wraps itself around the circle’s <strong>box </strong>container:</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fd6rtfh5y%2Fembedded%2Fresult%2Ccss%2Chtml%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fd6rtfh5y%2Fembedded%2Fresult%2Ccss%2Chtml%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5f7d8d775627a207bd38a6627c5b47f/href">https://medium.com/media/d5f7d8d775627a207bd38a6627c5b47f/href</a></iframe><p>However, thanks to <strong>CSS shapes</strong>, we have the power to break this limit and make browsers wrap text around any crazy shape that comes to mind.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fyqnrgeod%2Fembedded%2Fresult%2Ccss%2Chtml%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fyqnrgeod%2Fembedded%2Fresult%2Ccss%2Chtml%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e933d6d1b93c3e5985b845830dc2d25/href">https://medium.com/media/9e933d6d1b93c3e5985b845830dc2d25/href</a></iframe><p>Circles, ellipses, complex polygons, you name it. We can even use images with transparent backgrounds and get the same effect!</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fdpq6uon8%2Fembedded%2Fresult%2Ccss%2Chtml&amp;src=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fdpq6uon8%2Fembedded%2Fresult%2Ccss%2Chtml&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7021470c3957da75c5aac9a96089c352/href">https://medium.com/media/7021470c3957da75c5aac9a96089c352/href</a></iframe><h3>Now we’ve seen it in action, how does CSS shapes work?</h3><p>CSS shapes is a set of rules for wrapping content around custom shapes and path. <strong>It does not actually draw the shape</strong>, but rather gives instructions to the browser on what the float area looks like (We can still draw the shape using the <strong>clip-path</strong> CSS property, this feature just isn’t part of CSS Shapes). Currently it only works when paired with a <strong>float </strong>property (in the future, with the help of <a href="https://drafts.csswg.org/css-exclusions/">CSS Exclusions</a>, it will be possible to do so without it). Also, it’s not possible to wrap text from both sides of a shape.</p><p>The CSS Shapes specification Level 1 defines three properties:</p><ul><li>shape-outside</li><li>shape-image-threshold</li><li>shape-margin</li></ul><h3>shape-outside</h3><p>The <strong>shape-outside</strong> CSS property defines a shape around which adjacent inline content should wrap. By default, inline content wraps around its margin box; by accepting different functions, <strong>shape-outside</strong> provides a way to customize this wrapping.</p><p>Some supported values are:</p><ul><li><strong>circle()</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9696bef3f7ad4836471dce59ac878840/href">https://medium.com/media/9696bef3f7ad4836471dce59ac878840/href</a></iframe><ul><li><strong>polygon()</strong> —The polygon() function allows you to “go crazy” and create any kind of shape. It gets as an argument, a list of at least 3 coordinates. This, for example, is how you would create a simple 5 pointed star:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f422ef208d6dc302361cc9d944e0d2fe/href">https://medium.com/media/f422ef208d6dc302361cc9d944e0d2fe/href</a></iframe><p>Creating shapes by hand is a bit of a pain, so you can use online tools such as <a href="https://bennettfeely.com/clippy/">this one</a> to generate the correct CSS, which you can just copy-paste to your project.</p><ul><li><strong>url() — </strong>With this function you can create dynamic float borders from an image. It only supports png/gif/svg formats thought. Also note that you need the actual image present as an &lt;img&gt; tag for it to work.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90f9579dec281474f36c80ff71454334/href">https://medium.com/media/90f9579dec281474f36c80ff71454334/href</a></iframe><p>Other supported shapes are ellipse() and inset().</p><p><strong>Note:</strong> A useful property to use along with <strong>shape-outside</strong> is <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path"><strong>clip-path</strong></a> which takes the same values (except for url) and creates a visible shape.</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fyqnrgeod%2Fembedded%2Fresult%2Ccss%2Chtml%2F&amp;src=https%3A%2F%2Fjsfiddle.net%2FSvetaSR%2Fyqnrgeod%2Fembedded%2Fresult%2Ccss%2Chtml%2F&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e933d6d1b93c3e5985b845830dc2d25/href">https://medium.com/media/9e933d6d1b93c3e5985b845830dc2d25/href</a></iframe><h3>shape-image-threshold</h3><p>When using shape-outside along with an image value (using the url() function), the <strong>shape-image-threshold</strong> property is used to adjust the minimum opacity level of pixels that will be used to create the shape. Its value must be in the range between 0 and 1.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45ee4c0b9ae36287012d0919c4d5a5ed/href">https://medium.com/media/45ee4c0b9ae36287012d0919c4d5a5ed/href</a></iframe><h3>shape-margin</h3><p>If the shape you created with <strong>shape-outside</strong> is too close to the text, you can adjust its margin from the content using this property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50bcb20bb636557f98b700aab12b9dd2/href">https://medium.com/media/50bcb20bb636557f98b700aab12b9dd2/href</a></iframe><h3>Browser Support</h3><p>Unfortunately CSS shapes level 1 is not supported by IE11 and not even by Edge, however support from other browsers is not too bad! You can still make your page look better on these, and just let them fallback to the old behavior on non supported browsers, or you can use a <a href="https://github.com/adobe-webplatform/css-shapes-polyfill">polyfill</a>, created by Adobe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*aPuQvkwg9aLXkPI6o4BFdw.png" /><figcaption><a href="https://caniuse.com/#feat=css-shapes">https://caniuse.com/#feat=css-shapes</a></figcaption></figure><h3>Future Features</h3><p>Currently we can only float text around shapes, but when CSS Shapes level 2 hit the shelves, we will get a new feature called “shape-inside”, which will let us put text inside shapes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Nxlzccf244qPlthH5i961g.gif" /><figcaption><a href="https://drafts.csswg.org/css-shapes-2/#shape-inside-property">https://drafts.csswg.org/css-shapes-2/#shape-inside-property</a></figcaption></figure><h3>Conclusion</h3><p>We learned that we can break the limits we were previously set, and by using some simple CSS, make our web pages more interesting to look at! I really hope this little article will inspire you to test these neat features :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=250ae1fd340" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Things You Should Know Before Traveling to Japan]]></title>
            <link>https://sveta-slepner.medium.com/10-things-you-should-know-before-traveling-to-japan-ba216918db60?source=rss-9fbbda39eb22------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba216918db60</guid>
            <category><![CDATA[japanese-food]]></category>
            <category><![CDATA[travel]]></category>
            <category><![CDATA[travel-tips]]></category>
            <category><![CDATA[japanese-culture]]></category>
            <category><![CDATA[japan]]></category>
            <dc:creator><![CDATA[Sveta Slepner]]></dc:creator>
            <pubDate>Thu, 22 Mar 2018 23:01:47 GMT</pubDate>
            <atom:updated>2021-06-09T16:55:15.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egB2fsSU-wkSb4Vks8qppQ.jpeg" /></figure><p>Japan is an amazing country, and it’s hard not fall in love with it after visiting even once. However, its culture is so different and unique, it’s better to come prepared so you’ll enjoy your visit even more. So here are some 10 things you should know before visiting Japan:</p><h3><strong>1. Trash cans are a rare sight</strong></h3><p>Japan is probably the most hygiene obsessed nation in the world. This means that unlike other countries, you should never worry about getting sick from street food or an unfamiliar restaurant. This is also the reason for the most clean streets I&#39;ve ever seen in my life. It’s simply amazing how the asphalt in almost any place I&#39;ve visited, looked like it was paved yesterday!</p><p>With that being said, trash cans are nearly impossible to locate. It’s not that they’re nonexistent, but they can be hard to locate. So my advise is — take a plastic bag with you in your backpack, and use it until you do locate a trash can.</p><h3>2. No Tips!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XAAIQCPTNAQHw7qWq0F1dQ.jpeg" /></figure><p>Japanese people are diligent workers and believe that giving a good service is part of their job. So leaving a tip in a restaurant (aside for some exceptions) will not be received well, and might end up with an embarrassed waiter chasing you to return the money. Just avoid it whatsoever.</p><h3>3. Japanese toilets are awesome. And confusing.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FSLaOdWMjT_PLhWQpjPBQQ.jpeg" /><figcaption>A standard toilet UI</figcaption></figure><p>Prepare yourself to be shocked by Japanese toilets. No matter where you find one, be it a museum, the train or in an hotel room, the toilet will have some “extra” features such as toilet seat heating, bidet, and even a button playing flushing sounds for those embarrassed about their natural sounds.</p><p>Since not all toilets have their buttons translated into English, and some will have you playing guesses with which one is the flush button, just remember its symbol:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*skNqZMiyQu03zv1YfchplQ.png" /></figure><p>Speaking of toilets, crouching toilets are a thing in Japan, but in most cases, you’ll find at least one cabin with a western toilet, so don’t worry (though crouching toilets are supposed to be healthier).</p><h3>4. Taking off your shoes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-urv6m3axSxCLbVjMsYukA.jpeg" /></figure><p>In Japan it’s a custom to take off your shoes before entering someone’s house, when vising shrines, some museums, traditional hotels and more. So bring a conformable pair of shoes you can easily take off, and some clean pairs of socks with no holes ;)</p><h3>5. Finding a good WI-FI is like catching a unicorn</h3><p>Japan is known for it’s advanced technology. However for some reason, finding a good wi-fi connection is kinda hard. Even in hotels, you might have one, but it’ll be so slow that Skyping your grandma, or uploading the awesome photos you took during the day to Instagram, will prove to be challenging. Since using the internet these days is an essential part of travelling (For planning your public transport routes, checking out the weather and so on), I recommend you to purchase an oversees internet package from your mobile phone provider, or just rent a pocket wi-fi modem in Japan. These can last many hours without charging, and have multiple devices connected to them.</p><h3>6. Prepare the cash</h3><p>In Japan there are many places such as restaurants and souvenir stores that receive only cash as payment. So prepare your cash beforehand to avoid inconvenience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*xWIf-uQ8njmn2s_xai6Qjg.jpeg" /></figure><p>Also on that note, crime is rather rare in japan (it does exist, but for the most part Japan is a very safe country) and pick-pocketing is not an issue. You obviously shouldn&#39;t have your banknotes dangling from your pockets, but no need to hide them in your socks as well..</p><h3>7. Communication issues</h3><p>Most Japanese people don’t speak English so well, or are just too shy to speak it. This is more apparent the further away you travel from the large cities. They are however very friendly and keen to help, so installing Google Translate might prove to be very useful. You can download the Japanese translation package before your trip, and this way you won’t even need an internet connection to use it! Another neat feature of this app, allows you to easily translate signs or restaurant menus just by taking a photo of the text!</p><h3>8. Everything for 100 Yen</h3><p>Japan is known for its 100 Yen stores (especially Daiso, but there are many others). These stores contain anything — From art supply, to fluffy hats, small gadgets, cosmetics, and basically anything that comes to mind for the price of 100 Yen (currently less than a dollar). This is a great place to bulk buy some small souvenirs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxYotRAUXknk_vmRSONk1g.jpeg" /></figure><p>Speaking of souvenirs (or Omiyage as they’re called in Japanese), they are mostly cheap in comparison to other counties. This is probably because In-country tourism is very popular in Japan, and it’s a custom to bring Omiyage to friends, family and co-workers, so the prices are very affordable.</p><h3>9. The food is amazing</h3><p>Japanese food is amazing, especially if you enjoy raw fish and sea food. There is a non-ending variety of all sorts of dishes, and different varieties of the same dish depending on the part of Japan you’re visiting. So if you want to truly experience Japan, I recommend you to try as much as possible!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9AYvgTfspGbl_caI194WQ.jpeg" /><figcaption>A bowl of Udon soup with beaf</figcaption></figure><p>Some dishes I personally recommend:</p><ol><li>Chirashi — a bowl full of rice and all sorts of raw fish and salmon eggs on top.</li><li>Takoyaki — a savory ball-shaped pancake, typically filled with minced or diced octopus.</li><li>Okonomiyaki — a savory pancake containing a variety of ingredients (such as bacon, peanuts, cabbage and more).</li><li>Unagi — A japanese style eel, lacquered with a sweet barbecue sauce.</li><li>Yakitori — Japanese type of skewered chicken.</li><li>Kobe beef — if you love red meat, you’ll thank me later.</li></ol><h3>10. Any special requests? Write it down.</h3><p>As said above in section 7, Japanese people don’t really speak English. So what happens if you have some sort of allergy/medical condition/you’re vagan/keep kosher/halal etc? Prepare a written note in Japanese! But don’t rely on Google Translate for this one — find a native speaker in person or online, and ask nicely to help you with that note!</p><p>Have fun with your trip to Japan!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba216918db60" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>