<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Konstantin Lebedev</title>
    <description>The latest articles on Forem by Konstantin Lebedev (@kosslebedev).</description>
    <link>https://forem.com/kosslebedev</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F173118%2F33020e4a-940b-4747-89f6-de7fffa75f81.jpeg</url>
      <title>Forem: Konstantin Lebedev</title>
      <link>https://forem.com/kosslebedev</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/kosslebedev"/>
    <language>en</language>
    <item>
      <title>10 security tips for frontend developers</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Thu, 09 Apr 2020 13:24:35 +0000</pubDate>
      <link>https://forem.com/kosslebedev/10-security-tips-for-frontend-developers-4j8h</link>
      <guid>https://forem.com/kosslebedev/10-security-tips-for-frontend-developers-4j8h</guid>
      <description>&lt;p&gt;Web security is a topic that is often overlooked by frontend developers. When we assess the quality of the website, we often look at metrics like performance, SEO-friendliness, and accessibility, while the website's capacity to withstand malicious attacks often falls under the radar. And even though the sensitive user data is stored server-side and significant measures must be taken by backend developers to protect the servers, in the end, the responsibility for securing that data is shared between both backend and frontend. While sensitive data may be safely locked in a backend warehouse, the frontend holds the keys to its front door, and stealing them is often the easiest way to gain access.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;"The responsibility for securing user's data is shared between both backend and frontend."&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;There are multiple attack vectors that malicious users can take to compromise our frontend applications, but fortunately, we can largely mitigate the risks of such attacks with just a few properly configured response headers and by following good development practices. In this article, we'll cover 10 easy things that you can do to improve the protection of your web applications.&lt;/p&gt;

&lt;h2&gt;
  
  
  Measuring the results
&lt;/h2&gt;

&lt;p&gt;Before we start improving website security, it is important to have some feedback on the effectiveness of the changes that we make. And while quantifying what makes up "good development practice" may be difficult, the strength of security headers can be measured quite accurately. Much like we use Lighthouse to get performance, SEO, and accessibility scores, we can use &lt;a href="https://securityheaders.com/" rel="noopener noreferrer"&gt;SecurityHeaders.com&lt;/a&gt; to get a security score based on the present response headers. For imperfect scores, it will also give us some tips on how to improve the score and, as a result, strengthen the security:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F4hjf2gnujq57jeestejm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F4hjf2gnujq57jeestejm.png" alt="SecurityHeaders.com report"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The highest score that SecurityHeaders can give us is "A+", and we should always try to aim for it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Note on response headers
&lt;/h2&gt;

&lt;p&gt;Dealing with response headers used to be a task for the backend, but nowadays we often deploy our web applications to "serverless" cloud platforms like &lt;a href="https://zeit.co/" rel="noopener noreferrer"&gt;Zeit&lt;/a&gt; or &lt;a href="https://www.netlify.com/" rel="noopener noreferrer"&gt;Netlify&lt;/a&gt;, and configuring them to return proper response headers becomes frontend responsibility. Make sure to learn how your cloud hosting provider works with response headers, and configure them accordingly.&lt;/p&gt;

&lt;h2&gt;
  
  
  Security measures
&lt;/h2&gt;

&lt;h3&gt;
  
  
  1. Use strong content security policy
&lt;/h3&gt;

&lt;p&gt;Sound content security policy (CSP) is the cornerstone of safety in frontend applications. CSP is a standard that was introduced in browsers to detect and mitigate certain types of code injection attacks, including cross-site scripting (XSS) and clickjacking.&lt;/p&gt;

&lt;p&gt;Strong CSP can disable potentially harmful inline code execution and restrict the domains from which external resources are loaded. You can enable CSP by setting &lt;code&gt;Content-Security-Policy&lt;/code&gt; header to a list of semicolon-delimited directives. If your website doesn't need access to any external resources, a good starting value for the header might look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Content-Security-Policy: default-src 'none'; script-src 'self'; img-src 'self'; style-src 'self'; connect-src 'self';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we set &lt;code&gt;script-src&lt;/code&gt;, &lt;code&gt;img-src&lt;/code&gt;, &lt;code&gt;style-src&lt;/code&gt;, and &lt;code&gt;connect-src&lt;/code&gt; directives to self to indicate that all scripts, images, stylesheets, and fetch calls respectively should be limited to the same origin that the HTML document is served from. Any other CSP directive not mentioned explicitly will fallback to the value specified by &lt;code&gt;default-src&lt;/code&gt; directive. We set it to &lt;code&gt;none&lt;/code&gt; to indicate that the default behavior is to reject connections to any URL.&lt;/p&gt;

&lt;p&gt;However, hardly any web application is self-contained nowadays, so you may want to adjust this header to allow for other trusted domains that you may use, like domains for Google Fonts or AWS S3 buckets for instance, but it's always better to start with the strictest policy and loosen it later if needed.&lt;/p&gt;

&lt;p&gt;You can find a full list of CSP directives on &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy" rel="noopener noreferrer"&gt;MDN website&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Enable XSS protection mode
&lt;/h3&gt;

&lt;p&gt;If malicious code does get injected from user input, we can instruct the browser to block the response by supplying &lt;code&gt;"X-XSS-Protection": "1; mode=block"&lt;/code&gt; header.&lt;/p&gt;

&lt;p&gt;Although XSS protection mode is enabled by default in most modern browsers, and we can also use content security policy to disable the use of inline JavaScript, it is still recommended to include &lt;code&gt;X-XSS-Protection&lt;/code&gt; header to ensure better security for older browsers that don't support CSP headers.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Disable iframe embedding to prevent clickjacking attacks
&lt;/h3&gt;

&lt;p&gt;Clickjacking is an attack where the user on website A is tricked into performing some action on website B. To achieve this, malicious user embeds website B into an invisible iframe which is then placed under the unsuspecting user's cursor on website A, so when the user clicks, or rather thinks they click on the element on website A, they actually click on something on a website B.&lt;/p&gt;

&lt;p&gt;We can protect against such attacks by providing &lt;code&gt;X-Frame-Options&lt;/code&gt; header that prohibits rendering of the website in a frame:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"X-Frame-Options": "DENY"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Alternatively, we can use &lt;code&gt;frame-ancestors&lt;/code&gt; CSP directive, which provides a finer degree of control over which parents can or cannot embed the page in an iframe.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Limit access to browser features &amp;amp; APIs
&lt;/h3&gt;

