<?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 Mikhail Boutylin on Medium]]></title>
        <description><![CDATA[Stories by Mikhail Boutylin on Medium]]></description>
        <link>https://medium.com/@lahmataja-pa4vara?source=rss-136d5a8d785a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cf4UAAtAhr9jfU75.</url>
            <title>Stories by Mikhail Boutylin on Medium</title>
            <link>https://medium.com/@lahmataja-pa4vara?source=rss-136d5a8d785a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 01:31:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lahmataja-pa4vara/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[Share decisions and open questions from Cursor]]></title>
            <link>https://lahmataja-pa4vara.medium.com/share-decisions-and-open-questions-from-cursor-7b1e39b7694c?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1e39b7694c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[team-collaboration]]></category>
            <category><![CDATA[cursor]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 10:34:29 GMT</pubDate>
            <atom:updated>2026-10-07T10:34:29.631Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZli1rFTWM0qdGLTFwXtgg.png" /></figure><h3>Share decisions and open questions from Cursor</h3><p>How do you share the reasoning from your Cursor session with the rest of your team? Want to keep decisions, trade-offs, and open questions easy to find beyond the chat? Ask Cursor to save that context in your team’s <a href="https://pamiac.com/">Pamiac</a> workspace so teammates and their connected agents can build on it.</p><h3>1. Connect Pamiac</h3><p>Connect Cursor to your <a href="https://pamiac.com/">Pamiac</a> account using Pamiac’s agent setup. Once connected, check that Cursor can find your notes. Cursor supports external tools through <a href="https://cursor.com/docs/mcp">MCP</a>.</p><h3>2. Ask Cursor to capture the reasoning</h3><p>Paste this into the conversation where you’ve been working:</p><pre>Save a note in the “[workspace]” Pamiac workspace,<br>titled “[feature] — decisions and open questions”.</pre><pre>Review our conversation and capture:<br>- Decisions we made and why<br>- Alternatives considered and why we passed on them<br>- Trade-offs we accepted<br>- Open questions and what would help resolve them</pre><pre>Separate agreed decisions from proposals. Don’t invent reasons<br>or turn assumptions into facts. Include relevant links if available.<br>Keep it under 250 words and return the note link.</pre><h3>3. Review and share with your workspace</h3><p>Review the note to make sure it reflects what you actually agreed. <strong>Documents can be securely shared inside your Pamiac workspace</strong>, giving teammates and their connected agents quick access to decisions, trade-offs, and open questions. Access follows workspace permissions and the access granted to each agent connection.</p><p>Share the link with your team, or ask a connected agent with workspace access to find and read the note. You can also review the content and enable public access separately.</p><h3>Example: publish screenshots of translated text</h3><p>You’re working in Cursor on a page available in several languages. Publish screenshots of the same screen in English, Spanish, and French together in a Pamiac note, each labelled with its language and the text shown. Add the decisions behind the wording and any questions for reviewers. Share it inside your workspace for team review, or make the reviewed note public when it’s ready.</p><blockquote><strong><em>Decision:</em></strong><em> Keep the same meaning and tone across languages, while allowing natural phrasing.<br> </em><strong><em>Alternative:</em></strong><em> Translate word for word; rejected where the result sounds awkward.<br> </em><strong><em>Trade-off:</em></strong><em> Shorter button labels fit the layout, but may lose some nuance. Keep the fuller explanation nearby.<br> </em><strong><em>Open questions:</em></strong><em> Does each label clearly describe the action? Should we shorten the French text or give the button more room?</em></blockquote><h3>4. A teammate or another connected agent picks up the feature:</h3><pre>Read this translation review note: [link]. Compare the text<br>for each language using the recorded decisions and trade-offs.<br>Use the screenshots to check layout if you can view them;<br>otherwise ask for the relevant images or details.<br>Suggest changes for the open questions, and update the note<br>when we agree on wording or layout changes.</pre><p>Your teammate can review the translations in context, and their connected agent can use the same wording, decisions, and open questions when continuing the work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1e39b7694c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React without Pain: Avoid Re-Renders and Simplify Dependencies]]></title>
            <link>https://medium.com/front-end-weekly/react-without-pain-avoid-re-renders-and-simplify-dependencies-6f731b75e288?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f731b75e288</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[mlyn]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Mon, 13 May 2024 09:15:13 GMT</pubDate>
            <atom:updated>2024-05-15T20:16:23.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MAJ0JFe9rVL0rvZd.jpg" /></figure><p>Tracking re-renderings in React can be a painstaking process. Fine-grain reactivity pattern offers a solution that completely removes this problem, allowing React engineers to forget about tracking dependencies and focus on writing code. In this article, we’ll explore how library Mlyn simplifies dependency management and prevents unnecessary re-renders in React applications.</p><h3>Dependency Management: A Common Challenge</h3><p>In traditional React applications, managing state and dependencies can often lead to complex and error-prone code. Let’s consider a simple counter example to illustrate this issue.</p><h3>Traditional React Example</h3><pre>import React, { useState, useCallback } from &quot;react&quot;;<br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const onIncrement = useCallback(() =&gt; {<br>    setCount(prevCount =&gt; prevCount + 1);<br>  }, [count]); // Dependency on count<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;button onClick={onIncrement}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default Counter;</pre><h3>Issue with Dependencies</h3><p>In this example, the onIncrement function is wrapped in useCallback with count as a dependency. Every time count changes, onIncrement is re-created.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3>Simplifying with Mlyn</h3><p>Mlyn introduces fine-grain reactivity, allowing you to manage state updates without worrying about dependencies. Let’s rewrite the same example using Mlyn.</p><h3>Mlyn Example</h3><pre>import React, { useCallback } from &quot;react&quot;;<br>import { rc, useSubject } from &quot;mlyn/react&quot;;<br>const Counter = rc(() =&gt; {<br>  const state = useSubject({ count: 0 });<br>  const increment = useCallback(() =&gt; {<br>    state.count(state.count() + 1);<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {state.count()}&lt;/h1&gt;<br>      &lt;button onClick={onIncrement}&gt;Increment&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>});<br><br>export default Counter;</pre><p>Since the reference ofstate.count never changes, we can read it in useCallback without re-creating a new function.</p><h3>Benefits of Fine-Grain Reactivity</h3><ol><li>Stable Callbacks: The onIncrement function in Mlyn does not need state.count as a dependency. This stability prevents unnecessary re-creation of the function. And consumers of onIncrement will not re-render when count changes.</li><li>Simplified Code: With Mlyn, you don’t need to track dependencies manually.</li></ol><h3>Extracting IncrementButton: A Closer Look at Re-Rendering</h3><p>Let’s extract the increment button into theIncrementButton component to understand how Mlyn’s approach prevents unnecessary re-renders.</p><h3>Traditional React: Re-Rendering Issue</h3><p>In the traditional example, IncrementButton re-renders every time count changes because increment is a new function reference each time.</p><pre>const IncrementButton = React.memo(({ onIncrement }) =&gt; {<br>  console.log(&quot;IncrementButton re-rendered&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={onIncrement}&gt;Increment from Child&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>});<br><br>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br>  const onIncrement = useCallback(() =&gt; {<br>    setCount(prevCount =&gt; prevCount + 1);<br>  }, [count]); // Dependency on count<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {count}&lt;/h1&gt;<br>      &lt;IncrementButton onIncrement={onIncrement} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><h3>Mlyn: Preventing Unnecessary Re-Renders</h3><p>With Mlyn, onIncrement remains the same reference, so IncrementButton does not re-render unnecessarily. This is a key advantage of fine-grain reactivity.</p><h3>Example Revisited</h3><pre>const Counter = rc(() =&gt; {<br>  const state = useSubject({ count: 0 });<br>  const onIncrement = useCallback(() =&gt; {<br>    state.count(state.count() + 1); // No dependencies needed<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Count: {state.count()}&lt;/h1&gt;<br>      &lt;IncrementButton onIncrement={onIncrement} /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><h3>Summary</h3><p>Mlyn’s fine-grain reactivity simplifies state management by:</p><ul><li>Eliminating the Need for Dependency Tracking: You can write cleaner, more maintainable code without worrying about manually updating dependencies.</li><li>Preventing Unnecessary Re-Renders: Components only re-render when their actual state or props change, improving performance and efficiency.</li></ul><p>By adopting Mlyn, React engineers can focus on writing feature-rich code without the hassle of managing complex state dependencies. Try integrating Mlyn into your next project and experience the ease of fine-grain reactivity!</p><p>Interested in mlyn, check it out on github: <a href="https://github.com/vaukalak/mlyn">https://github.com/vaukalak/mlyn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f731b75e288" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/react-without-pain-avoid-re-renders-and-simplify-dependencies-6f731b75e288">React without Pain: Avoid Re-Renders and Simplify Dependencies</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React 18 Suspense Minimal Example]]></title>
            <link>https://javascript.plainenglish.io/react-18-suspense-minimal-example-775f786ba24?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/775f786ba24</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Sun, 23 Jan 2022 12:15:40 GMT</pubDate>
            <atom:updated>2022-01-27T16:19:40.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*7fJ68lmnebwn7jHhygONWg.png" /></figure><p>In the current version of React (17.0.2 at the day of this article creation), Suspense is a component, that allows developers to lazy-load application parts. It accepts fallback property, with content to display, while the child component is lazy-loading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0dDiRBK9SWqlifdnl_7KQ.png" /></figure><p>However, starting with React 18 it will be possible to use Suspense for data fetching. This means, that fallback will be displayed until the component will fetch all the data needed. Or in general, all events that components expect will occur. Let&#39;s say we want to just display the placeholder for 2 seconds:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6t6gEpXunPDqJnz_uWrcg.png" /></figure><p>As you could guess, Loading... will be displayed for 2 seconds and Component loaded afterward.</p><p>However, when I first saw the code above, I didn&#39;t understand <em>HOW</em> did that happen... What is that magic mechanism in the useTimeout hook? In short, it has to:</p><ol><li>Stop component code execution.</li><li>Let Suspense know that the component isn&#39;t yet ready</li><li>Notify Suspence when it should re-attempt with rendering component.</li></ol><p>To stop code execution you need to use the throw statement. In order to make Suspense know it&#39;s expected, the value thrown need to be a Promise. Suspense will catch this promise and subscribe to it, to re-attempt rendering.<br>Please note: the code below is just for a demo purpose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zwgCh4yVDduN97Wj0Eg78g.png" /></figure><p><em>(Confused about </em><em>||= ? Check </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment"><em>this doc</em></a><em>)</em></p><p>It turns out that suspense uses quite simple mechanisms, but there’s a hard part. You might ask why fullfilled and promise couldn&#39;t be stored in a ref, so the hook would be reusable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ACYEYfqA6J8llGgbGKtSdA.png" /></figure><p>It turns out, that while the component is not loaded, hooks can’t be really used. The component will be unmounted/mounted on every render attempt before the render will complete without throwing promises. Hence to figure out, if this component has actually started the data loading process, we should rely on a globally available cache. (In our simplified case it’s just fullfilled variable). Of course, in a real-world example such a simple approach wouldn&#39;t work (this hook works only one time).</p><p>This is why it’s advised to use good libraries that support suspense (like <a href="https://swr.vercel.app/">SWR</a>).</p><p><a href="https://codesandbox.io/s/suspense-timeout-example-4g7rh">Full code</a> of the example above.</p><p>👋</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=775f786ba24" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-18-suspense-minimal-example-775f786ba24">React 18 Suspense Minimal Example</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two-way binding will make your React code better.]]></title>
            <link>https://medium.com/front-end-weekly/two-way-binding-will-make-your-react-code-better-f58865923538?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f58865923538</guid>
            <category><![CDATA[recoil]]></category>
            <category><![CDATA[valtio]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Fri, 14 Jan 2022 15:44:23 GMT</pubDate>
            <atom:updated>2022-01-20T16:24:58.611Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qAhyHG_kc614Tm-dkgVbZg.jpeg" /></figure><p>Two-way binding allows creating synchronization between 2 entities, for example, application data and view. React out of the box, provides an api to get one-way binding. When we want to mutate the state, we need explicitly call updating callback:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pe6DJAtMp35-T2_3m5mYeg.png" /></figure><p>This is done to provide owner to child update experience. So when the root state of the app gets updated, changes will propagate to children. This makes application data flow clear and predictable, however increases the amount of code to write.<br>In order to make a two-way binding match with react update philosophy, I’ve built a library called mlyn. The main paradigm is that every piece of the state is readable and writable. However when you write to it, the change will bubble to the root of the state, and the root state will be updated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Bkc9QVW0BuaAnkkV0uArQ.png" /></figure><p>That’s it, the engine will update the state in the same way as on the plain react example above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*SMBgiqvVPFNu42bMUDUJ6w.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><p>However two-way binding is not limited to the communication with UI. You can easily bind your value to the local storage. Let say you have a hook that accepts a portion of mlyn state, and target local storage key:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jk5jq8PlcKF3o-MR0ZwC7Q.png" /></figure><p>Now you can easily bind user name to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t31zC1_DLjuGXP0LJ31BgA.png" /></figure><p>Note that you don’t need to create/pass any callbacks to update the value, it just works.<br>Another use-case is when you want to make changes of the state undoable / re-doable. Once again, just pass this state to the appropriate history management hooks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YXmAnheb4irSgooDWp1YPg.png" /></figure><p>The history object will contain the api to jump to any step of the state. However, it&#39;s a bit customized 2-way binding. Whenever state gets updated, the value is pushed to the history:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*GhiJOFZ096s0132YjIIm_A.jpeg" /></figure><p>When a history entry is selected, this entry is written back to the state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*6TQ_Iwan_oX8Zdqcm9QOuA.jpeg" /></figure><p>And note again that we don’t write a custom boilerplate for the state update, just connecting the dots. Check this <a href="https://codesandbox.io/s/react-mlyn-todo-mvc-with-history-lr34k?file=/src/App.js:1514-1555">code sandbox</a> with history management for a TodoMVC app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*kkac5rgo0BbEfB-8VfFDrg.gif" /></figure><p>For more examples on 2-way binding and mlyn visit <a href="https://github.com/vaukalak/react-mlyn">react-mlyn repo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f58865923538" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/two-way-binding-will-make-your-react-code-better-f58865923538">Two-way binding will make your React code better.</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Currency converter app in React and Mlyn]]></title>
            <link>https://medium.com/front-end-weekly/currency-converter-app-in-react-and-mlyn-7dda4258df2f?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dda4258df2f</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[mlyn]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Tue, 14 Dec 2021 17:59:53 GMT</pubDate>
            <atom:updated>2021-12-21T16:21:34.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JKeQ-MAauW31uiLt0IIIg.png" /></figure><p>👋 Let build a currency converter app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z7rNNWEWBBWemhuYciENjQ.gif" /></figure><p>The application should allow to edit the amount in the input fields and change currency. The amount in another input should change in the base of the conversion rate.<br>For a working example see <a href="https://codesandbox.io/s/mlyn-currency-converter-t5w0o?file=/src/App.js">this codesandbox</a> (It also contains an advanced example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZMpB85giw9F1WVOfyAUjg.png" /></figure><p>First of all, we need to define our data domain. We need to take a currency as a reference point, let use USD:</p><p>Now we can setup the root state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XF3LRHIaxs8sqGWTIP4Vow.png" /></figure><p>Yeah, that’s all boilerplate we need. And finally some JSX:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SeiGQrPljIhIFYDIZrFhXQ.png" /></figure><p>Operation state$.baseAmount created a read/write lens to baseAmount property. Calling state$.baseAmount() will return its current value and state$.baseAmount(1) will change the baseAmount value. The update will bubble to the root state, cause encapsulated object is immutable. Also, you can subscribe to this value. This enables 2-way binding. <br>Same thing for state$.currencies[0], it will read/write the first element of the currency array.<br>Now let write an incomplete version of the Currency component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jUio6cYveqJSZz-jkagmdg.png" /></figure><p>Mlyn.select is a wrapper over the plain select element, it has a property bindValue which accepts a read/write value, and creates a 2-way binding to it. Internally Mlyn.select will observe currency$ value, and re-render when it’s changed. When a selector option will be selected currency$ (and hence the root state) will be updated.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><p>To write the input we can’t just bind amount$ to it, cause we need to display the derived value of the currency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mx5cw3TBxbozA5NkeC8AQQ.png" /></figure><p>Ok. This will be the hardest part.<br>One of the good things about 2-way binding is that you can wrap binded value within a function, that will perform read/write derivation logic. So let create a function that will convert amount in a currency to/from USD amount:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jswIQx9TVSTq9jU6sOhuyA.png" /></figure><p>The above function is a simplified version, in reality we should do some input validation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Merak0FYb57USGE3sRpCHA.png" /></figure><p>Now you can use pass the converted currency lens to the amount input:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yfH9IlQsWaOpJ3z0n8I_PQ.png" /></figure><p>For more examples and docs about mlyn, I invite you to check the <a href="https://github.com/vaukalak/react-mlyn">github repo page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dda4258df2f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/currency-converter-app-in-react-and-mlyn-7dda4258df2f">Currency converter app in React and Mlyn</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Proxy / Observable as property” pattern in React]]></title>
            <link>https://medium.com/front-end-weekly/proxy-observable-as-property-pattern-in-react-51d081569534?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/51d081569534</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mlyn]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Mon, 06 Dec 2021 12:18:41 GMT</pubDate>
            <atom:updated>2021-12-07T16:14:07.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oaIjq_xXTxD1B0Bx1KB_hA.png" /></figure><p>Suppose you have the following app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*hUIrf1M-Uc3hNoGQ.png" /></figure><p>In this particular state you have Box1 element selected, and want to change it backgroundColor style by the color picker in the Details component. Let describe some possible implementations in React:</p><p>(Scroll down if want to bypass prop-drilling / context / redux approaches and go directly to proxy / observable approach).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3>Prop-drilling</h3><p>In this case we would lift the state that contains all elements to the top of the app (Application component). We would pass to the Details component the selected element, and a callback (updateComponent) to modify it. Then on color selection this callback updateComponent would be invoked, which would update state of Application component. Afterwards Application, Canvas and Box1 components would be re-rendered and finally background color will be updated.</p><h3>Pros</h3><p>Simple implementation to develop and support.</p><h3>Cons</h3><p>This would cause invalidation of all hooks (useCallback / useEffect / useMemo) to check if they need to update. Also re-rendering Canvas would cause invalidation of properties of all boxes (need to check if incoming properties changed for this specific box). In real-world application you&#39;ll get even more dependencies to update (for sure Canvas will not be the only child of Application). Also this is positive scenario, which suppose that all memoization in your app is properly managed.</p><p>This will certainly work fine if you update color only when releasing color picker. But what if you want to update the color of Box1 on every mouse move to get a handy preview experience? I think in some cases it will still work, but at a certain point, you might reach a performance wall, that will force you to optimize your application. And in this case, a simple implementation might become not so simple.</p><p>Also, you will not only need to pass down the state but also callbacks to update it.</p><h3>Context / Redux</h3><p>I grouped those two approaches, cause they solve this problem in a similar way. The state is stored in a context which then is injected into components via hooks (react-redux uses context under the hood as well). So when the state stored in context is updated, all dependent components are notified.</p><h3>Pros</h3><p>Since you don’t pass the property / update callbacks through the intermediary components, the amount of passed properties is reduced. The problem of re-rendering intermediate components is solved as well.</p><h3>Context cons</h3><p>All components subscribed to context via useContext re-renders when it&#39;s updated. This problem might be solved by fragmenting different parts of the state into different contexts. But I&#39;d prefer application data to be separated in base of logical distinction, rather than in base of thinking how it will re-render less.</p><h3>Redux concerns</h3><p>In redux, all components that are subscribed via useSelector hook are notified, but then a selector is run to extract selected state, afterward it figures out if that component actually needs to be re-rendered. This mostly solves the re-rendering issue, but still, more components are subscribed to the store, more selector logic needs to happen.</p><p>As another concern, I need to state, that unfortunately, I saw many situations, when some complex (or parametrized) selectors were written in the wrong way, from the memoization standpoint. And this would make the component re-render on every store update (even of data completely unrelated to the re-rendered component). Those memoization issues are quite hard to debug.</p><p>One more issue is that within useSelector hook you need to reference the full application state. This means if your module consumes user data, it has to be aware that this user data is stored under user key in the root state. Not good for modules decomposition. In general context (and especially with redux) makes it harder to create reusable components, and bootstrap unit tests / storybook.</p><h3>Proxy / Observable as property</h3><p>However, React doesn’t force component properties to be plain values. You can easily pass as property an observable value to a child and then internally subscribe to it. Let write some pseudo-code to explain it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CUgNx2wHyTNWHoI4l5sMAg.png" /></figure><p>Then inside a consumer component, you can subscribe to its value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7uF0ZUAL2GmGPstSqpx16g.png" /></figure><p>Looks like a lot of boilerplate is needed. Also within this approach all Box component function needs to re-execute. Suppose for example situation when a component has more than one child. But what if we create an ObserverDiv component, that will detect all observable properties automatically, then the code can be reduced to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2w3eGwT-fILqZ3stiX57VQ.png" /></figure><p>This is very similar to prop-drilling but on change of backgroundColor for one element only ObserverDiv will be re-rendered and the rest of the app will remain untouched. Very similar to the context / redux approach, but without related concerns.</p><p>The next question is how we can make every element property (like element.backgroundColor) observable. Here&#39;s where proxy enters the game. Within a javascript proxy object, you can override get accessors, and return another proxy, which will create a lens to backgroundColor, now you can directly subscribe to it.</p><p>To solve everything described above I have a created library called <a href="https://github.com/vaukalak/react-mlyn">mlyn</a>. Within it you can create proxies, that can be lensed, subscribed, and updated. And yeah, internally those proxies contain immutable objects, so none of React best practices are violated. How this app would look with mlyn:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*466fjBdpyAMSJOtzfw5uiA.png" /></figure><p>And now when you change backgroundColor of an element, only the Mlyn.div component will be re-rendered.</p><p>To see mlyn in action, please check out my <a href="https://medium.com/front-end-weekly/todomvc-app-with-react-and-mlyn-6a2bffb08c32">previous article </a>about it.</p><p>Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51d081569534" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/proxy-observable-as-property-pattern-in-react-51d081569534">“Proxy / Observable as property” pattern in React</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TodoMVC app with React and Mlyn.]]></title>
            <link>https://medium.com/front-end-weekly/todomvc-app-with-react-and-mlyn-6a2bffb08c32?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a2bffb08c32</guid>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[solidjs]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Tue, 23 Nov 2021 12:07:46 GMT</pubDate>
            <atom:updated>2021-12-01T14:51:44.786Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTXJCcZ7UoLRTelt5BmQ2w.jpeg" /></figure><p>Impressed by fine-grained reactivity concept from solid-js, I’ve tried to build a library that brings it to react. Some react issues I was going to solve where:</p><ul><li>Provide possibility to re-render just those elements, which data has has changed.</li><li>Enable easy 2-way binding, however maintaining unidirectional data flow.</li><li>Remove necessity to overflow the code by explicitly mentioning all dependencies, as we currently do with useEffect, useCallback, and useMemo.</li><li>Issues with encapsulation and modularisation when using redux or context as state management (I ❤️ redux btw).</li></ul><p>Now I’m going to present you main concepts of the library within a TodoMVC app example. You can find full source code <a href="https://codesandbox.io/s/react-mlyn-todo-mvc-owecw">here</a>. Note that example fits in less than 60 lines of code.</p><p>First of all let define our component:</p><pre>export const App = seal(() =&gt; {<br> // …<br>});</pre><p>seal is an import from react-mlyn, it’s a wrapper of React.memo, which compare function always returns true. Which means, component should never re-render by incoming properties change (those are not supposed to ever change). All children re-renders will be triggered by mlyn reactivity system.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><p>Now let define the state:</p><pre>const state$ = useSubject({<br> todos: [],<br> newTitle: &quot;&quot;<br>});</pre><p>useSubject is a react-hook, that will convert initial state to a subject. A subject in mlyn is a proxy object, which can we used in 4 different ways:</p><ul><li>you can read from it:</li></ul><pre>// will return actual state<br>state$();</pre><ul><li>you can write to it:</li></ul><pre>// will set `newTitle` to `hello`<br>state$({<br> ...state$(),<br> newTitle: “hello”,<br>});</pre><ul><li>you can subscribe to it:</li></ul><pre>useMlynEffect(() =&gt; {<br> // will log the `state$` value every time it’s updated<br> console.log(state$());<br>});</pre><p>By reading state$ inside of useMlynEffect hook we automatically set it as a dependency, which will re-run the hook every time state$ has been updated.</p><ul><li>you can lens it:</li></ul><pre>state$.newTitle(&quot;hello&quot;);<br>state$.newTitle(); // hello<br>state$(); // { newTitle: &quot;hello&quot;, todos: [] }</pre><p>Every lens behave like a subject, but when updated bubbles an immutable update to the root subject. Also within lens you can subscribe to updates of just a portions of the state.</p><p>Now let go back to our TodoMVC app, let create a synchroniser of todos to the local storage:</p><pre>// this hook accepts a subject and a string key for localStorage<br>const useSyncronize = (subject$, key) =&gt; {<br> // if localStorage already contains info for that key,<br> // let write it to `subject$` as initial state<br> if (localStorage[key]) {<br>   const preloadedState = JSON.parse(localStorage[key]);<br>   subject$(preloadedState);<br> }<br> // create a subscription to `subject$` and write<br> // write it to localStorage when updated<br> useMlynEffect(() =&gt; {<br>   localStorage[key] = JSON.stringify(subject$()); <br> });<br>};</pre><p>Invocation of this hook in the component code:</p><pre>// create a lens to `state$.todos` and<br>// bind it to localStorage `todos` key.<br>useSyncronize(state$.todos, “todos”);</pre><p>Let create methods for adding / deleting todos:</p><pre>const addItem = () =&gt; {<br> state$({<br>   todos: [<br>     // remember to use `()` when reading from a subject.<br>     ...state$.todos(),<br>     {<br>`      title: state$.newTitle(),<br>       createdAt: new Date().toISOString(),<br>       done: false<br>     }<br>   ],<br>   newTitle: &quot;&quot;<br> });<br>};</pre><p>This looks very similar to normal react update, but you don’t need to wrap it with useCallback since with mlyn component is not going to be re-rendered.</p><pre>const removeItem = (i) =&gt; {<br> state$.todos([<br>   ...state$.todos().slice(0, i),<br>   ...state$.todos().slice(i + 1)<br> ]);<br>};</pre><p>Note that since here you need to update just todos you can directly write to state$.todos without taking care of rest of the state. This is very handy, when passing a lens as a property to a child.<br>And finally jsx:</p><pre>return (<br>  &lt;&gt;<br>    &lt;h3&gt;Simple Todos Example&lt;/h3&gt;<br>    &lt;Mlyn.input<br>      type=&quot;text&quot;<br>      placeholder=&quot;enter todo and click +&quot;<br>      bindValue={state$.newTitle}<br>    /&gt;<br>    &lt;button onClick={addItem}&gt;+&lt;/button&gt;<br>    &lt;For<br>      each={state$.todos}<br>      getKey={({ createdAt }) =&gt; createdAt}<br>    &gt;<br>      {(todo$, index$) =&gt; (<br>        &lt;div&gt;<br>          &lt;Mlyn.input type=&quot;checkbox&quot; bindChecked={todo$.done} /&gt;<br>          &lt;Mlyn.input bindValue={todo$.title} /&gt;<br>          &lt;button onClick={() =&gt; removeItem(index$())}&gt;x&lt;/button&gt;<br>        &lt;/div&gt;<br>      )}<br>    &lt;/For&gt;<br>  &lt;/&gt;<br>);</pre><p>Notice that for inputs we use special tag Mlyn.input it has some properties which enables subscriptions to mlyn reactivity. One of those is bindValue. When you pass state$.newTitle to it, it will both update the input when the newTitle is updated, and write to newTitle when input is changed. In short, this is 2-way binding.</p><pre>&lt;Mlyn.input<br> type=&quot;text&quot;<br> placeholder=&quot;enter todo and click +&quot;<br> bindValue={state$.newTitle}<br>/&gt;</pre><p>Now let analyse how the For component, that is used to display collections works:</p><pre>&lt;For<br> // pass subject which holds array to display<br> each={state$.todos}<br> // key extractor, it’s used not only by react reconciliation,<br> // but also by `For` component logic.<br> getKey={({ createdAt }) =&gt; createdAt}<br>&gt;<br> {(todo$, index$) =&gt; (<br>   &lt;div&gt;<br>     &lt;Mlyn.input type=”checkbox” bindChecked={todo$.done} /&gt;<br>     &lt;Mlyn.input bindValue={todo$.title} /&gt;<br>     &lt;button onClick={() =&gt; removeItem(index$())}&gt;x&lt;/button&gt;<br>   &lt;/div&gt;<br> )}<br>&lt;/For&gt;</pre><p>The first parameter $todo of function child prop is still a 2-way lens. Which means, by updating it, you’ll update `todos` array and in general entire state. So writing:</p><pre>todo$.title(“new value”);</pre><p>Is like writing something similar to bellow in plain react:</p><pre>setState({<br> …state,<br> todos: state.todos.map(item =&gt; {<br>   if (getKey(item) === getKey(todo)) {<br>     return { …item, title: “new value” };<br>   }<br>   return item;<br> }),<br>});</pre><p>You probably noticed that one input is a checkbox toggle for boolean value:</p><pre>&lt;Mlyn.input type=”checkbox” bindChecked={todo$.done} /&gt;</pre><p>bindChecked is similar to bindValue but it creates 2-way binding for a boolean subject value to input checked field.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a2bffb08c32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/todomvc-app-with-react-and-mlyn-6a2bffb08c32">TodoMVC app with React and Mlyn.</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fine-grained reactivity in React with Mlyn]]></title>
            <link>https://medium.com/front-end-weekly/fine-grained-reactivity-in-react-with-mlyn-becf9d631c72?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/becf9d631c72</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mlyn]]></category>
            <category><![CDATA[solidjs]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Tue, 02 Nov 2021 16:18:57 GMT</pubDate>
            <atom:updated>2021-11-03T19:44:36.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xkHHtGe_-MTs5UI-MVwCow.jpeg" /></figure><p>You might hear recently about great frameworks like Svelte and Solid, that aim to become react replacements. One of the complaints about react is that it might become hard to manage re-renderings and hence huge virtual dom updates or expensive recomputations. Also taking care of memoization might become a tricky task. Let say you have auseCallback hook with some dependencies. You should take care to not only list properly all those dependencies but also be confident, that dependencies themselves are properly cached (in case of an object, array, or function). Otherwise, this useCallback will become a poorly memoized dependency and will cause on its own breaking memoization for dependent hooks and components. This cascade might be triggered in an unexpected place of the app, and it might become a complex and annoying issue to debug.</p><p>However, let assume we did a good job of memoizing our hooks and components:</p><pre>import React, { useCallback, useState} from &quot;react&quot;;</pre><pre>interface FieldProps {<br>  onChange(e: any): void;<br>  value: string;<br>  label: string;<br>}</pre><pre>const Field = React.memo((props: FieldProps) =&gt; {<br>  const { onChange, value, label } = props;<br>  const onChangeInternal = useCallback(<br>    (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>      onChange(e.target.value);<br>    },<br>    []<br>  );<br>  <br>  return (<br>    &lt;div&gt;<br>      {label}<br>      &lt;input<br>        value={value}<br>        onChange={onChangeInternal}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><pre>export const Form = React.memo(() =&gt; {<br>  const [firstName, setFirstName] = useState(&quot;&quot;);<br>  const [lastName, setLastName] = useState(&quot;&quot;);<br>  const [email, setEmail] = useState(&quot;&quot;);<br>  <br>  return (<br>    &lt;div&gt;<br>      PLAIN REACT<br>      &lt;Field<br>        label=&quot;First Name&quot;<br>        value={firstName}<br>        onChange={setFirstName}<br>      /&gt;<br>      &lt;Field<br>        label=&quot;Last Name&quot;<br>        value={lastName}<br>        onChange={setLastName}<br>      /&gt;<br>      &lt;Field<br>        label=&quot;Email&quot;<br>        value={email}<br>        onChange={setEmail}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><p>Virtual dom will not create a huge diff on this component, however updating firstName will still cause re-running full code of Formand one of Field components. This can be easily noticed if you turn on the Highlight updates when components rerender. option in react dev tools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*tCVr48qe1CeYSgfPVRgK6g.gif" /></figure><p>Svelte and Solid do propose a way to create subscriptions to atomic elements in a declarative way, and hence to increase update performance by reducing recalculation price. On the other side, they suggest not using virtual dom, cause all updates will be delivered to the address automatically.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><p>As an attempt to achieve the same level of control, but with react and <strong>with</strong> <strong>virtual dom</strong>, I’ve created a library called <a href="https://github.com/vaukalak/mlyn"><strong>mlyn</strong></a> and <a href="https://github.com/vaukalak/react-mlyn">react bindings to it</a>. Within it, you can create a <em>subject </em>that will hold your immutable state, and provide a lens to read / update / subscribe to a specific part of the state. In a <a href="https://medium.com/front-end-weekly/reduce-react-re-renders-with-mlyn-be138310b754">previous article</a>, I’ve mentioned a low-level approach to using the library, which will help to understand how it works under the hood. However we can achieve even less verbose and more granular update experience, we re-render ONLY what we need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*IHlJAEyQHaNrz5oyT-g-Mw.gif" /></figure><p>As you can see above we re-render only the element we want.</p><pre>import React, { useCallback } from &quot;react&quot;;<br>import Mlyn, { useSubject, seal } from &quot;react-mlyn&quot;;<br>import { Subject } from &quot;mlyn&quot;;</pre><pre>interface FieldProps {<br>  label: string;<br>  value$: Subject&lt;string&gt;;<br>}</pre><pre>const Field = seal((props: FieldProps) =&gt; {<br>  const { label, value$ } = props;<br>  const onChangeInternal = useCallback(<br>    (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>      value$(e.target.value);<br>  }, []);<br>  return (<br>    &lt;div&gt;<br>      {label}<br>      &lt;Mlyn.input<br>        value$={value$}<br>        onChange={onChangeInternal}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><pre>export const Form = seal(() =&gt; {<br>  const subject$ = useSubject({<br>    firstName: &quot;&quot;,<br>    lastName: &quot;&quot;,<br>    email: &quot;&quot;,<br>  });<br>  return (<br>    &lt;div&gt;<br>      REACT WITH MLYN<br>      &lt;Field label=&quot;First Name&quot; value$={subject$.firstName} /&gt;<br>      &lt;Field label=&quot;Last Name&quot; value$={subject$.lastName} /&gt;<br>      &lt;Field label=&quot;Email&quot; value$={subject$.email} /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><p>Let analyze the code above:</p><p>First of all we create a subject, that will hold our state.</p><pre>const subject$ = useSubject({<br>  firstName: &quot;&quot;,<br>  lastName: &quot;&quot;,<br>  email: &quot;&quot;,<br>});</pre><p>Then we pass to the Field component a lens to a field.</p><pre>&lt;Field label=&quot;First Name&quot; value$={subject$.firstName} /&gt;</pre><p>When we write subject.firstName we don’t pass it value, instead, we pass a <strong>readable</strong>, <strong>writable,</strong> and <strong>observable</strong> proxy to firstName . BTW, notice how it’s simple to achieve 2-way binding.</p><p>As you can notice Field is a <em>sealed </em>component, which means it will just never re-render by property change. All updates should be reactive via mlyn subscriptions.</p><pre>const Field = seal((props: FieldProps) =&gt; { ... });</pre><p>To update the value of passed projection (in our case firstName ), we just consume it as value$ and invoke it:</p><pre>const onChangeInternal = useCallback(<br>  (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    value$(e.target.value);<br>}, []);</pre><p>And the most interesting part:</p><pre>&lt;Mlyn.input<br>  value$={value$}<br>  onChange={onChangeInternal}<br>/&gt;</pre><p>Mlyn.input is a plain react dominput wrapped with utility that creates properties with trailing$ which will mean that this is a reactive property that will cause re-rendering whenever observable value will dispatch.</p><p>Hopefully, this approach will help you achieve a better developer experience, by simplifying connections among your components and simplifying performance-oriented tuning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=becf9d631c72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/fine-grained-reactivity-in-react-with-mlyn-becf9d631c72">Fine-grained reactivity in React with Mlyn</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two-way data binding in react with mlyn.]]></title>
            <link>https://lahmataja-pa4vara.medium.com/two-way-data-binding-in-react-with-mlyn-1693ca0e2821?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1693ca0e2821</guid>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[mlyn]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 18:46:58 GMT</pubDate>
            <atom:updated>2021-09-28T18:46:58.162Z</atom:updated>
            <content:encoded><![CDATA[<h3>Two-Way Data Binding in React with react-mlyn</h3><h4>How to Implement Two-Way Data Binding in React</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IyfQfH-9fEjlM69dKRpObA.jpeg" /></figure><p>React provides a consistent API to update the application state. However, it becomes too lengthy in some cases. There are many situations when components need to receive both value and a method to update it. This is especially noticeable in the form management, sprite sheet-like components, and boolean values toggle.</p><p>Suppose an application that manages some game state and has a panel to enter user first/last names:</p><pre>import React, { useState } from &quot;react&quot;;</pre><pre>const UserInfo = React.memo(({ user, onUserChange }) =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        value={user.firstName}<br>        onChange={(event) =&gt; {<br>          onUserChange({<br>            ...user,<br>            firstName: event.target.value<br>          });<br>        }}<br>      /&gt;<br>      &lt;input<br>        value={user.lastName}<br>        onChange={(event) =&gt; {<br>          onUserChange({<br>            ...user,<br>            lastName: event.target.value<br>          });<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><pre>const CurrentLevel = React.memo(({ currentLevel }) =&gt; {<br>  return &lt;div&gt;Current level: {currentLevel}&lt;/div&gt;;<br>});</pre><pre>export default function App() {<br>  const [state, setState] = useState({<br>    game: { currentLevel: 1 },<br>    user: {<br>      firstName: &quot;Barbara&quot;,<br>      lastName: &quot;Radzivil&quot;<br>    },<br>  });<br>  return (<br>    &lt;div&gt;<br>      &lt;UserInfo<br>        user={state.user}<br>        onUserChange={(user) =&gt; {<br>          setState({<br>            ...state,<br>            user,<br>          });<br>        }}<br>      /&gt;<br>      &lt;CurrentLevel currentLevel={state.game.currentLevel} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>The complexity of the code above comes from the fact that we have to modify a full object explicitly. In case of firstName the process looks like this:</p><pre>// we need to create new user object<br>const newUser = {<br>  ...state.user,<br>  firstName: event.target.value<br>}</pre><pre>// we need to create new state<br>const state = {<br>  ...state,<br>  user: newUser,<br>};</pre><p>Deeper is the path of certain property. More verbose is the code to update it.</p><p>When programming with mutable objects, everything you need to update a value is:</p><pre>state.user.firstName = &quot;new value&quot;;</pre><p>The problem is that you can’t detect the value change, or even if you can, it’s quite hard to determine what has been updated (Since the object is mutable, you’ll need to run a deep comparison).</p><p>I’ve brought up this list of 4 items for a good state management library:</p><p><strong>1. Objects must be immutable.</strong></p><p><strong>2. It should support the possibility to perform updates just specifying the target property. Also, each module needs just the reference to the consumed state to update it. Update can be performed on any root / node / leaf values. This simplifies the modularization of the app (no need to ref root state/interface in a certain module).</strong></p><pre>// updating firstName<br>state.user.firstName(&quot;Urshulia&quot;);</pre><pre>// you should be able to pass `firstName` to a function that can update it<br>const { firstName } = state.user;<br>firstName(&quot;Urshulia&quot;);</pre><pre>// you can also perform updates on any node<br>state.user({ firstName: &quot;Bona&quot;, lastName: &quot;Sforza&quot; });</pre><pre>// ro even on the root<br>state({ ...state });</pre><p><strong>3. It should support 2-way bindings within an intuitive and not verbose lens system. Every lens should provide both read and write access.</strong></p><pre>// track old state for reference<br>const oldState = state();</pre><pre>// we&#39;ve created lens for firstName.<br>const { firstName } = state.user;</pre><pre>// you should be able to read from property<br>console.log(&quot;firstName:&quot;, firstName()); // Barbara</pre><pre>// and write to it.<br>firstName(&quot;Urshulia&quot;);</pre><pre>// updating lens has changed full state.<br>state() !== oldState;</pre><p><strong>4. Components can consume just those parts of the state they need. Therefore, there should be no overhead by increasing the number of subscriptions that are not updated.</strong></p><pre>// let create a subscription to the `firstName` lens.<br>runInReactiveScope(() =&gt; {<br>  console.log(state.user.firstName());<br>});</pre><pre>// subscription will be invoked and value logged to console.<br>state.user.firstName(&quot;Hanna&quot;);</pre><pre>// we didn&#39;t subscribe to `lastName`, hence to listeners invoked.<br>state.user.lastName(&quot;Jagelonka&quot;);</pre><p>Based on the four concepts above, I’ve implemented a library called <a href="https://github.com/vaukalak/mlyn">mlyn</a> and react bindings to it <a href="https://github.com/vaukalak/react-mlyn">react-mlyn</a>. And would like to show how it simplifies state management in react.</p><p>Some handlers (for example, standard dom input handlers) are invoked with an updated value within an event containing this new value.</p><pre>onChange={(event) =&gt; { console.log(event.target.value; }}</pre><p>So to create a 2-way binding, we need a function that will enhance our lens:</p><pre>export const useSubjectInputBinding = &lt;T&gt;(subject: Subject&lt;T&gt;) =&gt; {<br>  // create react bindings to the lens<br>  const value = useSubjectValue(subject);</pre><pre>  // an object that can be binded to react input<br>  return { value, onChange: (e) =&gt; subject(e.target.value) };<br>};</pre><p>Let rewrite the initial example using mlyn:</p><pre>import React from &quot;react&quot;;<br>import {<br>  useSubject,<br>  useSubjectInputBinding,<br>  useSubjectValue<br>} from &quot;react-mlyn&quot;;</pre><pre>const UserInfo = React.memo(({ user$ }) =&gt; {<br>  const firstNameBinding = useSubjectInputBinding(user$.firstName);<br>  const lastNameBinding = useSubjectInputBinding(user$.lastName);<br>  return (<br>    &lt;div style={{ display: &quot;flex&quot;, flexDirection: &quot;column&quot;, width: &quot;100px&quot; }}&gt;<br>      &lt;input {...firstNameBinding} /&gt;<br>      &lt;input {...lastNameBinding} /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><pre>const CurrentLevel = React.memo(({ currentLevel$ }) =&gt; {<br>  const currentLevel = useSubjectValue(currentLevel$);<br>  return &lt;div&gt;Current level: {currentLevel}&lt;/div&gt;;<br>});</pre><pre>export default function App() {<br>  const state$ = useSubject({<br>    game: { currentLevel: 1 },<br>    user: {<br>      firstName: &quot;Barbara&quot;,<br>      lastName: &quot;Radzivil&quot;<br>    }<br>  });<br>  return (<br>    &lt;div&gt;<br>      &lt;UserInfo user={state$.user} /&gt;<br>      &lt;CurrentLevel currentLevel$={state$.game.currentLevel} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Summary:</p><ul><li>Amount of lines of code reduced by 30%.</li><li>More readable code (especially update).</li><li>Faster updates (in the plain react example, the root is re-rendered on every update).</li></ul><h3>Learn More</h3><ul><li><a href="https://enlear.academy/simple-random-number-generator-with-react-260e92655b2f">Simple Random Number Generator with React</a></li><li><a href="https://enlear.academy/how-to-implement-custom-hooks-in-react-69d7937d3dc8">How to Implement Custom Hooks in React</a></li><li><a href="https://enlear.academy/whats-the-best-js-framework-for-lightning-fast-applications-a3e4c201ec62">Best JavaScript Framework for Lightning-Fast Applications</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1693ca0e2821" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reduce React re-renders with mlyn.]]></title>
            <link>https://medium.com/front-end-weekly/reduce-react-re-renders-with-mlyn-be138310b754?source=rss-136d5a8d785a------2</link>
            <guid isPermaLink="false">https://medium.com/p/be138310b754</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[immutability]]></category>
            <category><![CDATA[mlyn]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mikhail Boutylin]]></dc:creator>
            <pubDate>Sat, 04 Sep 2021 10:20:54 GMT</pubDate>
            <atom:updated>2021-09-08T14:50:11.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4CnkwoFehYT_IY1w.jpg" /></figure><p>The problem: you have an application, where a component updates state, that should be displayed in an absolutely different part of the app. The simplest solution would be to “prop-drill” the value through your components hierarchy.</p><p>Suppose the following app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*z2El-69BanWPX9j_SAE_mw.gif" /></figure><p>It has only 4 components:</p><ul><li><strong>App</strong>: application container (declares the state)</li><li><strong>A</strong>: Slider</li><li><strong>B</strong>: div where the value of the slider is rendered</li><li><strong>C</strong>: container of <strong>B</strong></li></ul><p>Possible implementation in plain react:</p><pre>import React, { useState } from &quot;react&quot;;</pre><pre>const A = React.memo(({ progress, setProgress }) =&gt; {<br>  return (<br>    &lt;input<br>      type=&quot;range&quot;<br>      value={progress}<br>      onChange={(e) =&gt; {setProgress(e.target.value);}}<br>    /&gt;<br>  );<br>});</pre><pre>const B = React.memo(({ progress }) =&gt; {<br>  console.log(&quot;&gt;&gt;&gt; render B&quot;);<br>  return &lt;div&gt;{progress}&lt;/div&gt;;<br>});</pre><pre>const C = React.memo(({ progress }) =&gt; {<br>  console.log(&quot;&gt;&gt;&gt; render C:&quot;, progress);<br>  return (<br>    &lt;div style={{ padding: 10, backgroundColor: &quot;yellow&quot; }}&gt;<br>      &lt;B progress={progress} /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><pre>export const App = React.memo(() =&gt; {<br>  const [progress, setProgress] = useState(0);<br>  console.log(&quot;&gt;&gt;&gt; render App&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;A progress={progress} setProgress={setProgress} /&gt;<br>      &lt;C progress={progress} setProgress={setProgress} /&gt;<br>    &lt;/div&gt;<br>  );<br>});</pre><p><em>(You can run a full example </em><a href="https://codesandbox.io/s/mlyn-vs-react-state-prop-drilling-fjw03?file=/src/drill/DrillMlyn.js:0-855"><em>o</em>n this sandbox</a><em>)</em></p><p>If we want to update display value of the slide in <strong>B</strong>, this is what will happen on every update</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*Lhv7O2ruqRmotEA12utNcg.png" /></figure><p><a href="https://github.com/vaukalak/mlyn"><strong>Mlyn</strong></a> solves this problem by introducing proxy values called <em>subjects. </em>You can pass those subjects (or parts of them) to your children and subscribe / update only where needed. Let review the migration of the code above by steps:</p><pre>export const App = () =&gt; {<br>  const progress$ = <strong>useSubject(0);</strong><br>  console.log(&quot;&gt;&gt;&gt; render App&quot;);<br>  return (<br>    &lt;div&gt;<br>      &lt;A progress$={progress$} /&gt;<br>      &lt;C progress$={progress$} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><p>Here in the <strong>App</strong>, we create a subject with an initial value of 0 . You can do following with a subject: subscribe to it value, write a new value to it, and pass it as a reference to another component.</p><pre>const A = ({ progress$ }) =&gt; {<br>  const progress = <strong>useSubjectValue(progress$);</strong><br>  return (<br>    &lt;input<br>      type=&quot;range&quot;<br>      value={progress}<br>      onChange={(e) =&gt; {<br>        <strong>progress$(e.target.value);</strong><br>      }}<br>    /&gt;<br>  );<br>};</pre><p>To bind a subject value to a react component you should <strong>useSubjectValue</strong> function from react-mlyn package. And to update it, simply invoke it as a function passing a new value.</p><p>The value of progress$ subject can be passed through other components of your app. However, only the component in which you’ve subscribed to the subject will be re-rendered.</p><pre>const B = ({ progress$ }) =&gt; {<br>  console.log(&quot;&gt;&gt;&gt; render B&quot;);<br>  const progress = useSubjectValue(progress$);<br>  return &lt;div&gt;{progress}&lt;/div&gt;;<br>};</pre><pre>const C = ({ progress$ }) =&gt; {<br>  console.log(&quot;&gt;&gt;&gt; render C&quot;);<br>  return (<br>    &lt;div style={{ padding: 10, backgroundColor: &quot;yellow&quot; }}&gt;<br>      &lt;B progress$={progress$} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><p>This is how updating <strong>B </strong>diagram simplifies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/1*bEUsTQyT1OjPpUSeJCDwAQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be138310b754" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/reduce-react-re-renders-with-mlyn-be138310b754">Reduce React re-renders with mlyn.</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>