<?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 Iurii Komarov on Medium]]></title>
        <description><![CDATA[Stories by Iurii Komarov on Medium]]></description>
        <link>https://medium.com/@iuriikomarov?source=rss-778f4206c10e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rsgBO1YOwsRvUmeReTAgpA.jpeg</url>
            <title>Stories by Iurii Komarov on Medium</title>
            <link>https://medium.com/@iuriikomarov?source=rss-778f4206c10e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 23:12:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iuriikomarov/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[Enums in TypeScript]]></title>
            <link>https://medium.com/@iuriikomarov/enums-in-typescript-9295b6b63fee?source=rss-778f4206c10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9295b6b63fee</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Iurii Komarov]]></dc:creator>
            <pubDate>Sun, 07 Jun 2020 10:40:40 GMT</pubDate>
            <atom:updated>2020-06-07T11:09:12.251Z</atom:updated>
            <content:encoded><![CDATA[<p>There are three ways how to represent enumerated values in TypeScript and it’s not always clear for newcomers which one to use.</p><p>Union string types are most popular between folks who came from JavaScript:</p><pre>type Role = &quot;anonymous&quot; | &quot;user&quot;</pre><pre>function greeting(role: Role): string {<br>    switch (role) {<br>        case &quot;anonymous&quot;:<br>            return &quot;Hi&quot;<br>        case &quot;user&quot;:<br>            return &quot;Welcome back there&quot;<br>    }<br>}</pre><p>Enums are more idiomatic and have better IDE support:</p><pre>enum Role { Anonymous, User }</pre><pre>function greeting(role: Role): string {<br>    switch (role) {<br>        case Role.Anonymous:<br>            return &quot;Hi&quot;<br>        case Role.User:<br>            return &quot;Welcome back there&quot;<br>    }<br>}</pre><p>And finally, const enums are almost the same except const keyword in front of enum declaration statement.</p><p>I advise you to start using const enums in any TS project and the reason is quite obvious: <em>they may be optionally be preserved or not in compiled JavaScript using </em><em>preserveConstEnums compiler flag</em>.</p><p>Why does it make sense?</p><p>As you may know, all the compile-time programming abstractions language can propose (<a href="https://blog.rust-lang.org/2015/05/11/traits.html">almost</a>) always will have some runtime price measured in bytes of memory our program consumes. In the case of isomorphic web applications that price is being paid twice and unfortunately, traffic bytes may cost you much more <a href="https://web.dev/interactive/">UX/SEO points</a> than physical costs for memory-hungry server nodes.</p><p>Notating enumerated values in language syntax tokens allows a compiler to represent that values as integers, what TypeScript compiler actually does unless you specify <a href="https://www.typescriptlang.org/docs/handbook/enums.html#string-enums">string runtime representations</a> for them explicitly.</p><p>Compare generated JavaScript for <a href="https://www.typescriptlang.org/play/index.html?ssl=10&amp;ssc=2&amp;pln=1&amp;pc=1#code/C4TwDgpgBASg9gG2gXigIgIYDs5ZAWzgFcBnNKAH3VIgCc0AoBgMyKwGNgBLXKAc1oQI3LHwAUtRBABcsKQEpZJYLS6ioAbwYBIEgHcuwdgAsoEhZp3b2GEtEw48hUmmlXtg4EVpZ0ACS5GbW0oGztqO3o3YI9hb180AHUIBHY4fGgAIwx2AGsoYGM6CCCAXwZyhjSsEikAOgATCEyicQdcAmIyeSrcWqRG5taxNBp6eSA">union string types</a>, <a href="https://www.typescriptlang.org/play/index.html?ssl=16&amp;ssc=1&amp;pln=1&amp;pc=1#code/KYOwrgtgBASg9gG2FA3gKCpqBBEcQCeEcYAzgDQZYCqpwATpQL5poBmYIAxgC4CW+KAHN6wYPxBCAFPUTAAXLDkBKVFUykA7nx5cAFlBkq1WU1C4BDOkqQA6XPiIlS89WdNd8pObYAmwACMwaQAiAAk+AEIQ5Td3TFEeMHoQOKxLa3g7WgZXeLNPEG87fyDQiPIoMgZo2PzTROTU0xYWNELi4D9A4KksrodCYjJYjp9S3v7bHPplIA">enums</a>, <a href="https://www.typescriptlang.org/play/index.html?preserveConstEnums=true#code/MYewdgzgLgBApmArgWxgJRAGzjA3gKBiJgEExwBPZERCAGkOIFUI4AnBgX33wDNEwwKAEtwMAOZs4cEWHEAKNljgAudMoCUeRkQgB3YVGAALGIs3biVmMACGrddgB0ZStVoqd1q6EjKnACZwAEaICgBEABLCAIThGl7eRFJQiGxgicR2DhjOLOyeSda+EP5BoRHRdDC07HEJRVYpaRlW3Nz4JWUhYfK5cC7kYFQ0EAldzuW9-U75bAlAA">const enums with </a><a href="https://www.typescriptlang.org/play/index.html?preserveConstEnums=true#code/MYewdgzgLgBApmArgWxgJRAGzjA3gKBiJgEExwBPZERCAGkOIFUI4AnBgX33wDNEwwKAEtwMAOZs4cEWHEAKNljgAudMoCUeRkQgB3YVGAALGIs3biVmMACGrddgB0ZStVoqd1q6EjKnACZwAEaICgBEABLCAIThGl7eRFJQiGxgicR2DhjOLOyeSda+EP5BoRHRdDC07HEJRVYpaRlW3Nz4JWUhYfK5cC7kYFQ0EAldzuW9-U75bAlAA">preserveConstEnums flag on</a>, and <a href="https://www.typescriptlang.org/play/index.html#code/MYewdgzgLgBApmArgWxgJRAGzjA3gKBiJgEExwBPZERCAGkOIFUI4AnBgX33wDNEwwKAEtwMAOZs4cEWHEAKNljgAudMoCUeRkQgB3YVGAALGIs3biVmMACGrddgB0ZStVoqd1q6EjKnACZwAEaICgBEABLCAIThGl7eRFJQiGxgicR2DhjOLOyeSda+EP5BoRHRdDC07HEJRVYpaRlW3Nz4JWUhYfK5cC7kYFQ0EAldzuW9-U75bBpAA">default const enums</a>.</p><p>As you may see, the first one is most memory-inefficient since JavaScript will create “anonymous” and “user” string literals each time when you refer to Role values. Your program may explode to thousands of such literals which may be mapped to kilobytes of bundled source code which will be delivered millions of times over the slow 3G networks affecting your application performance metrics.</p><p>The last one is much better since all the enum values do not have string representations at all and 13 bytes needed to store “anonymous” and “user” strings are dramatically reduce to 2 bytes of two integers in a JavaScript bundle.</p><p>Why you may need to preserve string representation of const enums in runtime? Well, the most common cases are projects in a state if migration from JavaScript to TypeScript codebase, so sometimes you may need to import TS-generated enums to ES-compliant ecosystem and use them as plain JavaScript objects. In such a case, enum values strings are being created only once as JavaScript object values and being just referenced from ES modules. You do not pollute your memory and JavaScript bundles with thousands of repeating literals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9295b6b63fee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Periodically call function in mounted React component with a hook]]></title>
            <link>https://medium.com/@iuriikomarov/periodically-call-function-in-mounted-react-component-with-a-hook-3653e934ee07?source=rss-778f4206c10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3653e934ee07</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Iurii Komarov]]></dc:creator>
            <pubDate>Thu, 04 Jun 2020 11:33:47 GMT</pubDate>
            <atom:updated>2020-06-04T11:35:42.367Z</atom:updated>
            <content:encoded><![CDATA[<h3>Periodically call function in a mounted React component with a hook</h3><p>It wasn’t easy to find a working solution on how to run a memo-safe function periodically from a functional component.</p><p>Saying about “memo safety” I mean cases when target function refers to component state (which is changing over time).</p><p>I decided to skip memoization at all since:</p><ol><li>Using target function arguments as predicates is very expensive in JavaScript when they (arguments) are not scalars. Object instances <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness">equality will always be an open issue</a> in JavaScript so comparing immutable predicates for proper usage of useMemo or useEffect in most cases may be heavier operation than calling few extra non-memoized callbacks (if you are not dealing with animation of course).</li><li>I walked through my current project codebase and literally didn’t find any target function that needs to be used in such hook and which does not refer to a caller component state.</li></ol><p>Here comes my hook:</p><pre>const isInFocus = () =&gt; (<br>    document === undefined ||<br>    document.visibilityState === undefined<br>    ) ? true : document.visibilityState === &quot;visible&quot;</pre><pre>function useClock(<br>    func: Function,<br>    delay: number,<br>    skipUnfocused = false<br>): void {<br>    const funcRef = React.useRef&lt;Maybe&lt;Function&gt;&gt;()</pre><pre>    React.useEffect(() =&gt; { funcRef.current = func }, [func])<br>    <br>    React.useEffect(() =&gt; {<br>        const exec = () =&gt; {<br>            if (<br>                !funcRef.current ||<br>                (skipUnfocused &amp;&amp; !isInFocus())<br>            ) return<br>            funcRef.current()<br>        }<br>        const i = setInterval(exec, delay)</pre><pre>        return () =&gt; clearInterval(i)<br>     }, [delay])<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3653e934ee07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Derived states in functional React]]></title>
            <link>https://medium.com/@iuriikomarov/derived-states-in-functional-react-b7e003e72c9b?source=rss-778f4206c10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7e003e72c9b</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <dc:creator><![CDATA[Iurii Komarov]]></dc:creator>
            <pubDate>Thu, 04 Jun 2020 11:01:25 GMT</pubDate>
            <atom:updated>2020-06-26T14:13:16.820Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*hpZGrE_JlkAlFHp7-twsMQ.jpeg" /><figcaption>Mekong Delta by NASA</figcaption></figure><p>React offers an excellent design approach for building stateful components that may <em>infer their values from parent components</em>.</p><p>We say that component implements <a href="https://reactjs.org/docs/forms.html#controlled-components">controlled design</a> when it’s completely stateless and infers value from its parent and all it can do is to render the value in a way it needs to (well, and to call some function defined in a parent component when rendered value changes as a result of some user actions). This design is completely straightforward and easy to understand but actually, the only one problem such a component can <strong>incapsulate and solve</strong> is how to show some piece of UI on a screen.</p><p>From time to time, in a fancy world of real business problems, we need to delegate a bunch of more complex problems to some piece of code which:</p><ol><li>incapsulates some business logic holding and changing the internal data;</li><li>lets us forget about implementation details and provides a clear API to reuse the solution in different environments with the different initial input.</li></ol><p>React calls such components stateful and provides an <a href="https://reactjs.org/docs/uncontrolled-components.html">uncontrolled design</a> to pass in initial input and subscribe to changes which may occur inside the black box of such component.</p><p>That approach was introduced at a very early stage of React lifecycle (much earlier than classy components, hooks, and contexts were born), and in my humble opinion that was one of the breaking ideas which brought UI development to the new stage. Stateful components allowed us to do exactly what we did before with Backbone or Ember: <strong>incapsulate the problem</strong> and <strong>reuse its solution</strong>. But in a functional reactive style :)</p><p>I think I need both designs. <a href="https://itnext.io/controlled-vs-uncontrolled-components-in-react-5cd13b2075f9">There are a lot of words were spoken about that</a> so I do not pay too much attention here to the “when to use uncontrolled components” topic.</p><p>Across my React projects I use simple hook called useDerivedState to build stateful controls which implement both designs with a next signature:</p><pre>interface DerivedValue&lt;T&gt; {<br>    value: T,<br>    controlled?: boolean,<br>    onChange?: (v: T) =&gt; void,<br>}</pre><p>where T is a type of value to hold and controlled is true by default.</p><p>I have departed from the conventional value/defaultValue signature to overcome possible tangles when both value and defaultValue props are given.</p><p>Here comes a code:</p><pre>function useDerivedState&lt;T&gt;({<br>    value,<br>    controlled = true,<br>    onChange,<br>}: DerivedValue&lt;T&gt;): [T, (v: T) =&gt; void] {<br>    const [stateValue, setStateValue] = React.useState&lt;T&gt;(value)<br>    const handler = React.useCallback(<br>        (x: T) =&gt; {<br>            if (!controlled) setStateValue(x)<br>            if (_.isFunction(onChange)) onChange(x)<br>            return<br>        },<br>        [controlled, onChange],<br>    )<br>    return controlled<br>        ? [value, handler]<br>        : [stateValue, handler]<br>}</pre><p>And here comes an example of radio buttons group component which implements both designs out of the box:</p><pre>interface Choices { [index: string]: string | number }</pre><pre>interface Props extends DerivedValue&lt;string&gt; {<br>    choices: Choices<br>}</pre><pre>function RadioButtonsGroup({<br>    choices,<br>    ...rest<br>}: Props): React.FunctionComponentElement&lt;Props&gt; {<br>    const [choice, setChoice] = useDerivedState&lt;string&gt;(rest)</pre><pre>    return (<br>        &lt;ul&gt;{<br>            _.map(choices, (v, k) =&gt; (<br>                &lt;li key={String(v)} onClick={() =&gt; setChoice(k)}&gt;<br>                    {v as string}<br>                &lt;/li&gt;<br>            ))<br>        }&lt;/ul&gt;<br>    )<br>}</pre><p>Now we can use RadioButtonsGroup component as controlled component (by default) in any Flux-styled application or pass incontrolled={false} to make component acting like React’s intrinsic input with defaultValue instead of value given.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7e003e72c9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React keys and deferred self re-render]]></title>
            <link>https://medium.com/@iuriikomarov/react-keys-and-deferred-self-re-render-5e868eecf501?source=rss-778f4206c10e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e868eecf501</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Iurii Komarov]]></dc:creator>
            <pubDate>Wed, 03 Jun 2020 23:13:29 GMT</pubDate>
            <atom:updated>2020-06-03T23:13:29.058Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I was working on yet another date picker React component with an ability to exclude “today” from options allowed for selection which is ordinary usage case for any booking platform.</p><p>I show red mark to indicate current date in calendar component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*r2AEbePLdD333eGmgu9q2w.png" /></figure><p>To determine that “today” cell inside map on a dates range I use isToday function from date-fns which is being called each time component re-renders itself in response to state change (e.g. selecting a new date) and I wasn’t surprised at all to notice red mark jumping from 7th of June to 8th of June when I clicked somewhere at some point of time. I took a look at the clock, it was 12:03AM. Today’s mark was updated and of course it was updated in response to user action and everything worked as expected but in terms of business logic it was updated <strong>too late</strong>.</p><p>In such rare case your client may open date picker modal at 23:59:xx, and if for some reason the choice will be made with a minute delay, user will be allowed to send a booking request back to the past.</p><p>So how to force React component re-render itself at exact time in a clear way?</p><p>If you need to update something in a functional reactive system, you need to change the state. So let’s add state container of a type Date to hold the “today” stamp.</p><pre>const [datestamp, setDatestamp] = React.useState&lt;Date&gt;(new Date())</pre><p>Then, let’s do defer state update function invocation to the desired moment of time which in our case is ongoing midnight.</p><pre>useDefer(tomorrowMidnight(), () =&gt; { setDatestamp(new Date()) })</pre><p>useDefer hook is defined as:</p><pre>function useDefer(d: Date, f: () =&gt; void): void {<br>    React.useEffect(() =&gt; {<br>        const delta = d.valueOf() - Date.now()<br>        if (delta &lt;= 0) return undefined<br>        const timeout = setTimeout(f, delta)<br>        return () =&gt; clearTimeout(timeout)<br>    }, [])<br>}</pre><p>To answer the question “how to force functional React component to re-render itself” I’d recommend you to rephrase the imperative “Hey, component, I order you to…” in a functional manner. “What should be changed, dear component, so Your Lordship be updated”?</p><p>Actually, we already have datestamp state property which will be changed with the first beat of the clock and all we need is to <strong>define an interconnection</strong> between that datestamp state and key prop of the root node of the component.</p><pre>return &lt;Root key{datestamp.toLocaleDateString()}&gt; ...</pre><p>React uses key prop as one of the top and most straightforward factors <a href="https://reactjs.org/docs/lists-and-keys.html#keys">to decide should DOM node be updated or not</a> when virtual DOM changes occur. If key swaps between re-renders, React shakes out the whole DOM nodes subtree and re-renders all the stuff from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e868eecf501" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>