&lt;p&gt;Part of good security practice is restricting access to anything that is not needed for the proper use of our website. We've already applied this principle using CSP to limit the number of domains the website is allowed to connect to, but it can also be applied to browser features. We can instruct the browser to deny access to certain features and APIs that our application doesn't need by using &lt;code&gt;Feature-Policy&lt;/code&gt; header.&lt;/p&gt;

&lt;p&gt;We set &lt;code&gt;Feature-Policy&lt;/code&gt; to a string of rules separated by a semicolon, where each rule is the name of the feature, followed by its policy name.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Feature-Policy": "accelerometer 'none'; ambient-light-sensor 'none'; autoplay 'none'; camera 'none'; encrypted-media 'none'; fullscreen 'self'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; midi 'none'; payment 'none';  picture-in-picture 'none'; speaker 'none'; sync-xhr 'none'; usb 'none'; vr 'none';"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://www.smashingmagazine.com/2018/12/feature-policy/" rel="noopener noreferrer"&gt;Smashing Magazine&lt;/a&gt; has a great article explaining &lt;code&gt;Feature-Policy&lt;/code&gt; in great detail, but most of the time you'll want to set &lt;code&gt;none&lt;/code&gt; for all features that you don't use.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Don't leak referrer value
&lt;/h3&gt;

&lt;p&gt;When you click on a link that navigates away from your website, the destination website will receive the URL of the last location on your website in a &lt;code&gt;referrer&lt;/code&gt; header. That URL may contain sensitive and semi-sensitive data (like session tokens and user IDs), which should never be exposed.&lt;/p&gt;

&lt;p&gt;To prevent leaking of &lt;code&gt;referrer&lt;/code&gt; value, we set &lt;code&gt;Referrer-Policy&lt;/code&gt; header to &lt;code&gt;no-referrer&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"Referrer-Policy": "no-referrer"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This value should be good in most cases, but if your application logic requires you to preserve referrer in some cases, check out &lt;a href="https://scotthelme.co.uk/a-new-security-header-referrer-policy/" rel="noopener noreferrer"&gt;this article by Scott Helme&lt;/a&gt; where he breaks down all possible header values and when to apply them.&lt;/p&gt;

&lt;h3&gt;
  
  
  6. Don't set innerHTML value based on the user input
&lt;/h3&gt;

&lt;p&gt;Cross-site scripting attack in which malicious code gets injected into a website  can happen through a number of different DOM APIs, but the most frequently used is &lt;code&gt;innerHTML&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You should never set &lt;code&gt;innerHTML&lt;/code&gt; based on unfiltered input from the user. Any value that can be directly manipulated by the user -  be that text from an input field, a parameter from URL, or local storage entry - should be escaped and sanitized first. Ideally, use &lt;code&gt;textContent&lt;/code&gt; instead of &lt;code&gt;innerHTML&lt;/code&gt; to prevent generating HTML output altogether. If you do need to provide rich-text editing to your users, use well-established libraries that use whitelisting instead of blacklisting to specify allowed HTML tags.&lt;/p&gt;

&lt;p&gt;Unfortunately, &lt;code&gt;innerHTML&lt;/code&gt; is not the only weak point in DOM API, and the code susceptible to XSS injections can still be hard to detect. This is why it is important to always have a strict content security policy that disallows inline code execution.&lt;/p&gt;

&lt;p&gt;For the future, you may want to keep an eye on a new &lt;a href="https://developers.google.com/web/updates/2019/02/trusted-types" rel="noopener noreferrer"&gt;Trusted Types specification&lt;/a&gt; which aims to prevent all DOM-based cross-site scripting attacks.&lt;/p&gt;

&lt;h3&gt;
  
  
  7. Use UI frameworks
&lt;/h3&gt;

&lt;p&gt;Modern UI frameworks like React, Vue, and Angular have a good level of security built into them, and can largely eliminate the risks of XSS attacks. They automatically  encode HTML output, reduce the need for using XSS-susceptible DOM APIs, and give unambiguous and cautionary names to potentially dangerous methods, like &lt;code&gt;dangerouslySetInnerHTML&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  8. Keep your dependencies up to date
&lt;/h3&gt;

&lt;p&gt;A quick look inside &lt;code&gt;node_modules&lt;/code&gt; folder will confirm that our web applications are lego puzzles built out of hundreds (if not thousands) dependencies. Ensuring that these dependencies don't contain any known security vulnerabilities is very important for the overall security of your website.&lt;/p&gt;

&lt;p&gt;The best way to make sure that dependencies stay secure and up-to-date is to make vulnerability checking a part of the development process. To do that, you can integrate tools like &lt;a href="https://dependabot.com/" rel="noopener noreferrer"&gt;Dependabot&lt;/a&gt; and &lt;a href="https://snyk.io/" rel="noopener noreferrer"&gt;Snyk&lt;/a&gt;, which will create pull requests for out-of-date or potentially vulnerable dependencies and help you apply fixes sooner.&lt;/p&gt;

&lt;h3&gt;
  
  
  9. Think twice before adding third-party services
&lt;/h3&gt;

&lt;p&gt;Third-party services like Google Analytics, Intercom, Mixpanel, and a hundred others can provide a "one line of code" solution to your business needs. At the same time, they can make your website more vulnerable, because if a third-party service gets compromised, then so will be your website.&lt;/p&gt;

&lt;p&gt;Should you decide to integrate a third-party service, make sure to set the strongest CSP policy that would still permit that service to work normally. Most of the popular services have documented what CSP directives they require, so make sure to follow their guidelines.&lt;/p&gt;

&lt;p&gt;Especial care should be taken when using Google Tag Manager, Segment, or any other tools that allow anyone in your organization to integrate more third-party services. People with access to this tool must understand the security implication of connecting additional services and ideally discuss it with their development team.&lt;/p&gt;

&lt;h3&gt;
  
  
  10. Use Subresource Integrity for third-party scripts
&lt;/h3&gt;

&lt;p&gt;For all third-party scripts that you use, make sure to include &lt;code&gt;integrity&lt;/code&gt; attribute when possible. Browsers have &lt;a href="https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity" rel="noopener noreferrer"&gt;Subresource Integrity&lt;/a&gt; feature that can validate the cryptographic hash of the script that you're loading and make sure that it hasn't been tampered with.&lt;/p&gt;

