<?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 Michael Pautov on Medium]]></title>
        <description><![CDATA[Stories by Michael Pautov on Medium]]></description>
        <link>https://medium.com/@michael-pautov?source=rss-1ab426232cb7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hsGaK07EM91V-NZDn-vO4A.jpeg</url>
            <title>Stories by Michael Pautov on Medium</title>
            <link>https://medium.com/@michael-pautov?source=rss-1ab426232cb7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 20:51:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@michael-pautov/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[TypeScript 4.0! What is New?]]></title>
            <link>https://michael-pautov.medium.com/typescript-4-0-what-is-new-3cf8b996bc19?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cf8b996bc19</guid>
            <category><![CDATA[microsoft]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript-4]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Wed, 28 Oct 2020 05:18:18 GMT</pubDate>
            <atom:updated>2020-10-28T05:18:18.474Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mIrt2DeQMpXqhlOqAA-_A.jpeg" /></figure><p>It is time to see the best things about the new Typescript 4.0. Recently, Microsoft announced a new version that will enhance the productivity and efficiency of the language. Of course, all of us now know about the Typescript (that’s why you are here, right?). For the people who want a quick overview, here it is. Typescript is a language that is built over JavaScript. Here, you will get many new things that you are waiting for.</p><p>Let’s get into our main topic that is about the new things in TypeScript 4.0</p><p>You will get the following things</p><ul><li>Better Editor with new improvements</li><li>Labeled Tuple Elements</li><li>Variadic tuple types</li><li>Custom JSX factories</li><li>Class property interference directly from Constructors</li><li>Short-circuiting assignment operators</li><li>Unknown on Catch clauses</li><li>— incremental with — noEmit</li></ul><p>That’s not all, they have also got a new website where you can find more information about the language. Some of these are self-explanatory whereas some of them need an overview. Let’s get into that.</p><h3>Editor Improvements</h3><p>One of the biggest issues that the editor faced was regarding optional chaining. The website just broke if the developer didn’t use proper chaining. This happened with the fields such as address. Now, the new TypeScript 4.0 can suggest you convert it to option chaining.</p><p>The next change is the partial semantic mode at startup. This will improve the opening time (no more waiting in big projects). Of course, there is a smart import that can auto-import the files.</p><p>Also, TypeScript now supports /**@deprecated **/</p><h3>Tuple</h3><p>There are two new things regarding tuple. One of them is the variadic tuple type.</p><p>Let’s say, there are various tuple types in the code. The type of the tuple is unknown. The new TypeScript will assign it as an array type. Further, TS 4 can also count the number of types.</p><p>It allows the developers to label the tuple. This has various usage. It will decrease the code complexity and it will also decrease the load. The auto-suggestion will only show the type name. The developer can then choose the type they want.</p><h3>Class Properties and Catch Clauses</h3><p>The developers can now use the unknown on catch clauses. It helps with the entire error handling problem. This will enhance your try..catch block a little more.</p><p>Further, you can also access the class properties from the constructor. In simpler words, a constructor can also analyze the path of the class. Isn’t this amazing? This will also increase the security of the code along with the efforts.</p><h3>Compound Operators</h3><p>The next best thing about TS 4 is the compound operators. Like we mentioned earlier, you can now use three more compound operators that were previously now supported.</p><p>The three compound operators are logical and (&amp;&amp;), logical or (||), and nullish coalescing (??).</p><p>Many developers who are costly using them will find TS more amazing.</p><h3>The Website</h3><p>Last but not the least, they have also announced the official website. You can see the docs from there or you can also talk with the developer’s community. There is a handbook if you are new to TypeScript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cf8b996bc19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Most useful methods of ‘ramda.js’]]></title>
            <link>https://michael-pautov.medium.com/most-useful-methods-of-ramda-js-f4c9d587fd0b?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c9d587fd0b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[top-ramda-js-functions]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[ramda]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Sat, 05 Sep 2020 13:09:11 GMT</pubDate>
            <atom:updated>2020-09-05T13:09:11.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nz0yZfc2VvdluCl0-knoMg.jpeg" /></figure><p>List of methods:</p><ol><li><a href="#ccb9">Pluck</a></li><li><a href="#4064">ApplySpec</a></li><li><a href="#bc45">Cond</a></li><li><a href="#93eb">PropEq</a></li><li><a href="#455a">Pipe</a></li><li><a href="#d56d">FromPairs</a></li><li><a href="#cbff">PathOr</a></li></ol><h3>Pluck</h3><p>Using all the time. Go throw the array and take the value which we put as the key</p><pre>const getAges = R.pluck(‘age’);</pre><pre>getAges([{name: ‘fred’, age: 29}, {name: ‘wilma’, age: 27}]); //=&gt; [29, 27]</pre><h3>ApplySpec</h3><p>The gold key when we would like to format or translate our values of the object</p><pre>const getTranslated = R.applySpec({</pre><pre>  header: i18n.translate,</pre><pre>  content: i18n.translate</pre><pre>});</pre><pre>getTranslated(article); //=&gt; {header: ‘Translated header’, content: ‘Translated content’}</pre><h3>Cond</h3><p>The devilish replacement for all the mad “switch” and all the awful if / else cases.</p><pre>const fn = R.cond([</pre><pre>  [R.equals(0), R.always(‘water freezes at 0°C’)],</pre><pre>  [R.equals(100), R.always(‘water boils at 100°C’)],</pre><pre>  [R.T, temp =&gt; ‘nothing special happens at ‘ + temp + ‘°C’]</pre><pre>]);</pre><pre>fn(0); //=&gt; ‘water freezes at 0°C’</pre><pre>fn(50); //=&gt; ‘nothing special happens at 50°C’</pre><pre>fn(100); //=&gt; ‘water boils at 100°C’</pre><h3>PropEq</h3><p>Helps to sort and filter the list of data</p><pre>const abby = {name: ‘Abby’, age: 7, hair: ‘blond’};</pre><pre>const fred = {name: ‘Fred’, age: 12, hair: ‘brown’};</pre><pre>const rusty = {name: ‘Rusty’, age: 10, hair: ‘brown’};</pre><pre>const alois = {name: ‘Alois’, age: 15, disposition: ‘surly’};</pre><pre>const kids = [abby, fred, rusty, alois];</pre><pre>const hasBrownHair = R.propEq(‘hair’, ‘brown’);</pre><pre>R.filter(hasBrownHair, kids); //=&gt; [fred, rusty]</pre><h3>Pipe</h3><p>Helper for implementation graceful functions</p><pre>const getFirstFiveBooks = R.pipe(</pre><pre>   R.filter(propEq(‘type’, ‘book’),</pre><pre>   R.path(‘bookInfo’),</pre><pre>   R.take(5)</pre><pre>);</pre><h3>FromPairs</h3><p>From array to object</p><pre>R.fromPairs([[‘a’, 1], [‘b’, 2], [‘c’, 3]]); //=&gt; {a: 1, b: 2, c: 3}</pre><h3>PathOr</h3><p>When you not sure about your path of the object</p><pre>R.pathOr(‘N/A’, [‘a’, ‘b’], {a: {b: 2}}); //=&gt; 2</pre><pre>R.pathOr(‘N/A’, [‘a’, ‘b’], {c: {b: 2}}); //=&gt; “N/A”</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c9d587fd0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 10 Interview Questions Related To React Hooks]]></title>
            <link>https://michael-pautov.medium.com/top-10-interview-questions-related-to-react-hooks-dfdada3c0040?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfdada3c0040</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Mon, 27 Jul 2020 05:32:12 GMT</pubDate>
            <atom:updated>2020-07-27T05:32:12.286Z</atom:updated>
            <content:encoded><![CDATA[<p>React is an incredibly versatile JavaScript framework that allows developers to create intuitive interfaces for web applications. A React developer earns <a href="https://arc.dev/hire-developers/reactjs">$57 per hour on average</a> plus they are widely sought after in the market. React was introduced by Facebook and it is a favorite of many web developers in the world.</p><p>In this article, we will be going over the top 10 interview questions related to React Hooks, which were introduced in ver 16.8 to address some issues within the framework.</p><h3>Q1. What Are React Hooks?</h3><p>These are in-built functions that allow developers to use state and lifecycle methods within components in React. Each component’s lifecycle has 3 phases which are mount, unmount, and update. Alongside that, components have states and properties. Hooks allow developers to use these methods whilst improving code reuse with greater flexibility navigating the component tree.</p><h3>Q2. What is the primary benefit of Hooks?</h3><p>Through Hooks, you can code in React without using classes. With Hooks, you can reuse existing states in your code plus easily test them later on for errors and bugs in the code. Through the use of Hooks, you can tightly couple logic in the code on React.</p><h3>Q3. What Are The 2 Rules You Must Follow While Using Hooks?</h3><p>There are 2 rules which are imposed while you are coding with Hooks:</p><ol><li>React Hooks should only be called at the Top Level. They shouldn’t be called inside loops, nested functions or conditions.</li><li>Hooks can only be called from React Function Components.</li></ol><h3>Q4. What is the difference between setState() and useEffect() in React?</h3><p>Simply put, setState() allows programmers to set the state of functional components whereas the useEffect() method allows programmers to use lifecycle methods to React.</p><h3>Q5. Explain State Hook with an example</h3><p>State Hooks are primarily used to refer to the states of the components in React and can be used to change them on the runtime as per the functionality of your web application. An example below increments a counter on click of a button:</p><pre>function Counter() {<br><br>  const [count, setCount] = useState(0)<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increment Counter<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>In the above example, we declare a constant count whose state initially is 0. Depending on how many times the button on the webpage is clicked, the count variable will be incremented that many times.</p><h3>Q6. Is it possible to use both classes and Hooks in my React Code?</h3><p>While Hooks cannot be a part of classes, you can use both within your React Web applications as you wish. Existing React applications will continue to work fine and there are no plans of removing classes from React in the near future. However, Hooks offer greater flexibility and easier code understanding therefore your company or organization should quickly transition to it.</p><h3>Q7. Do Hooks work with static typing?</h3><p>Static typing is a process of checking code during compile time to ensure that all variables are statically typed. Hooks are primarily functions and have been designed in a way to ensure that all attributes are statically typed. You can also use the React API with custom Hooks if you want to enforce stricter static typing within your code.</p><h3>Q8. What functionalities that are provided by classes and are not covered by Hooks yet?</h3><p>The following methods have not been introduced in Hooks yet:</p><ol><li>getSnapshotBeforeUpdate</li><li>getDerivedStateFromError</li><li>componentDidCatch</li></ol><p>These are uncommon lifecycles, however. Furthermore, Hooks may not be compatible with certain third-party libraries.</p><h3>Q9. How do you use multiple states with Hooks?</h3><p>The example below illustrates the use of multiple states with React Hooks:</p><pre>function MultipleStates() {<br>  // Declare multiple state variables!<br>  const [car_model, setModel] = useState(1998);<br>  const [car_name, setName] = useState(&#39;Toyota Corolla&#39;);<br>  const [car_price, setPrice] = useState(600000);<br>  // ...<br>}</pre><p>As you can see, we have declared multiple states within a single function. We have the car price, model, and name in a single function MultipleStates() above.</p><h3>Q10. Explain Effect Hook with an example</h3><p>If an action is performed on a webpage, an Effect Hook may be used to transfer a side effect to another part of the DOM. The example below updates the document title of the webpage when a button is clicked:</p><pre>function Effect() {<br>  const [car, setcar] = useState(&#39;Ferrari&#39;);<br>  useEffect(() =&gt; {<br><br>    <strong><em>document</em></strong>.title = `My favorite car is ${car}`;<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;My favorite car is {car}&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setcar(&#39;McLaren&#39;)}&gt;<br>        Not this one?<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The above example changes the favorite car of the user from Ferrari to McLaren upon the click of a button. The effect of the change is also transferred using useEffect()to the document title and it is also updated simultaneously.</p><p>In essence, useEffect() is replacing componentDidMount and componentDidUpdate in this code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfdada3c0040" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When to use Storybook?]]></title>
            <link>https://michael-pautov.medium.com/when-to-use-storybook-92ed45117d9b?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/92ed45117d9b</guid>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[isolation]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[components]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Wed, 08 Jul 2020 05:03:55 GMT</pubDate>
            <atom:updated>2020-07-08T05:03:55.317Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ktvRPr3IDYCFcBjXuqg0xg.png" /></figure><p>User Interface has become an essential part of modern development. Several technologies are used together to create attractive and high-performing user interfaces. Creating a simple user interface, with few screens is not a big deal, but as the application grows, the user interface becomes more and more complicated.</p><p>The Storybook is a tool that is very helpful while working user interface components. It is basically a development environment in which a developer can create components in an organized manner in isolation.</p><p>In this article, we will discuss when to use the storybook.</p><h3>1. When you need to develop components in isolation</h3><p>Suppose you are working on a component and this component is to be added to another component which is not ready yet. Say, you need to add a button to a web page but that page is not fully completed. So you have to wait until it is completed and then you can start working on the button. But with the storybook, it is not required to wait because it works completely independently from the real application. You can create the button without even bothering about the pending web page.</p><p>You can run the storybook on a separate port on your localhost and create your component there.</p><h3>2. When there is a need to manage edge test cases</h3><p>With a vast range of components, there is always a vast range of edge test cases. There can be several test cases for even small components, such as a button, leave the whole application alone.</p><p>For example, there is a button and the text on it can change. For one case, the text can be very long and for another, there is no text. You need to adjust the size of the button according to the length of the text. You may need to apply particular CSS properties for a particular length. Storybook has a brilliant facility that provides visuals of such test cases. With such visuality, it becomes easy to manage edge test cases.</p><h3>3. When there is a need to create awareness regarding the components</h3><p>You may encounter a situation when multiple developers are working on a single component. Each of them adds the same functionality that is already present. Or, there is a component created by a developer several months ago and the new developer wants the same functionality but he is not aware of the existing component, so he creates a new one. There can be numerous such situations where developers are unaware of the existing components or functionalities, so they start creating a new one.</p><p>Using the storybook, you can create a story of a particular component. Each of these stories is basically documentation that contains the visual state of a component. The documentation helps in creating awareness for everyone who is working on the application.</p><h3>## Conclusion</h3><p>So these are the situations in which you should your storybook. It is a very helpful tool when you need to create components in isolation and there are several edge test cases.</p><p>A huge application always creates confusion among the developers, but with the story facility in the storybook, you can easily create visual documentation that can help eliminate such confusion. Moreover, it has a number add-on that is very useful while creating components.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92ed45117d9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Как использовать React.memo и useCallback]]></title>
            <link>https://michael-pautov.medium.com/%D0%BA%D0%B0%D0%BA-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D1%82%D1%8C-react-memo-%D0%B8-usecallback-d6c2f134821?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c2f134821</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[perfomance]]></category>
            <category><![CDATA[react-memo]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 03:40:13 GMT</pubDate>
            <atom:updated>2020-07-01T03:40:13.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_i_o8ZAou0G49nUUV8zqQ.jpeg" /></figure><p>В этой статье расскажу о том когда и как использовать <strong>React.memo</strong> и хук <strong>useCallback</strong>. После этой статьи поймете в каких случаях используют <strong>useCallback</strong>. Узнаете как работает между собой <strong>React.Memo</strong> и <strong>useCallback</strong>.</p><h4>Кратко о React.memo и useCallback</h4><p><strong>React.Memo</strong> — компонент высшего порядка. Похож на <strong>React.PureComponent</strong>, но предназначен для функциональных компонентов.</p><blockquote>Вторым аргументом React.Memo есть возможность передать функцию которая будет принимать решение ре-рендерить компонент на основе предыдущих и нынешних props</blockquote><p>Компонент высшего порядка<strong> </strong>— функция принимает дочерний компонент и параметры, и затем создаёт контейнер поверх дочернего компонента.</p><p><strong>React.PureComponent</strong> — схож с React.Component, но единственная разница в методе <strong>shouldComponentUpdate</strong>.</p><blockquote>В PureComponent <strong>сравнивает новые значения с предыдущими</strong> и возвращает результат сравнения. React.Component — возвращает <strong>true</strong></blockquote><p><strong>useCallback</strong> — хук вернёт мемоизированную функцию колбэка, который изменяется только, если изменяются значения из зависимостей.</p><h4>Примеры использования</h4><p><strong>Base</strong> — не использует React.Memo. Компонент будет рендерится <strong>каждый раз</strong></p><pre>let count = 0<br>export default function Base({ action }) {<br>  <strong><em>console</em></strong>.log(`${++count} Base component`)<br>  return &lt;h3 onClick={action}&gt;Base&lt;/h3&gt;<br>}</pre><p><strong>Memo</strong> — использует React.Memo. Компонент будет рендерится <strong>каждый раз когда меняются свойства</strong></p><pre>let count = 0<br>export default React.memo(function Memo({ action }) {<br>  <strong><em>console</em></strong>.log(`${++count} Memo component`)<br>  return &lt;h3 onClick={action}&gt;Memo&lt;/h3&gt;<br>})</pre><p><strong>NoUseCallback</strong> — не используем useCallback. Рендерится Base и Memo компоненты <strong>каждый раз</strong></p><pre>export default function NoUseCallback() {<br>  const [a, setA] = useState(&#39;&#39;)<br>  const [b, setB] = useState(&#39;&#39;)<br><br>  useEffect(() =&gt; {<br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value not related to action&#39;)<br>      setA(&#39;a&#39;)<br>    }, 1000)<br><br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value related to action&#39;)<br>      setB(&#39;b&#39;)<br>    }, 3000)<br>  }, [])<br><br>  const action = () =&gt; <strong><em>console</em></strong>.log(b)<br>  return (<br>      &lt;&gt;<br>        &lt;Base action={action} /&gt;<br>        &lt;Memo action={action} /&gt;<br>      &lt;/&gt;<br>  );<br>}</pre><p><strong>Console:</strong></p><pre>1 Base component<br>1 Memo component<br>change value not related to action<br>2 Base component<br>2 Memo component<br>change value related to action<br>3 Base component<br>3 Memo component</pre><p><strong>UseCallback</strong> — используем useCallback метод. <strong>Рендерится Base 3 и Memo 2 раза</strong></p><pre>export default function UseCallback() {<br>  const [a, setA] = useState(&#39;&#39;)<br>  const [b, setB] = useState(&#39;&#39;)<br><br>  useEffect(() =&gt; {<br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value not related to action&#39;)<br>      setA(&#39;a&#39;)<br>    }, 1000)<br><br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value related to action&#39;)<br>      setB(&#39;b&#39;)<br>    }, 3000)<br>  }, [])<br><br>  const action = useCallback(() =&gt; {<br>    <strong><em>console</em></strong>.log(b)<br>  }, [b]);<br><br>  return (<br>      &lt;&gt;<br>        &lt;Memo action={action} /&gt;<br>        &lt;Base action={action} /&gt;<br>      &lt;/&gt;<br>  );<br>}</pre><p><strong>Console:</strong></p><pre>1 Memo component<br>1 Base component<br>change value not related to action<br>2 Base component<br>change value related to action<br>2 Memo component<br>3 Base component</pre><h4>Заключение</h4><p>Используем <strong>React.Memo</strong> когда хотим что бы компонент ререндерился когда меняются props или конкретные props. <br>Оборачиваем функцию в <strong>useCallback</strong> когда передаем другим компонентам или когда используются внешние переменные</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c2f134821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use React.memo and useCallback]]></title>
            <link>https://michael-pautov.medium.com/how-to-use-react-memo-and-usecallback-f153868cacda?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f153868cacda</guid>
            <category><![CDATA[react-memo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[usecallback]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 03:29:35 GMT</pubDate>
            <atom:updated>2020-07-01T03:29:35.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A_i_o8ZAou0G49nUUV8zqQ.jpeg" /></figure><p>In this article, I’ll talk about when and how to use <strong>React.memo</strong> and the <strong>useCallback</strong> hook. After this article, you will understand when to use <strong>useCallback</strong>. Learn how <strong>React.Memo</strong> and useCallback work together.</p><h4>Briefly about React.memo and useCallback</h4><p><strong>React.Memo</strong> is a higher-order component. Similar to <strong>React.PureComponent</strong>, but intended for functional components.</p><blockquote>The second argument of React.Memo is the ability to pass a function that will decide to re-render the component based on previous and current props</blockquote><p>Higher-order component — the function takes a child component and parameters, and then creates a container on top of the child component.</p><p><strong>React.PureComponent </strong>— similar to React.Component, but the only difference in the shouldComponentUpdate method.</p><blockquote>The <strong>PureComponent</strong> compares new values ​​with previous ones and returns the result of the comparison. React.Component — returns true</blockquote><p><strong>useCallback</strong> — the hook will return a memoized callback function, which changes only if the values ​​from the dependencies change.</p><h4>Examples</h4><p><strong>Base</strong> — Doesn’t use React.Memo. The component will be rendered <strong>every time</strong>.</p><pre>let count = 0<br>export default function Base({ action }) {<br>  <strong><em>console</em></strong>.log(`${++count} Base component`)<br>  return &lt;h3 onClick={action}&gt;Base&lt;/h3&gt;<br>}</pre><p><strong>Memo</strong> — uses React.Memo. The component will be rendered <strong>every time the properties change</strong>.</p><pre>let count = 0<br>export default React.memo(function Memo({ action }) {<br>  <strong><em>console</em></strong>.log(`${++count} Memo component`)<br>  return &lt;h3 onClick={action}&gt;Memo&lt;/h3&gt;<br>})</pre><p><strong>NoUseCallback</strong> — do not use useCallback. Base and Memo components are rendered<strong> every time</strong></p><pre>export default function NoUseCallback() {<br>  const [a, setA] = useState(&#39;&#39;)<br>  const [b, setB] = useState(&#39;&#39;)<br><br>  useEffect(() =&gt; {<br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value not related to action&#39;)<br>      setA(&#39;a&#39;)<br>    }, 1000)<br><br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value related to action&#39;)<br>      setB(&#39;b&#39;)<br>    }, 3000)<br>  }, [])<br><br>  const action = () =&gt; <strong><em>console</em></strong>.log(b)<br>  return (<br>      &lt;&gt;<br>        &lt;Base action={action} /&gt;<br>        &lt;Memo action={action} /&gt;<br>      &lt;/&gt;<br>  );<br>}</pre><p><strong>Console:</strong></p><pre>1 Base component<br>1 Memo component<br>change value not related to action<br>2 Base component<br>2 Memo component<br>change value related to action<br>3 Base component<br>3 Memo component</pre><p><strong>UseCallback</strong> — use the useCallback method. <strong>Rendered Base 3 and Memo 2 times</strong></p><pre>export default function UseCallback() {<br>  const [a, setA] = useState(&#39;&#39;)<br>  const [b, setB] = useState(&#39;&#39;)<br><br>  useEffect(() =&gt; {<br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value not related to action&#39;)<br>      setA(&#39;a&#39;)<br>    }, 1000)<br><br>    setTimeout(() =&gt; {<br>      <strong><em>console</em></strong>.log(&#39;change value related to action&#39;)<br>      setB(&#39;b&#39;)<br>    }, 3000)<br>  }, [])<br><br>  const action = useCallback(() =&gt; {<br>    <strong><em>console</em></strong>.log(b)<br>  }, [b]);<br><br>  return (<br>      &lt;&gt;<br>        &lt;Memo action={action} /&gt;<br>        &lt;Base action={action} /&gt;<br>      &lt;/&gt;<br>  );<br>}</pre><p><strong>Console:</strong></p><pre>1 Memo component<br>1 Base component<br>change value not related to action<br>2 Base component<br>change value related to action<br>2 Memo component<br>3 Base component</pre><h4>Conclusion</h4><p>We use <strong>React.Memo</strong> when we want the component to be re-rendered when props or specific props change.<br>We wrap the function in <strong>useCallback</strong> when we pass it to other components or when external variables are used</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f153868cacda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Micro and Macro tasks in JavaScript]]></title>
            <link>https://michael-pautov.medium.com/micro-and-macro-tasks-in-javascript-4c556a3ea18c?source=rss-1ab426232cb7------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c556a3ea18c</guid>
            <category><![CDATA[javascript-event-loop]]></category>
            <category><![CDATA[micro-and-macro]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Michael Pautov]]></dc:creator>
            <pubDate>Mon, 29 Jun 2020 05:00:22 GMT</pubDate>
            <atom:updated>2020-06-29T05:00:22.498Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2SAky0uYt6sTy9RkiyOEg.jpeg" /></figure><p>Multithreading is what made great computing speeds possible. Today, it is a compulsory feature in all operating systems and programming languages. While even the old languages like C++ added built-in thread support in the somewhat latest updates, JavaScript remained stubborn.</p><p>But multithreading was needed in browsers nonetheless, so the concept of event loop is used to perform asynchronous functions in JavaScript. Event loop monitors message queue and the execution stack to make sure callback functions are executed as soon as the execution stack is empty. The callback functions are further divided into micro-tasks and macro-tasks.</p><p>We will look at the difference and need for micro and macro tasks in JavaScript in this article. Let’s start with the supporting concepts.</p><h3>Execution Stack</h3><p>The environment in which a JavaScript code element runs in is called an execution context. It stores all the local variables for the code block and evaluation criteria. Every function receives a new execution context as soon as it is called. These execution contexts are stored on top of each other in a container like object called the execution stack.</p><h3>Message Queue</h3><p>When a callback function is called in an existing execution context, it is pushed to the message queue. They remain in the queue until the execution stack is empty which is when the event loop finally executes these tasks. Reading the code, Queueing up the tasks, and execution of the tasks is done by the event loop.</p><p>This message queue is what actually makes these tasks asynchronous and thus helps JavaScript programmers implement multithreading. But as it is seen, all tasks in the message queue are not created and treated equally. They are further divided into two queues; micro-task queue and macro-task queue.</p><h3>Micro-tasks and Macro-tasks</h3><p>Simply speaking, micro-tasks are used to create a queue of synchronous tasks inside the message queue which is executed asynchronously with the execution stack.</p><h3>How are micro and macro tasks executed?</h3><p>An event loop has a task queue which is the macro-task queue. Once it starts executing the callback functions in the message queue, it takes one macro-task, executes it and goes to execute the micro-task queue. It keeps executing the micro-task queue until it is finished. Then it goes back to the macro-tasks (task) queue and executes another one.</p><p>It might happen that each micro-task keep queuing up more micro-tasks and we are stuck in an infinite loop. To avoid this, JavaScript limits the number of micro-tasks that can be executed simultaneously to 1000. After 1000 micro-tasks, it has to pick up a macro-task and then come back to the micro-task queue.</p><p>Render is also blocked while the micro-tasks are executing to keep the UI intact for the user. So if we are stuck in the micro-task queue for too long, the page might become unresponsive.</p><h3>How to divide micro and macro tasks?</h3><p>It is advised to the programmers to use micro-tasks when you want to perform some functions synchronously in an asynchronous manner. Otherwise, it is best to use macro-tasks.</p><p>Few examples of macro-tasks are setTimeout, setInterval, setImmediate, I/O tasks, UI rendering. While promises are micro-tasks as they are executed as soon as their constructor is invoked.</p><h3>Wrapping up</h3><p>We discussed the differences, merits, demerits, and examples of micro and macro tasks in JavaScript. We also touched a bit upon how they are used to implement multi-threading in browsers using JS. Hope this clears any confusion that you might have had regarding the topic. If you’ve got any more questions, feel free to ask in the comments below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c556a3ea18c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>