<?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 Ben Carp on Medium]]></title>
        <description><![CDATA[Stories by Ben Carp on Medium]]></description>
        <link>https://medium.com/@bencarp?source=rss-77ab187e7fe2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WKKvdkK5whVve88za8-eQA.jpeg</url>
            <title>Stories by Ben Carp on Medium</title>
            <link>https://medium.com/@bencarp?source=rss-77ab187e7fe2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 13:32:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bencarp/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[What I learned from React-Query, and why I will not use it in my next project]]></title>
            <link>https://medium.com/duda/what-i-learned-from-react-query-and-why-i-will-not-use-it-in-my-next-project-a459f3e91887?source=rss-77ab187e7fe2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a459f3e91887</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[react-query]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Carp]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 11:01:07 GMT</pubDate>
            <atom:updated>2022-03-11T11:20:36.636Z</atom:updated>
            <content:encoded><![CDATA[<p>The beginning was exciting. The company’s lead front-end architect suggested checking out React-Query for our new Do-It-Yourself editor. Looking it up on NPM made it very clear — React-Query could not be ignored.<br>React-Query is on it’s way to becoming one of the most popular libraries in React’s ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rj3JR9wLE6hsR8L0duQMUg.png" /><figcaption>By <a href="http://duda.co">Duda</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iE1eFgI73iuTbWST" /><figcaption><em>React-Query vs React vs Redux. Downloads in library’s first two years, according to `NPM trends`</em></figcaption></figure><p>The next thing that surprised me was the `quick start` page.<br>This is how a request is managed on React-Query:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00b2bf40ef261faaebe16615e6193fa9/href">https://medium.com/media/00b2bf40ef261faaebe16615e6193fa9/href</a></iframe><p>Seeing it for the first time, you might ask yourself “Where is all the cycle of managing the request’s state? Changing it to loading, saving an error message, or hopefully, saving the returned data? This is React-Query’s magic — it does it for you.</p><p>To create the same functionality prior to React-Query, I’d have to write:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96803d5a6904dc32451ef4f71c1d8cb4/href">https://medium.com/media/96803d5a6904dc32451ef4f71c1d8cb4/href</a></iframe><p>From a product point of view, both snippets are equivalent. But managing the cycle in the old pattern required 19 lines of code, and using React-Query requires only one. The query object returned by React-Query includes all the state information we had before. We are released from the burden of repetitively managing the request process over and over — React-Query does it for us. By this stage, to put it in React terms, I was hooked.</p><h3>Does React-Query qualify as a request framework?</h3><p>React-Query does so much more than just manage the request state cycle. It provides out of the box tools related to network requests, such as re-fetching, prefetching and caching. It shares query state across an entire React-tree, which you can access by a key. It comes with an out-of-the-box mechanism to keep data fresh, by re-fetching data automatically when it is needed and defined as stale. And it also provides tools to manage your mutation requests (accessed via the `<em>useMutation</em>` hook).</p><p>But above all, React-Query comes with a new and different paradigm. According to this paradigm, server state was improperly managed till now. UI state and server state are of a different nature, have different needs and should be handled separately.</p><p>Furthermore, the way we managed global state until now is only appropriate for client state.</p><blockquote>“Redux, MobX, Zustand, etc. are <strong>client-state</strong> libraries that can be used to store asynchronous data, albeit inefficiently when compared to a tool like React Query”</blockquote><blockquote>“For a vast majority of applications, the truly <strong>globally accessible client state</strong> that is left over after migrating all of your async code to React Query is usually very tiny.”</blockquote><blockquote><em>(</em><a href="https://react-query.tanstack.com/guides/does-this-replace-client-state"><em>O</em>fficial site</a><em>)</em></blockquote><h3>Going all in</h3><p>Back to the project I was working on — Duda’s new DIY editor.</p><p>The idea is to provide Duda’s partners with a tool, with which their users can painlessly, easily and quickly create their own new site according to the partner’s specific needs. Duda already has the technology to create websites, we just wanted to create a simpler flow for a certain segment of users.</p><p>As you know, by this stage I was excited about React-Query, and decided to give the React-Query paradigm a fair try. Our plan was to hold all server state in a React-Query cache, and access it via the <em>useQuery</em> hook. It looked good.</p><p>Too good.</p><p>Once we had added complex user interactions issues started bubbling up.</p><h3>User adds new section to their site</h3><p>We’ll demonstrate those issues with a specific user flow — user tries to add new section to their site.</p><p>In the side panel the user can multi-select the kind of sections they want to add to their site, such as: “about”, “testimonials”, “FAQ”, “Contact us”, etc.</p><p>We send a request to the server to add this section to the website. If the request succeeds, the website then updates, and can edit various fields in that section in a simple form.</p><h3>Optimistic updates</h3><p>In our new DIY editor, we want to provide the user with a live experience. For that we use optimistic updates. React-Query’s approach to optimistic updates (<a href="https://react-query.tanstack.com/guides/optimistic-updates#_top">link</a>) is to update the query cache, according to what the data should look like if the request succeeds. If it ends up failing, we revert to the previous value.</p><p>We tried to implement it, and we reached a dead end:</p><ol><li>To determine if a section kind in the multiselect should show as selected, we look at the current data of our sections (<em>sectionsDataQuery.data</em>), and check if one of the sections in the website is of that kind. The thing is, at the time the user clicks to add a section, we have no way of knowing what the new section data will look like. (See <a href="https://gist.github.com/carpben/45d23a79af4a76302754945b3b6ef4d3">gist</a>)</li><li>There is a conceptual issue. The whole idea of separating client state from server state is that we’ll have a clear source of truth which we can trust. A source of truth which represents the real persistent state of things. But now the cache dedicated to server state isn’t reliable any more.</li><li>There is also a practical issue. A user can select multiple sections from the list. What if there are many optimistic updates taking place at the same time, some succeed and some fail? how do you know which state version to revert to. According to React-Query’s approach you might revert to an unreliable version.</li></ol><h3>Weird flows</h3><p>Following the React-Query approach we had a minimal store for client state, and we accessed server state via React-Query’s hooks.</p><p>The thing is, in a complex app those two sources of state interact. We have computed values that are derived from both. And we have async flows that have to do with both. To go back to the same example:</p><ol><li>User can select a template of a section they want to add to their site</li><li>Request is fired to the server</li><li>Response with the data of the new section is sent back to the client</li><li>Data of the new section is merged into the section’s array (server state)</li><li>Id of the new section is saved to the store as <em>selectedSectionId</em> (client state)</li><li>Value of <em>selectedSectionData</em> is derived from the <em>siteSections</em> data and the <em>selectedSectionId</em> (computed state)</li><li><em>selectedSectionData</em> is used on various components in our app, and also sent to an Iframe window</li></ol><p>We think that such a process should not be managed within the component. It affects the entire app, even beyond (the Iframe), and might be triggered by various components. <br>But if we were serious about accessing React-Query’s server state from the component, the server state would only be available from the components themselves. This also means that computed values and managing the async process is pushed down to the component.<br>We then had to access those values and functions by various components in the tree, so we had to add a context provider.</p><p>State and functionality that relate to the entire app started having various centers: React-Query, store, services and context providers.</p><h3>App structure</h3><p>Until now components were only aware of one app level source for logic/side effects and state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*SAHCh5tgDKkGlsVDNB9s6Q.png" /></figure><p>Now, there was another separate source that exposed functionality and processes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9Ey2TPulT2Cpmzf1dfw9A.png" /></figure><p>Not only that — those centers had to be accessed in a different mechanism. <br>It seemed like the component’s responsibility had grown significantly.</p><p>To be honest, we followed the React-Query approach and we got lost.</p><p><strong>Our current solution</strong></p><p>React-Query’s API does expose a <em>QueryObserver</em>, that allows you to trigger a query and listen to any changes. It can be accessed from anywhere. We can then subscribe to any change, take the <em>QueryResult</em> value, and place it in our MobX store in a dedicated property. When a query is relevant to more than one component, we moved away from managing the queries via <em>useQuery</em> (from the component), in favor of managing them on the app level, via the <em>QueryObserver</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*cPYRuOVxyNBYOMrAFxkeaQ.png" /></figure><p>The solution isn’t perfect though: <br>1. React-Query does not provide a non-hook tool to trigger mutation requests.</p><p>2. The data structure returned from React-Query was built with hooks in mind — it is a work around.</p><h3>React-Query is a revolution we should learn from</h3><p>Don’t get me wrong. React-Query is a revolution, and I think it has greatly contributed to the community. Mostly, because it has shown us that things can be done differently.<br>But it is a revolution that is taking place at this very moment, and we might need some time for the noise and dust to settle, so we can distinguish its great parts from some of its pitfalls.</p><h3>React-Query — The good parts</h3><p>React-Query <strong>automates the request process</strong>, including the requests’ state cycle. I can’t underemphasize this, because it is the first time, AFAIK, that automation occurs on a state related process.</p><p>It provides valuable <strong>tools to improve reliability of server data</strong> (invalidating data and marking data as stale).</p><p>It provides <strong>Tools to improve fetch UX </strong>(prefetching, re-fetching, caching, and more).</p><h3>React-Query — The pitfalls</h3><p>I often think of front-end development as the art of creating Lego pieces and composing them. For a code unit to be easily composable, it should have a single responsibility and an interface that can easily fit potential consumers.<br>Let’s look at Redux and MobX for example. You can consume them independently from React, and then they provide a second package (React-Redux for instance) that makes consuming them in React components more convenient. Each library has a single responsibility, and can be consumed independently from React, or consumed in React in various ways. There is an abstraction that allows it to play nicely in different architectures.</p><p>At present this isn’t the case with React-Query. <strong>This lego piece is big, and can only fit in a specific way to a specific structure</strong>.<br>The concept of automating and managing the request flow could be relevant for various architectures. But the React-Query package was built to be consumed by a specific kind of architecture.</p><p>React-Query presents a paradigm that is aligned to the architecture it was built for — “<em>Global state is not suitable for server data</em>”.<br>I have a different point of view. I believe that you should always <strong>start from local state</strong>. But there comes a time when you need to pick state up. And sometimes you need to make it global. I believe that <strong>global state makes sense</strong>, also for server data.</p><p><strong>I understand the meaning of server state differently</strong>. Like React-Query, I think that server state is its own thing and should be treated differently from client state. It is different because we are not the masters of that data, and we have a responsibility to represent it reliably. I do think that we should keep an independent representation of server state, that is our reliable source of truth. But does it mean we need to hold server state and UI state in a different kind of infrastructure? <br>React-Query suggests keeping server state and client state in different kinds of entities, accessed in a different way. But do they actually keep server state independent from client state?<br>React-Query’s method for optimistic updates actually mixes server and client state. Treating server state as a reliable representation of server data is what counts, not having a different infrastructure to hold it.</p><h3>What I will use in my next React Project</h3><p>React-Query showed me that there is a need for a layer that manages the request cycle and state. I have other things to do, and I’m happy to delegate this responsibility to an external tool. But in my next React project, I’ll try to find a tool that can integrate nicely into an existing and changing codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a459f3e91887" width="1" height="1" alt=""><hr><p><a href="https://medium.com/duda/what-i-learned-from-react-query-and-why-i-will-not-use-it-in-my-next-project-a459f3e91887">What I learned from React-Query, and why I will not use it in my next project</a> was originally published in <a href="https://medium.com/duda">Duda</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an AI algorithm for the Tic-Tac-Toe challenge]]></title>
            <link>https://medium.com/free-code-camp/building-an-ai-algorithm-for-the-tic-tac-toe-challenge-29d4d5adee07?source=rss-77ab187e7fe2------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d4d5adee07</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[games]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ben Carp]]></dc:creator>
            <pubDate>Wed, 08 Nov 2017 16:57:27 GMT</pubDate>
            <atom:updated>2017-11-12T19:26:41.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*tTQJFNpKFOOiH8dN_2tyEQ.png" /></figure><p>As part of the <a href="https://www.freecodecamp.org/">freeCodeCamp</a> curriculum, I was challenged build a <a href="https://en.wikipedia.org/wiki/Tic-tac-toe">Tic-Tac-Toe</a> web app. It was a real pleasure.</p><p>The app includes an ultimate computer player. It can optimize any given situation on the Tic-Tac-Toe board. The outcome surprised me.</p><p>Even in such a simple game, the computer player taught me some new moves. As for the code I wrote, it is somewhat unique and interesting to explore.</p><h3>Check it out</h3><p>Visit <a href="https://carpben.github.io/TicTacToe/">this link</a> and choose to play against the computer. <strong>I challenge you to win</strong>. You might find…that you can’t.</p><p>Yet, if you are hard on the defense, you might find out that the computer is not able to win either. I learned by experience that Tic-Tac-Toe has a simple <strong>non-lose</strong> strategy.</p><p>This means that if you manage to get a tie you are making the right defensive choices. The computer still optimizes its’ moves. So, the best result it can achieve against a player such as yourself might only be a tie.</p><h3>Main Solution steps</h3><h3>1. board data structure</h3><pre>_gameBoard: [<br>[“”, “”, “”],<br>[“”, “”, “”],<br>[“”, “”, “”]<br>]</pre><p>The board Array contains 3 arrays, each representing a row.<br>Each row array contains 3 character or string elements.</p><p>These elements are either:</p><ul><li>“ ” as an empty string, representing an empty cell</li><li>“X” representing the X player</li><li>“O” representing the O player</li></ul><h3>2. getResult function</h3><p><a href="https://github.com/carpben/TicTacToe/blob/ea8a67918f0ab97bca40e4383839e95695da803f/tictactoe.js#L59">Begins at Line 59</a></p><p>At any given state, the board will be in one and one only of these possible states:</p><ul><li>Incomplete</li><li>player X won</li><li>Player O won</li><li>or a tie</li></ul><p>The getResult function receives a board array, iterates over all the rows, through all the columns and across both diagonals. It checks the succession of symbols. Then it lets us know the current state of that board.</p><h3>3. getBestMove Function</h3><p>Here it gets more difficult. When the board is empty it is very difficult to identify the best possible move. Take a look at this board.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/0*Dsyde0AOjxdNDKcf." /></figure><p>Which is the best possible possible move?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*i4_4_Zj1k5vL6y-M." /></figure><p>When the board becomes populated, the best possible move pops out to our eyes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*AhY-mhauWzJUci57." /></figure><p>Let’s use this populated board as our starting point. Lets decide that the next move is ours, and that our symbol is an “X”.</p><p>Let’s try to identify the best possible move with the tools we already have. There are 3 empty cells that correspond with 3 possible moves. Lets check the result for each of these options.</p><p>We can do this by iterating over the possible moves, and for each of them:</p><ul><li>Create a new board</li><li>Add our symbol to the corresponding empty cell</li><li>Send this board to the getResult function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*icD9gAM1qcKbp2Co." /><figcaption><strong>Move 1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*W5gAvB6HADWOxeaF." /><figcaption><strong>Move 2</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*zae3uSQUIuWlXFM6." /><figcaption><strong>Move 3</strong></figcaption></figure><p>From the 3 boards in the figure above, when we send the second board to the getResult function, we will receive our trophy.</p><p>Please concentrate for the next essential steps:</p><ol><li>We need to grade the possible moves so we can compare them. Let’s decide that if a move yields a winning board we will grade it 1. If it yields a losing board it will receive the grade of -1. A tie will receive a grade of 0.</li><li>Move 2 will receive a grade of 1. When we find a move graded with 1 we can ignore all other possible moves. There is no other better possible move than a definite victory.</li><li>But for the sake of understanding, how would we grade moves 1 or 3, or any other move with an incomplete result?</li></ol><p>Let’s Focus on move 3. The solution is to send the corresponding board recursively to the getBestMove function.</p><p>You might be thinking, “But wait! Our opponent plays the next move.” That’s right. Let’s find out what grade our opponent gets for his best future move.</p><p>Our opponent has only two possible moves:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*WGMUS4167_ub3ev-." /><figcaption><strong>Move 3–1</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/0*bUNVZCA4P7FVxeY4." /><figcaption><strong>Move 3–2</strong></figcaption></figure><p>Move 3–1 will win the game in favor of our opponent. Since we are using the exact same getBestMove function, Move 3–1 will receive a grade of 1.</p><p>This might be a bit confusing as both our victory and our loss will receive grades of 1. We need to remember that this function call belongs to our opponent, and his victory is our loss and vice versa.</p><p>We must negate any grade returned to the getBestMove function by the getBestMove function.</p><p>Move 3–1 receives a grade of 1. The getBestMove function returns a grade of 1, and we can grade Move 3 with a -1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/0*DrYhRWpB33bwSdPU." /></figure><p>In this manner, the getBestMove function continues to explore moves and consequent moves. This process will continue until:</p><ol><li>It finds a move graded with 1, in which case it will return the move immediately</li><li>It will continue until each possible move has a grade. The possible moves (with grades 0 and -1) are stored in an array</li><li>The array will then be: <br>[a] randomized <br>[b] sorted from high to low <br>[c] the first element will be returned</li></ol><p>These steps guarantee that:</p><ol><li>A losing move will be avoided unless it’s the only option</li><li>The computer player can play diversely</li></ol><h4>End Notes:</h4><ol><li>There are strong legitimate concerns over the <a href="https://en.wikipedia.org/wiki/Friendly_artificial_intelligence">risks</a> Artificial Intelligence (AI) brings with it.<br>Lets use AI for the benefit of all. <br>The best possible AI software is that which can prevent us from misusing AI.</li><li>I consulted <a href="https://twitter.com/assafweinberg?lang=en">Assaf Weinberg</a> in the process of writing the app</li></ol><p>See <a href="https://github.com/carpben/TicTacToe/blob/master/tictactoe.js">my code</a> on GitHub.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d4d5adee07" width="1" height="1" alt=""><hr><p><a href="https://medium.com/free-code-camp/building-an-ai-algorithm-for-the-tic-tac-toe-challenge-29d4d5adee07">Building an AI algorithm for the Tic-Tac-Toe challenge</a> was originally published in <a href="https://medium.com/free-code-camp">We’ve moved to freeCodeCamp.org/news</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>