&lt;p&gt;This how your &lt;code&gt;script&lt;/code&gt; tag may look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight html"&gt;&lt;code&gt;&lt;span class="nt"&gt;&amp;lt;script &lt;/span&gt;&lt;span class="na"&gt;src=&lt;/span&gt;&lt;span class="s"&gt;"https://example.com/example-framework.js"&lt;/span&gt;
        &lt;span class="na"&gt;integrity=&lt;/span&gt;&lt;span class="s"&gt;"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/ux..."&lt;/span&gt;
        &lt;span class="na"&gt;crossorigin=&lt;/span&gt;&lt;span class="s"&gt;"anonymous"&lt;/span&gt;&lt;span class="nt"&gt;&amp;gt;&amp;lt;/script&amp;gt;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It's worth clarifying that this technique is useful for third-party libraries, but to a lesser degree for third-party services. Most of the time, when you add a script for a third-party service, that script is only used to load another dependant script. It's not possible to check the integrity of the dependant script because it can be modified at any time, so in this case, we have to fall back on a strict content security policy.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Save browsing experience is an important part of any modern web application, and the users want to be sure that their personal data remains secure and private. And while this data is stored on the backend, the responsibility for securing it extends to client-side applications as well.&lt;/p&gt;

&lt;p&gt;There are many variations of UI-first attacks that malicious users can take advantage of, but you can greatly increase your chances of defending against them if you follow the recommendations given in this article.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>security</category>
    </item>
    <item>
      <title>Animating between units with react-spring</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Thu, 21 Nov 2019 14:44:50 +0000</pubDate>
      <link>https://forem.com/kosslebedev/animating-between-units-with-react-spring-4ob9</link>
      <guid>https://forem.com/kosslebedev/animating-between-units-with-react-spring-4ob9</guid>
      <description>&lt;p&gt;It's no secret, that on the web we have to deal with different units - from rems and pixels to percentages and viewport-based values. In this tutorial, we'll explore the problem of animating between different units, and see how we can overcome it.&lt;/p&gt;

&lt;h2&gt;
  
  
  The problem
&lt;/h2&gt;

&lt;p&gt;Let's start by creating this simple animation where a div with pixel-based size expands to fill the entire viewport width and height when we click on it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fvu71uqfopaczgawo79jv.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fvu71uqfopaczgawo79jv.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To create this animation, we'll use &lt;code&gt;useSpring&lt;/code&gt; hook from &lt;code&gt;react-spring&lt;/code&gt; package, and set the width and the height of the box to 200px when it's not expanded, and to 100vh and 100vw when it is. We'll also remove 10px border-radius when the box is expanded:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The result will look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F4oyaj8o2iv2aaru1vh9c.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F4oyaj8o2iv2aaru1vh9c.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;As we can see, the border-radius animation is working, but the box gets smaller instead. Why is that?&lt;/p&gt;

&lt;p&gt;To understand the problem, we need to look at how &lt;code&gt;react-spring&lt;/code&gt; (and most of React animation libraries for that matter) handles animation between units. When we pass width and height values as strings, &lt;code&gt;react-spring&lt;/code&gt; will parse the numeric values from the "from" and "to" values, take the unit from the "from" value, and completely ignore the unit of the "to" value:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fis1y9cvjvdl755688tmz.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fis1y9cvjvdl755688tmz.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;In our example, the initial state of the box is collapsed and the height of the box is pixel-based, so when &lt;code&gt;react-spring&lt;/code&gt; starts animating it, it'll use "pixels" as a unit. If instead the initial state was expanded and the height was viewport-based, then the animation would use "vh" as a unit and run from 100vh to 200vh instead.&lt;/p&gt;

&lt;p&gt;The border-radius animation works fine because if uses pixels for both expanded and collapsed states.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Side note: the only library that I found that handles animation between units correctly out-of-the-box is &lt;a href="https://www.framer.com/motion/" rel="noopener noreferrer"&gt;framer-motion&lt;/a&gt;. I have an &lt;a href="https://konstantinlebedev.com/framer-motion-intro/" rel="noopener noreferrer"&gt;intro level article&lt;/a&gt; about framer-motion, and you can also sign up for my upcoming &lt;a href="https://konstantinlebedev.com/framer-motion/" rel="noopener noreferrer"&gt;framer-motion course&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  The solution
&lt;/h2&gt;

&lt;p&gt;To fix this problem, we need to make sure that both the initial and the target value use the same unit. We can easily convert viewport-based values into pixels with these simple calculations:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now instead of using viewport-based values, we'll use our helper functions to set the width and the height of the box:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This solves the problem only partially because if we resize the browser window after the animation has run, we'll discover a different issue - the box doesn't adjust to the viewport size anymore since now it has pixel-based size:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fgjme2bpilcme6e47ae78.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fgjme2bpilcme6e47ae78.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can fix this issue by setting the box size back to viewport-based values once the animation finishes. First of all, we'll use &lt;code&gt;useRef&lt;/code&gt; hook to hold a reference to the actual DOM node of our box. Secondly, &lt;code&gt;react-spring&lt;/code&gt; provides a handy &lt;code&gt;onRest&lt;/code&gt; callback that fires at the end of each animation, so we can use it to check if we animated to the expanded state, and if so, we'll set the box width and height directly.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;With this setup, animation works fine - it uses pixel values while animating, and sets the box dimensions to viewport-based size upon completion, so the box remains responsive even if we resize the browser afterward.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fvu71uqfopaczgawo79jv.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fvu71uqfopaczgawo79jv.gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can find working CodeSandbox demo &lt;a href="https://codesandbox.io/s/animate-across-units-react-spring-d7q8e" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Animation libraries such as &lt;code&gt;react-spring&lt;/code&gt; give us a greater degree of control over our animations compared to CSS animations, but they have  shortcomings as well. Animating values between units is one of them, and it requires us to do extra work to make sure that our animation runs smoothly and remains responsive.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>animations</category>
      <category>reactspring</category>
    </item>
    <item>
      <title>Building a Cool Horizontal Scroll Interaction in React</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Sat, 02 Nov 2019 10:41:26 +0000</pubDate>
      <link>https://forem.com/kosslebedev/building-a-cool-horizontal-scroll-interaction-in-react-46h4</link>
      <guid>https://forem.com/kosslebedev/building-a-cool-horizontal-scroll-interaction-in-react-46h4</guid>
      <description>&lt;p&gt;In this tutorial, we'll create a fun scroll animation in which items "flip" in the direction of the scroll. We're going to use &lt;a href="http://react-spring.surge.sh"&gt;react-spring&lt;/a&gt; for animating and &lt;a href="https://github.com/react-spring/react-use-gesture"&gt;react-use-gesture&lt;/a&gt; to tie animation to the scroll events. The native &lt;code&gt;onScroll&lt;/code&gt; event handler won't do in this case, because we'll need additional information about scrolling that native &lt;code&gt;onScroll&lt;/code&gt; handler doesn't provide - scroll delta in pixels, and whether the scrolling is in progress or not.&lt;/p&gt;

&lt;p&gt;This is what we're going to build:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--U64OiQIc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/pynqc7fg2niwp2xdvuj0.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--U64OiQIc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/pynqc7fg2niwp2xdvuj0.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Basic setup
&lt;/h2&gt;

&lt;p&gt;We'll start with the basic React component you can see below. The component renders a list of images from &lt;code&gt;public&lt;/code&gt; folder, and sets them as background for &lt;code&gt;div&lt;/code&gt; elements:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Next, we'll apply some styling. We need to make sure that the container takes up 100% of the width and it allows its children to overflow:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;With the basic styling, our component will look like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ZNRF3r9A--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/gckioe0fk6t6mg6f832d.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ZNRF3r9A--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/gckioe0fk6t6mg6f832d.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding animation
&lt;/h2&gt;

&lt;p&gt;Let's start by adding a rotation animation. First, we'll replace &lt;code&gt;div&lt;/code&gt; element with &lt;code&gt;animated.div&lt;/code&gt;. &lt;code&gt;animated&lt;/code&gt; is a decorator that&lt;br&gt;
extends native elements to receive animated values. Every HTML and SVG element has an &lt;code&gt;animated&lt;/code&gt; counterpart that we have to use if we intend to animate that element.&lt;/p&gt;

&lt;p&gt;Next, we'll use &lt;code&gt;useSpring&lt;/code&gt; hook from react-spring package to create a basic animation that will run when the component is mounted. Eventually, we'll bind our animation to the scroll event, but for the time being, it will be easier to see the result of the changes that we make if animation simply runs on mount.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useSpring&lt;/code&gt; hook takes an object with CSS properties that should be animated. These properties should be set to &lt;strong&gt;end values&lt;/strong&gt; of the animation, so if we want to rotate &lt;code&gt;div&lt;/code&gt;s from 0 to 25 degrees, we set the &lt;code&gt;transform&lt;/code&gt; value to &lt;code&gt;rotateY(25deg)&lt;/code&gt;. To set the &lt;strong&gt;initial values&lt;/strong&gt;, we use &lt;code&gt;from&lt;/code&gt; property which itself takes an object with CSS properties.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useSpring&lt;/code&gt; hook returns a &lt;code&gt;style&lt;/code&gt; object that we need to set on the target component. We can see the updated code and the result below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nt5B_YQn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/09f7d0ib5nyq9wat6nbn.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nt5B_YQn--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/09f7d0ib5nyq9wat6nbn.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This animation looks flat because by default the rotation is 2-dimensional, it's rendered as if there were no distance between the user observing the animation and the rotation plane. &lt;code&gt;perspective&lt;/code&gt; transformation allows us to move the observation point away from the rotation plane, and thus makes 2-dimensional animation look 3-dimensional:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ezmQr2sN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/4550a81w9tvgg2d8hzhu.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ezmQr2sN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/4550a81w9tvgg2d8hzhu.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Finally, we need to add vertical padding to the container &lt;code&gt;div&lt;/code&gt; to make sure that children elements don't get cut off:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--2GWSOxIC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/14bxtnhtt6wycumeqoeu.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--2GWSOxIC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/14bxtnhtt6wycumeqoeu.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Binding animation to scroll
&lt;/h2&gt;

&lt;p&gt;Before we start working with scroll events, we need to make a small change to how we use &lt;code&gt;useSpring&lt;/code&gt; hook. There are two things to keep in mind:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;we need to be able to trigger animation manually&lt;/li&gt;
&lt;li&gt;we no longer need to run animation on mount&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To address both of these issues, we'll use a different &lt;code&gt;useSpring&lt;/code&gt; signature - instead of &lt;strong&gt;passing an object&lt;/strong&gt; with CSS properties, we'll &lt;strong&gt;pass a function&lt;/strong&gt; that returns an object with CSS properties. Previously, &lt;code&gt;useSpring&lt;/code&gt; hook returned us a &lt;code&gt;style&lt;/code&gt; object&lt;br&gt;
. With the new signature, it will return a tuple, where the first argument is a &lt;code&gt;style&lt;/code&gt; object, and the second argument is a &lt;code&gt;set&lt;/code&gt; function that we can call anytime to trigger the animation.&lt;/p&gt;

&lt;p&gt;We can also drop &lt;code&gt;from&lt;/code&gt; property since this value will be determined based on the current rotation of the &lt;code&gt;div&lt;/code&gt;s:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now we can import &lt;code&gt;useScroll&lt;/code&gt; hook from react-use-gesture package and bind it to the container &lt;code&gt;div&lt;/code&gt;. The logic for handling scroll events is very simple - if the user is scrolling (&lt;code&gt;event.scrolling === true&lt;/code&gt;), we want to rotate cards by the number of degrees equal to scroll delta on Y-axis (&lt;code&gt;event.delta[0]&lt;/code&gt;); if scrolling stops, we want to reset the rotation angle to &lt;code&gt;0&lt;/code&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--OjSygz09--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/hrga0isdgmbt6buxf8jo.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--OjSygz09--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/hrga0isdgmbt6buxf8jo.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Animation works, but there is an undesired side-effect - if we scroll sharply, the Y delta will be quite big, which may cause cards to flip more than 90 degrees. I've tested different values and discovered that the animation looks best if the cards flip no more than 30 degrees. We can write a helper function to clamp the delta value so it never gets more than 30 and less than -30:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now we can use this helper function to clamp Y delta inside &lt;code&gt;useScroll&lt;/code&gt; hook and get the final result:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--U64OiQIc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/pynqc7fg2niwp2xdvuj0.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--U64OiQIc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/pynqc7fg2niwp2xdvuj0.gif" alt=""&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can find a complete working demo of this interaction &lt;a href="https://codesandbox.io/s/react-spring-fun-scroll-vmncd"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PS:&lt;/strong&gt; I also made the same interaction using &lt;a href="https://framer.com/motion/"&gt;framer-motion&lt;/a&gt;. working demo is available &lt;a href="https://codesandbox.io/s/framer-motion-fun-scroll-788qb"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you want to get more tutorials like this one, make sure to &lt;a href="https://konstantinlebedev.com/newsletter/"&gt;subscribe to my newsletter&lt;/a&gt;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h2&gt;
  
  
  Final thoughts
&lt;/h2&gt;

&lt;p&gt;I would like to mention two decisions that stayed behind the curtain of this tutorial but had been made before making this particular animation.&lt;/p&gt;

&lt;p&gt;The first decision concerns performance. To make the flip animation, we animated only &lt;code&gt;transform&lt;/code&gt; property, which is one of the only two properties that are accelerated by GPU and that don't take time off the main thread (the other property is &lt;code&gt;opacity&lt;/code&gt;). There's quite a lot we can achieve by animating only &lt;code&gt;transform&lt;/code&gt; and &lt;code&gt;opacity&lt;/code&gt;, and whenever possible, we should avoid animating any other CSS properties.&lt;/p&gt;

&lt;p&gt;Secondly, we need to consider responsiveness. Horizontal scroll that we implemented works well on phones and tablets, but for larger desktop screens we might want to use a more common grid layout. With small CSS changes and a media query we can switch from &lt;code&gt;flex&lt;/code&gt; to &lt;code&gt;grid&lt;/code&gt; layout, and we don't have to change the animation at all - it will continue working on small screens that use &lt;code&gt;flex&lt;/code&gt; layout, and it will be ignored on large screens since with &lt;code&gt;grid&lt;/code&gt; layout we won't have horizontal scroll.&lt;/p&gt;

</description>
      <category>react</category>
      <category>animations</category>
      <category>reactspring</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Animate React with Framer Motion</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Thu, 25 Jul 2019 13:24:03 +0000</pubDate>
      <link>https://forem.com/kosslebedev/animate-react-with-framer-motion-fo2</link>
      <guid>https://forem.com/kosslebedev/animate-react-with-framer-motion-fo2</guid>
      <description>&lt;p&gt;&lt;a href="https://www.framer.com/motion/" rel="noopener noreferrer"&gt;Framer-motion&lt;/a&gt; is a library that powers animations in &lt;a href="https://www.framer.com/" rel="noopener noreferrer"&gt;Framer&lt;/a&gt;, and it's now available as an independent package that we can use in React applications. It has a very simple declarative API that makes it easy to create and orchestrate complex animations with a minimal amount of code. In this article, we'll start with very basic animations and gradually move to the more advanced ones.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: animation examples in the article may not look smooth because of a low frame rate of GIF images. Rest assured, real animation are &lt;strong&gt;butter-smooth&lt;/strong&gt;. You can play with them in the &lt;a href="https://codesandbox.io/s/framer-motion-intro-96bu3" rel="noopener noreferrer"&gt;sandbox here&lt;/a&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;p&gt;We can start with framer-motion by simply installing it with &lt;code&gt;yarn add framer-motion&lt;/code&gt; command.&lt;/p&gt;

&lt;p&gt;To animate elements, we'll need to ditch primitive HTML elements (&lt;code&gt;div&lt;/code&gt;, &lt;code&gt;span&lt;/code&gt;, &lt;code&gt;path&lt;/code&gt;, etc.) in favor of their "motion-infused" counterparts - &lt;code&gt;motion.div&lt;/code&gt;, &lt;code&gt;motion.span&lt;/code&gt;, &lt;code&gt;motion.path&lt;/code&gt;, etc. These elements expose the properties that we'll need to add our animations.&lt;/p&gt;

&lt;h2&gt;
  
  
  Get things moving
&lt;/h2&gt;

&lt;p&gt;To create the simplest animation, we can specify &lt;code&gt;animate&lt;/code&gt; property that accepts an object with CSS properties that we want to animate. This is how we can animate opacity and background color of the &lt;code&gt;div&lt;/code&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F1iefdj7df3rdd1p1ymnd.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F1iefdj7df3rdd1p1ymnd.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 1: Animate on mount



&lt;p&gt;The properties that we pass to &lt;code&gt;animate&lt;/code&gt; represent the &lt;strong&gt;final state&lt;/strong&gt; of the animation. Framer-motion will infer the initial state based on the specified CSS properties, or their defaults. For example, default opacity for CSS elements is &lt;code&gt;1&lt;/code&gt; (even if we don't set it explicitly), so framer-motion knows how to animate it down to &lt;code&gt;0.5&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We can also set the initial values of animatable CSS properties using &lt;code&gt;initial&lt;/code&gt; prop. It also accepts an object with CSS properties that will tell framer-motion what initial values should be like. In the example below, we fade in the rectangle by animating &lt;code&gt;y&lt;/code&gt; and &lt;code&gt;opacity&lt;/code&gt; properties:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fv0iqqnn0fhyxjcsyj3ql.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fv0iqqnn0fhyxjcsyj3ql.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 2: Animate using initial state



&lt;p&gt;It's worth mentioning that property &lt;code&gt;y&lt;/code&gt; is special - it's not a real CSS property, but framer-motion understands it. There are a bunch of CSS &lt;code&gt;transform&lt;/code&gt;-related properties that have shortcuts in framer-motion, so when we change &lt;code&gt;y&lt;/code&gt; property, we actually apply animation to &lt;code&gt;transform: translateY()&lt;/code&gt; property. Similarly, there are &lt;code&gt;scale&lt;/code&gt;, &lt;code&gt;rotate&lt;/code&gt;, &lt;code&gt;scaleX&lt;/code&gt;, &lt;code&gt;scaleY&lt;/code&gt; and some other properties, you can find the complete list &lt;a href="https://www.framer.com/api/motion/component/#transform" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Animating state changes
&lt;/h2&gt;

&lt;p&gt;The animations that we've done so far only run when components mount. Now let's see how we can animate elements when some internal state changes.&lt;/p&gt;

&lt;p&gt;We can set &lt;code&gt;animation&lt;/code&gt; property to different values based on the internal state, and framer-motion will animate between those values when the state changes:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fstzpryy1rh23l695eize.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fstzpryy1rh23l695eize.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 3: Animate div on click



&lt;p&gt;Note that the component re-renders only when state changes, and not on every animation frame, which makes animations very efficient.&lt;/p&gt;

&lt;h2&gt;
  
  
  Variants
&lt;/h2&gt;

&lt;p&gt;The real power of framer-motion comes from using &lt;strong&gt;variants&lt;/strong&gt;. Let's start by exploring how we can rewrite the previous example to use variants.&lt;/p&gt;

&lt;p&gt;We'll begin by extracting inline definition of animatable properties from &lt;code&gt;animate&lt;/code&gt; prop into a separate object. This object will contain key-value pairs, where keys are some meaningful names that we give to our animatable properties, and values are the properties themselves. Then we can pass this variants object to &lt;code&gt;variants&lt;/code&gt; prop, and inside &lt;code&gt;animation&lt;/code&gt; we can toggle animations based on the string names we gave to them:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fstzpryy1rh23l695eize.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fstzpryy1rh23l695eize.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 4: Animate div on click (again, but using variants)



&lt;p&gt;This example works, but it's not very useful. The power of variants is in orchestrating complex animations throughout a component tree, and to see that, we'll need a slightly bigger example.&lt;/p&gt;

&lt;p&gt;In the component below, we have a container &lt;code&gt;div&lt;/code&gt; that has three child &lt;code&gt;div&lt;/code&gt;s inside of it. Container &lt;code&gt;div&lt;/code&gt; uses the same &lt;code&gt;onClick&lt;/code&gt; animation that we've seen before:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fgqsj8053llrzlo9bs12a.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fgqsj8053llrzlo9bs12a.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 5: Animate div



&lt;p&gt;Now we can animate children elements simultaneously with the parent by setting their own variants object. When descriptive names of child animations match those of the parent, child animations will be triggered at the same time as parent animation.&lt;/p&gt;

&lt;p&gt;Notice how both &lt;code&gt;container&lt;/code&gt; and &lt;code&gt;box&lt;/code&gt; variants have the same keys &lt;code&gt;active&lt;/code&gt; and &lt;code&gt;disabled&lt;/code&gt;:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fx3lzzon3ouope7q285sk.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fx3lzzon3ouope7q285sk.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 6: Animate div with child elements



&lt;h2&gt;
  
  
  Configuring variants
&lt;/h2&gt;

&lt;p&gt;Variants also allow us to orchestrate the child animations. We can do that by providing &lt;code&gt;transition&lt;/code&gt; property inside the animation object.&lt;/p&gt;

&lt;p&gt;For example, we can set &lt;code&gt;staggerChildren&lt;/code&gt; children property, which specifies the delay in seconds between child animations:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fyds86kjqifrt1zvsg9zp.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fyds86kjqifrt1zvsg9zp.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 7: Stagger child elements



&lt;p&gt;Note how transition is applied only when we transition &lt;strong&gt;into a given variant&lt;/strong&gt;. Since we defined &lt;code&gt;transition&lt;/code&gt; property inside &lt;code&gt;active&lt;/code&gt; variant, the stagger animation is only applied when we transition from &lt;code&gt;disabled&lt;/code&gt; &lt;strong&gt;into&lt;/strong&gt; &lt;code&gt;active&lt;/code&gt;, but not when we transition from &lt;code&gt;active&lt;/code&gt; to &lt;code&gt;disabled&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;By default, variants start animating parent element and its children at the same time. We can control that behavior using &lt;code&gt;when&lt;/code&gt; property. We can set it to &lt;code&gt;beforeChildren&lt;/code&gt; to make parent element animate first, or to &lt;code&gt;afterChildren&lt;/code&gt;, to make parent element animate after its children:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fh1wn3m8y13o1zqwka7b3.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fh1wn3m8y13o1zqwka7b3.gif"&gt;&lt;/a&gt;&lt;/p&gt;
Demo 8: Animate parent before children



&lt;p&gt;With this configuration, the parent &lt;code&gt;div&lt;/code&gt; changes background color first, and then child elements rotate with a staggered delay.&lt;/p&gt;

&lt;p&gt;There are a lot more properties of variants that we can control - animation delays, stagger direction, etc. You can find more information on them in framer-motion &lt;a href="https://www.framer.com/api/motion/animation/#variants" rel="noopener noreferrer"&gt;documentation&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Wrapping up
&lt;/h2&gt;

&lt;p&gt;In this article, we've seen how easy it is to animate React components using declarative API that framer-motion provides. However, we just scratched the surface, since there's a lot more that framer-motion is capable of - gestures, dragging, working with SVG paths and much more. If you're interested in learning more - check out my &lt;a href="https://octocourses.com/framer-motion" rel="noopener noreferrer"&gt;new course&lt;/a&gt; that covers all the great features that framer-motion has to offer:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://octocourses.com/framer-motion" rel="noopener noreferrer"&gt;&lt;br&gt;
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F1hexmg8hghrtbkrkjv0g.png"&gt;&lt;br&gt;
&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>react</category>
      <category>animation</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Rematch with Hooks</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Mon, 24 Jun 2019 15:20:51 +0000</pubDate>
      <link>https://forem.com/kosslebedev/rematch-with-hooks-4ddp</link>
      <guid>https://forem.com/kosslebedev/rematch-with-hooks-4ddp</guid>
      <description>&lt;p&gt;If you've been using Rematch for managing state in your application, the latest release of &lt;code&gt;react-redux&lt;/code&gt; that adds support for hooks should get you really excited. &lt;/p&gt;

&lt;p&gt;Rematch has always tried to keep compatibility with existing &lt;code&gt;react-redux&lt;/code&gt; API, and that stays true for the newly released version that supports hooks!&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In addition to having more readable and reusable code, hooks allow us to do less work when adding type safety with TypeScript.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Let's look at an example of doing things "the old way". Here's a component that stores a list of users in Redux store, and loads them when the component is mounted:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This code looks and works fine, but there are a couple of issues that we couldn't address in pre-hook era. One of them is related to typing &lt;code&gt;connect&lt;/code&gt; component. Higher order components are notoriously difficult to type properly due to the difficulty of inferring types of the properties being passed down to the component inside. To get around this problem, we have to define types for props being passed to the component separately &lt;code&gt;(type UsersProps)&lt;/code&gt;, and then manually set them for the component &lt;code&gt;(FC&amp;lt;UsersProps&amp;gt;)&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;With hooks, we can replace &lt;code&gt;mapState&lt;/code&gt; function with &lt;code&gt;useSelector&lt;/code&gt; hook, &lt;code&gt;mapDispatch&lt;/code&gt; with &lt;code&gt;useDispatch&lt;/code&gt;, and we can drop our difficult-to-type &lt;code&gt;connect&lt;/code&gt; HOC altogether, leaving us with concise and fully typed code:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If  we need to work with multiple actions, we can create a custom &lt;code&gt;useRematchDispatch&lt;/code&gt; hook that allows us to have the familiar syntax that we used for writing &lt;code&gt;mapDispatch&lt;/code&gt; functions:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;&lt;code&gt;useRematchDispatch&lt;/code&gt; hook can also come in handy if we want to refactor existing Rematch application, because it allows us to copy &lt;code&gt;mapDispatch&lt;/code&gt; functions with minimum changes.&lt;/p&gt;




&lt;p&gt;If you want to learn more about Rematch, check out my &lt;a href="https://www.youtube.com/playlist?list=PLNG2YBDrzK-w1VSeDpMxdGwkb4L6hDy8Z"&gt;free course on YouTube&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>typescript</category>
      <category>react</category>
      <category>redux</category>
    </item>
    <item>
      <title>Type aliases vs. interfaces in TypeScript-based React apps</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Fri, 31 May 2019 08:35:08 +0000</pubDate>
      <link>https://forem.com/kosslebedev/type-aliases-vs-interfaces-in-typescript-based-react-apps-2jg2</link>
      <guid>https://forem.com/kosslebedev/type-aliases-vs-interfaces-in-typescript-based-react-apps-2jg2</guid>
      <description>&lt;p&gt;&lt;em&gt;Type aliases&lt;/em&gt; and &lt;em&gt;interfaces&lt;/em&gt; are TypeScript language features that often confuse people who try TypeScript for the first time. What’s the difference between them? When should we use one over the other?&lt;/p&gt;

&lt;p&gt;Type aliases and interfaces used to be quite different in their capabilities. However, it’s no longer true in the latest versions of TypeScript. Over time they have grown together to the point when they are almost identical. They still have some subtle differences — interfaces are more “extendable” due to the support of declaration merging, and types are more “composable” due to support of union types. We’ll talk about these differences in more details a bit later.&lt;/p&gt;

&lt;p&gt;Owing to the nature of differences between type aliases and interfaces, the decision to use one over another usually depends on your preferred programming style. &lt;strong&gt;If you write object-oriented code — use interfaces, if you write functional code — use type aliases.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now let’s talk about React.&lt;/p&gt;

&lt;p&gt;React is more functional by nature. Functional components are generally preferred over class-based components. Hot and shiny React Hooks are just functions used inside functional components. HOCs, Redux, pure functions, and a handful of other concepts widely used in React come from a functional world. So for these reasons,&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In React applications, just use type aliases.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now let’s see why.&lt;/p&gt;




&lt;h2&gt;
  
  
  1. Power of interfaces isn’t useful in React applications
&lt;/h2&gt;

&lt;p&gt;One of the main things that differentiate interfaces from type aliases is the ability to merge declarations. With interfaces, we can re-open previously declared interfaces and add additional properties to it:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The code above doesn’t have any errors, because the resulting &lt;code&gt;IUser&lt;/code&gt; interface will contain all 3 properties — &lt;code&gt;firstName&lt;/code&gt;, &lt;code&gt;lastName&lt;/code&gt;, and &lt;code&gt;age&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This is a very powerful feature that allows us to write type declarations for 3rd party libraries and gives us an option to extend them. However, In regular React application, this feature doesn’t bring any value. On the contrary, it can introduce unnecessary complexity and add bugs if somebody will try to monkey-patch props or state interfaces.&lt;/p&gt;

&lt;h2&gt;
  
  
  2. Type aliases are more composable
&lt;/h2&gt;

&lt;p&gt;One thing that type aliases can do that interfaces can’t is create an intersection with a type alias that uses union operator within its definition:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This can be useful when we want to combine component’s own props with some HOC’s props that might use union operator.&lt;/p&gt;

&lt;h2&gt;
  
  
  3. Type aliases require less typing (as in typing on the keyboard)
&lt;/h2&gt;

&lt;p&gt;It’s simply faster to type &lt;code&gt;type Props&lt;/code&gt; than &lt;code&gt;interface IProps&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  4. Consistency
&lt;/h2&gt;

&lt;p&gt;First of all, we don’t want to mix interfaces and types. It’s a common convention to prefix interface names with &lt;code&gt;I&lt;/code&gt;, so we’ll have a mix of &lt;code&gt;IProps&lt;/code&gt; interfaces and &lt;code&gt;Props&lt;/code&gt; type aliases in our code. Not only will it create unnecessary clutter, but also increase required mental effort every time we need to think: “Do we have &lt;code&gt;IProps&lt;/code&gt; interface or &lt;code&gt;Props&lt;/code&gt; type aliases here?”&lt;/p&gt;

&lt;p&gt;Second, we won’t be able to just use interfaces either. As we mentioned earlier, type composition is a very useful feature for React applications, and because interfaces cannot be combined with union-based types, at some point we may need to change our interfaces to type aliases. That means that we’ll also have to rename &lt;code&gt;IProps&lt;/code&gt; to &lt;code&gt;Props&lt;/code&gt; to avoid further confusion. And if the type is exported, we have to rename all the occurrences in the code as well. This extra work can be avoided by simply using type aliases everywhere.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Hopefully, this article helped you to see the difference between interfaces and type aliases in TypeScript and also convinced you that type aliases are preferable for React applications.&lt;/p&gt;

&lt;p&gt;If you disagree with any of the points or feel that something is missing, please let me know in the comments. In the meantime, go ahead and disable &lt;code&gt;interface-over-type-literal&lt;/code&gt; setting in TS Lint and start using type aliases in your React applications!&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Shameless plug&lt;/strong&gt;: if you want to learn how to use Redux without writing a ton of boilerplate, check my &lt;a href="https://www.youtube.com/playlist?list=PLNG2YBDrzK-w1VSeDpMxdGwkb4L6hDy8Z"&gt;"State management with Rematch" course&lt;/a&gt; on Youtube.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/f06elAAbb60"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>react</category>
      <category>typescript</category>
    </item>
    <item>
      <title>Typing components in Next.JS applications</title>
      <dc:creator>Konstantin Lebedev</dc:creator>
      <pubDate>Wed, 29 May 2019 14:39:02 +0000</pubDate>
      <link>https://forem.com/kosslebedev/typing-components-in-next-js-applications-4m5l</link>
      <guid>https://forem.com/kosslebedev/typing-components-in-next-js-applications-4m5l</guid>
      <description>&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;Note&lt;/strong&gt;: This post covers typing Next.JS applications that use versions prior to v9. Starting with version 9, Next.JS comes with its own types by default, and their names may differ from those used in DefinitelyTyped package. If you use Next.JS version 9 and older, please refer to the &lt;a href="https://nextjs.org/docs#typescript"&gt;official documentation&lt;/a&gt;. For earlier versions, continue reading :)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In this article, we'll talk about typing Next.JS components. We'll be using &lt;a href="https://github.com/koss-lebedev/nextjs-typescript"&gt;this Next.JS&lt;/a&gt; application that connects to Reddit API and displays a list of top posts in a given subreddit. Right now, the main component &lt;code&gt;Posts.tsx&lt;/code&gt; doesn't have any type-safety, so we're going to fix that.&lt;/p&gt;

&lt;p&gt;The project already contains TypeScript configured, so if you don't know how to do that, please read the official guide &lt;a href="https://github.com/zeit/next-plugins/tree/master/packages/next-typescript"&gt;here&lt;/a&gt;, it's as easy as installing a few dependencies and dropping in some configuration files.&lt;/p&gt;

&lt;p&gt;Now let's clone &lt;a href="https://github.com/koss-lebedev/nextjs-typescript"&gt;the project&lt;/a&gt; from GitHub and get started.&lt;/p&gt;

&lt;h2&gt;
  
  
  FunctionComponent
&lt;/h2&gt;

&lt;p&gt;First, let's take a look at how we type React components in general.&lt;/p&gt;

&lt;p&gt;If we write our components as functions, we can use &lt;code&gt;FunctionComponent&lt;/code&gt; type from React library. This type takes a generic type argument that describes the shape of the props. Our &lt;code&gt;Posts&lt;/code&gt; component takes a subreddit name and a list of posts, so &lt;code&gt;props&lt;/code&gt; object is going to look like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now when we destructure props into &lt;code&gt;posts&lt;/code&gt; and &lt;code&gt;subreddit&lt;/code&gt;, we get full type safety. Pretty neat, right?&lt;/p&gt;

&lt;p&gt;Now let’s look at Next.JS components.&lt;/p&gt;

&lt;h2&gt;
  
  
  NextFunctionComponent
&lt;/h2&gt;

&lt;p&gt;One thing that makes Next.JS components different is a static &lt;code&gt;getInitialProps&lt;/code&gt; function. If we try to assign it to our regular React component, we’ll get a type error:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;To fix this problem, we need to use a special component type from Next.JS package called &lt;code&gt;NextFunctionComponent&lt;/code&gt;. This type extends standard React’s &lt;code&gt;FunctionComponent&lt;/code&gt; type with Next.JS-specific static lifecycle methods (well, only one method, really). So now our code will look like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;To make our types more robust, we can &lt;em&gt;infer&lt;/em&gt; the shape of &lt;code&gt;props&lt;/code&gt; returned from &lt;code&gt;getInitialProps&lt;/code&gt; function instead of defining them manually. To do that, first, we want to extract &lt;code&gt;getInitialProps&lt;/code&gt; function into a separate variable. This step is required to avoid circular type reference when we start inferring the shape of our props:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Next, we can use &lt;code&gt;ReturnType&lt;/code&gt; helper type to get the type of the value returned from &lt;code&gt;getInitialProps&lt;/code&gt; function:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Since &lt;code&gt;getInitialProps&lt;/code&gt; function is asynchronous, the return type is going to be a promise, so we also need to extract its value. We can define a global helper type that will use conditional type magic to unwrap our promise:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now we can put everything together:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  NextContext
&lt;/h2&gt;

&lt;p&gt;Let’s make this example more interesting by taking the name of a subreddit from a query string.&lt;/p&gt;

&lt;p&gt;To achieve that, we can use a &lt;code&gt;context&lt;/code&gt; argument that gets passed to &lt;code&gt;getInitialProps&lt;/code&gt; function that we haven’t used so far. We will use &lt;code&gt;NextContext&amp;lt;T&amp;gt;&lt;/code&gt; type to type this argument. The type &lt;code&gt;T&lt;/code&gt; allows us to specify the parameters we know we will have in a query string (&lt;code&gt;subreddit&lt;/code&gt; in our case):&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;We got type-safety inside &lt;code&gt;getInitialProps&lt;/code&gt; function, but now we run into another type error talking about incompatible types of &lt;code&gt;Context&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The reason is that by default &lt;code&gt;getInitialProps&lt;/code&gt; expects a context to be of a generic type &lt;code&gt;NextContext&lt;/code&gt;, but we specified a stricter, more specific type — &lt;code&gt;NextContext&amp;lt;{ subreddit: string }&lt;/code&gt;. To resolve this issue, we need to pass a few more type arguments to &lt;code&gt;NextFunctionComponent&lt;/code&gt; type. Its full signature looks like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;As you can see, &lt;code&gt;NextFunctionComponent&lt;/code&gt; can take up to 3 types — &lt;code&gt;Props&lt;/code&gt;, &lt;code&gt;InitialProps&lt;/code&gt;, and &lt;code&gt;Context&lt;/code&gt;. &lt;code&gt;InitialProps&lt;/code&gt; should only contain props returned from &lt;code&gt;getInitialProps&lt;/code&gt; function. &lt;code&gt;Props&lt;/code&gt; should contain all the props that component has access to, which include own component props, props passed through higher order components (such as &lt;code&gt;connect&lt;/code&gt; from Redux), plus the initial props. And finally, &lt;code&gt;Context&lt;/code&gt; specifies the shape of the context used by our component.&lt;/p&gt;

&lt;p&gt;When we put everything together, we’ll get a fully typed Next.JS component&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;You can find the source code for the fully typed component in &lt;a href="https://github.com/koss-lebedev/nextjs-typescript/tree/final"&gt;"final" branch&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this article, we've explored how to type Next.JS components. The approach is different from typing regular React functional components because of the special &lt;code&gt;getInitialProps&lt;/code&gt; function that Next.JS uses to prepare props data server-side. For that reason, we need to use special &lt;code&gt;NextFunctionComponent&lt;/code&gt; and &lt;code&gt;NextContext&lt;/code&gt; types that come with Next.JS typing package.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PS&lt;/strong&gt;: If you’re curious why we used type aliases everywhere instead of interfaces, make sure to check &lt;a href="https://konstantinlebedev.com/type-aliases-vs-interfaces/"&gt;this article&lt;/a&gt;.&lt;/p&gt;




&lt;p&gt;&lt;strong&gt;Shameless plug&lt;/strong&gt;: if you want to learn how to use Redux without writing a ton of boilerplate, check my &lt;a href="https://www.youtube.com/playlist?list=PLNG2YBDrzK-w1VSeDpMxdGwkb4L6hDy8Z"&gt;"State management with Rematch" course&lt;/a&gt; on Youtube.&lt;/p&gt;

&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/f06elAAbb60"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>nextjs</category>
      <category>react</category>
    </item>
  </channel>
</rss>
