<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Statecharts - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Statecharts - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sat, 30 May 2026 19:50:36 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/statecharts/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Kissing the state machine goodbye ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Recently, I have written about simplifying an event sourced application. The article starts with code from a talk by Jakub Pilimon and Kenny Bastani. And it ends with building a model  for events in the code: how they are applied, and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/kissing-the-state-machine-goodbye/</link>
                <guid isPermaLink="false">66d45de04a7504b7409c334b</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ finite state machine ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Statecharts ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Thu, 27 Jun 2019 21:05:06 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/Kissing.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Recently, I have written about <a target="_blank" href="https://www.freecodecamp.org/news/simplifying-an-event-sourced-application/">simplifying an event sourced application</a>.</p>
<p>The article starts with <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/">code</a> from a <a target="_blank" href="https://youtu.be/r7AGQsM7ncA">talk</a> by Jakub Pilimon and Kenny Bastani. And it ends with building a model  for events in the code: how they are applied, and under which  conditions.</p>
<p>The sample application is about Credit Card management. You can:</p>
<ul>
<li><strong>Assign a credit limit</strong>. But only once, otherwise the application throws an <code>IllegalStateException</code>.</li>
<li><strong>Withdraw money</strong>. But you can't make more than 45 withdrawals in a certain cycle. Or you'll get an exception as well.</li>
<li><strong>Repay money</strong></li>
</ul>
<p>I played around with the <code>CreditCard</code> class. I had a feeling that something might be wrong with the <code>withdraw</code> method. So I wrote a test that checks for the correct behavior.</p>
<pre><code class="lang-java"><span class="hljs-meta">@Test(expected = IllegalStateException.class)</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdrawWithoutLimitAssignedThrowsIllegalStateException</span><span class="hljs-params">()</span> </span>{
    CreditCard card = <span class="hljs-keyword">new</span> CreditCard(UUID.randomUUID());
    card.withdraw(BigDecimal.ZERO);
}
</code></pre>
<p>The test attempts to withdraw an amount of zero. But no credit limit  has been assigned before. The application should reject this, and throw  an <code>IllegalStateException</code>.<br>Instead, the application threw a <code>NullPointerException</code>.</p>
<p>The application assumed that the limit had been assigned before.<br>Now: this is a sample application. If it covered all cases it probably wouldn't be as understandable as it is.</p>
<p>Let's pretend we're dealing with a real world application. What if  the required order of commands/events depends on a multitude of  conditions and states?</p>
<p>If you have ever tried to implement this with conditional statements  only, you probably know it's easy to lose the overview. But there is a  standard solution for managing complicated flows and changes in  behavior.</p>
<h2 id="heading-state-machine-to-the-rescue">State machine to the rescue</h2>
<p>In computer science, state machines have been around for decades.  They are well understood in theory. They are battle proven in practice.  They are the de facto standard for dealing with state dependent  behavior.</p>
<p>So I decided to create a UML state machine model for the sample  application. I asked myself first: Do I want to deal with commands or  events in the state machine?</p>
<p>Commands are about something the application should do in the future.<br>Events are about something that has happened in the past.</p>
<p>I wanted to <em>prevent</em> withdrawals without a credit limit assigned.<br>So the state machine model needed to deal with commands. </p>
<p>The syntax of a transition in the diagram is <code>command[condition] / commandHandler()</code>. It means: when a command object has been received, and the condition is  fulfilled if present, handle the command and go to the next state.</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--IsFVxafc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/3laq9tz8h82nwvjsmugv.png" alt="State machine" width="600" height="400" loading="lazy"></p>
<p>The model fixes what is allowed to happen, and what not. For example: repaying is only possible after withdrawing.</p>
<p>But that precision has a price. If you want the state machine model  to be executed and to control the behavior at runtime, you need to model  every possible transition from every state. Including its condition, if  there are two transitions with the same event.</p>
<p>That's why there is a lot more repetition in the state machine than in the original code with the <code>if</code> statements. A way to reduce the amount of repetition is to use <em>super states</em> and <em>sub states</em>:</p>
<p><img src="https://res.cloudinary.com/practicaldev/image/fetch/s--CCZSYf5s--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://thepracticaldev.s3.amazonaws.com/i/2cwl67ddaa64l2szlp4s.png" alt="State machine with sub states" width="600" height="400" loading="lazy"></p>
<p>It is easy to define state dependent behavior in a state machine model. But a state independent rule like <em>in any state (when condition X holds), do Y</em> leads to several transitions. For example, I needed to add <code>requestToCloseCycle</code> to every super state.</p>
<p>You need people with the right skills to create the models. And it's  not easy to communicate about the models with non-technical  stakeholders. It's not the way they normally speak about user journeys.</p>
<h2 id="heading-saying-goodbye">Saying goodbye</h2>
<p>It seems there are two options so far.</p>
<p>In the left corner: the <code>if</code> statement. Easy to start  with. Low overhead. Best fit for applications that have no complicated  flows of behavior. But it's easy to lose the overview when the behavior  gets complicated.</p>
<p>In the right corner: the executable state machine model. Powerful.  Proven. Precise. Gives you an overview of the behavior. But it's hard to  define state independent rules. And state machine models are difficult  to communicate about with non-technical stakeholders.</p>
<p>I stand in the third corner. I have found an alternative to state machines.<br>A solution that</p>
<ul>
<li>enables you to define conditions. But you don't have to in most cases.</li>
<li>makes state dependent and independent rules equally easy to specify.</li>
<li>uses language that all stakeholders can relate to.</li>
</ul>
<p>Before I dig into the details, here's the sample state machine model rewritten using that solution:</p>
<pre><code class="lang-java">Model model = Model.builder()
  .useCase(useCreditCard)
    .basicFlow()
        .step(assigningLimit).user(requestsToAssignLimit).systemPublish(assignedLimit)
        .step(withdrawingCard).user(requestsWithdrawingCard).systemPublish(withdrawnCard).reactWhile(accountIsOpen)
        .step(repaying).user(requestsRepay).systemPublish(repay).reactWhile(accountIsOpen)

    .flow(<span class="hljs-string">"Withdraw again"</span>).after(repaying)
        .step(withdrawingCardAgain).user(requestsWithdrawingCard).systemPublish(withdrawnCard)
        .step(repeating).continuesAt(withdrawingCard)

    .flow(<span class="hljs-string">"Cycle is over"</span>).anytime()
        .step(closingCycle).on(requestToCloseCycle).systemPublish(closedCycle)

    .flow(<span class="hljs-string">"Limit can only be assigned once"</span>).condition(limitAlreadyAssigned)
        .step(assigningLimitTwice).user(requestsToAssignLimit).system(throwsAssignLimitException)

    .flow(<span class="hljs-string">"Too many withdrawals"</span>).condition(tooManyWithdrawalsInCycle) 
        .step(withdrawingCardTooOften).user(requestsWithdrawingCard).system(throwsTooManyWithdrawalsException)
.build();
<span class="hljs-keyword">return</span> model;
</code></pre>
<p>As you can see, the model is <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCardAggregateRoot.java">in the code</a>.  A model runner executes this model. The runner reacts to commands/events, similar to a state machine.</p>
<p>The basic flow is the "happy day scenario". The steps of a user to  reach her goal. The other flows cover alternative and error scenarios.</p>
<p>A flow can define an <em>explicit condition</em> for its first step to run - e.g. <code>after(...)</code>, <code>anytime()</code> or <code>condition()</code> in the sample.<br>If a flow has an explicit condition, the flow starts when the condition  is fulfilled and the runner is currently in a different flow.<br>If a flow has no explicit condition (e.g. the basic flow in the sample),  the first step runs after the runner has started, when no step has been  run so far.</p>
<p>Starting with the second step of a flow, each step has an <em>implicit condition</em>.  That condition is: run the step after the previous step in the same  flow, unless a different flow with an explicit condition can start.<br>So in contrast to state machines, you don't need to specify the conditions after the first step.</p>
<p>Internally, state depending behavior is realized by checking a condition.<br>Every step contains its complete condition that defines exactly when the step can run. That's how <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">requirements as code</a> can treat state dependent and independent behavior alike.</p>
<p>Have a look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/tree/master/requirementsascodeexamples/helloworld">further examples</a> to dig deeper.</p>
<h2 id="heading-when-to-use-requirements-as-code">When to use requirements as code</h2>
<p>Many applications have dynamic internal behavior. This is true for  distributed applications in particular. They need to deal with the fact  that "the other party" is not available.</p>
<p>But from a user's perspective, these applications look quite  predictable and regular. When I want to watch a show on Netflix or  Amazon Prime, I follow the exact same steps each time until I can watch  it. It looks like one step just follows the other.</p>
<p>That's the sweet spot for requirements as code, if used as an alternative to a state machine: defining the <em>visible behavior</em> of an application.</p>
<h2 id="heading-how-the-credit-card-application-works-now">How the Credit Card application works now</h2>
<ul>
<li>A <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/EventsourcingApplication.java">client</a> sends a command to the <code>CreditCardAggregateRoot</code></li>
<li>The <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCardAggregateRoot.java">CreditCardAggregateRoot</a> uses the event repository to replay all the events for the credit card, to restore it</li>
<li>The <code>CreditCardAggregateRoot</code> uses the above model to dispatch the command to a command handling method</li>
<li>The command handling method produces an event and applies it to the <code>CreditCard</code> instance.</li>
<li>The event handling model of the <a target="_blank" href="https://github.com/bertilmuth/requirementsascode/blob/master/requirementsascodeexamples/creditcard_eventsourcing/src/main/java/creditcard_eventsourcing/model/CreditCard.java">CreditCard</a> instance dispatches the event to a state changing method</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed my article. I also want to invite you to look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">the library</a> that I used throughout the article. Try it out in practice, and let me know the result.</p>
<p><em>If you want to keep up with what I'm doing or drop me a note, follow me on <a target="_blank" href="https://www.linkedin.com/in/bertilmuth/">LinkedIn</a> or <a target="_blank" href="https://twitter.com/BertilMuth">Twitter</a>. To learn about agile software development, visit my <a target="_blank" href="https://skl.sh/2Cq497P">online course</a>.</em><br><em>Last edited April 27, 2020: updated event sourcing process</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Patterns for using React with Statechart-based state machines ]]>
                </title>
                <description>
                    <![CDATA[ By Shawn McKay Statecharts and state machines offer a promising path for designing and managing complex state in apps. For more on why statecharts rock, see the first article of this series. But if statecharts are such an excellent solution for manag... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/patterns-for-using-react-with-statechart-based-state-machines-33e6ab754605/</link>
                <guid isPermaLink="false">66c35c7ee9895571912a0cec</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Statecharts ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 01 Aug 2018 21:50:47 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*m3KYQevuZRrlEgP684bk_Q.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shawn McKay</p>
<p>Statecharts and state machines offer a promising path for designing and managing complex state in apps. For more on why statecharts rock, see <a target="_blank" href="https://medium.freecodecamp.org/how-to-visually-design-state-in-javascript-3a6a1aadab2b">the first article</a> of this series.</p>
<p><strong>But if statecharts are such an excellent solution for managing UI &amp; state in Javascript (JS), why isn’t there more momentum behind them?</strong></p>
<p>One of the main reasons statecharts have not grown in popularity within the front-end world is that best practices have yet to be established. It’s not abundantly clear how to use state machines with popular component-based UI libraries such as React, Vue, or Angular.</p>
<p>While it may be too early to declare best practices for statecharts in JS, we can explore some patterns used by existing state machine integration libraries.</p>
<h3 id="heading-statechart-machine">Statechart machine</h3>
<p>Statecharts work both for visual design and as the underlying code for a graph-based state machine.</p>
<p>Bear in mind that we’re in the early days of using statecharts with JS, and it may be worth experimenting with a variety of libraries or even developing your own. That being said, <a target="_blank" href="https://github.com/davidkpiano/xstate">XState</a> is currently leading the pack for statechart machine libraries in JS.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/7jucyNQr2bs02ta20zRnBRj-uUQ0DvKFoLLk" alt="Image" width="800" height="1118" loading="lazy">
_[https://gist.github.com/ShMcK/769a179f89f1d7db1f83363cc2e42399](https://gist.github.com/ShMcK/769a179f89f1d7db1f83363cc2e42399" rel="noopener" target="<em>blank" title=")</em></p>
<p>The above state machine code can generate a much more readable statechart diagram when passed as JSON to the <a target="_blank" href="https://github.com/davidkpiano/xstate#visualizer">XState Visualizer</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/eUlLxIJzgceeXmtnFNwZVl9ZdPtOJm5GUFAx" alt="Image" width="800" height="231" loading="lazy"></p>
<p>You can even work the other way, starting by visually designing and then exporting to an XState configuration using <a target="_blank" href="http://sketch.systems">sketch.systems</a>. We don’t have all the pieces in one place yet, but there are no serious technical barriers to an open source solution.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/q3OYT9hd3E2M93-qLHciSoHceVwcC5ELrs7e" alt="Image" width="472" height="423" loading="lazy"></p>
<p>Now that we have an idea of what XState does, let’s look at what it doesn’t do.</p>
<blockquote>
<p>XState Tagline: “stateless finite state machines and statecharts”.</p>
</blockquote>
<p>So what does it mean for a state machine to be <strong>stateless</strong>?</p>
<h3 id="heading-stateless-machines">Stateless machines</h3>
<p>Stateless machines offer an unopinionated <strong>blueprint</strong> for state management — a kind of “roll your own” solution that doesn’t dictate where or how state in your application is stored.</p>
<p>Much like a presentational component, a stateless machine is made of pure functions, is immutable, and maintains no state. It tracks no past, current, or future — but it can be used to help you calculate each.</p>
<p>Managing your state can be as easy as storing it in a local state variable.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/kAqxO0cq9qT-nMGfnhlsFaSxINVkpP233WSb" alt="Image" width="800" height="486" loading="lazy"></p>
<p>Stateless machines don’t give you much out of the box. To trigger a transition, we must always pass in the current state node in to find the next. XState can let you know which actions should be fired on each state change, but you’ll have to find a way to manage the actions yourself.</p>
<p>If you’re interested in a more complete solution, consider making your state machine <strong>stateful.</strong></p>
<h3 id="heading-stateful-machines">Stateful machines</h3>
<p>A stateful machine tracks your node position on the state graph and manages the firing of actions. There is no need to pass in the current state on transitions — it tracks your current state node.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/D1FxAQN9JgcjK9TwGl1TxXHUewyTFZBAIvn9" alt="Image" width="800" height="231" loading="lazy"></p>
<p>As a summary, the instance of the stateful machine above:</p>
<ul>
<li>determines the green state position at “Ringing”</li>
<li>limits the possible purple’active transition events to <code>CANCEL</code> or <code>SNOOZE</code></li>
<li>fires the <code>startRing</code> action on entry</li>
<li>fires the <code>stopRing</code> action on leaving the state</li>
</ul>
<p>Of course, there is more than one way to create a stateful machine. We’re back to the question of where to manage state:</p>
<ul>
<li>within the existing component state?</li>
<li>in a connected state machine?</li>
</ul>
<p>Let’s explore some design patterns with examples, starting with <strong>stateful components</strong>.</p>
<h3 id="heading-stateful-components">Stateful components</h3>
<p>A stateful component, as you might imagine, manages state within the component, or within a wrapping higher-order component. In React, this would be as <code>state</code>. Storing state within a UI library ensures that changes won’t be missed and will trigger re-renders.</p>
<p>This is the approach of a library called <a target="_blank" href="https://github.com/MicheleBertoli/react-automata">React-Automata</a> that uses a higher-order component initiated by <code>withStatechart</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/6hX-DEHCmfZZbMsyp8bE4MyZgqmKr-BmqfR3" alt="Image" width="800" height="365" loading="lazy"></p>
<p>React-Automata offers several patterns for using statecharts with components:</p>
<ul>
<li>state from props</li>
<li>conditional rendering from a context</li>
<li>state from actions</li>
</ul>
<p>We’ll go over each pattern and consider the pros and cons.</p>
<h4 id="heading-state-from-props"><strong>State from Props</strong></h4>
<p>Passing state directly into components seems like the most obvious solution.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/CfqmdxiglBKlVIBCSOBMrKoSnnjvqYuwsBtD" alt="Image" width="518" height="446" loading="lazy"></p>
<p>In React-Automata, state can be passed by accessing it on the <code>machineState</code> prop — a reference to the actual state machine.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Gr113rIoWhqeyyCvUT3GSjebtKN4y14VtQCg" alt="Image" width="800" height="440" loading="lazy"></p>
<p>But be wary, <strong>this is by no means best practice</strong>. In the example above, the integration has <strong>coupled</strong> the statechart to the component, leading to a poor separation of concerns.</p>
<p>Consider that the statechart and components can allow for a clean divide as they solve different problems:</p>
<ul>
<li>statecharts: <strong>when</strong> things happen, for example, enter state, actions fired</li>
<li>components: <strong>how</strong> and <strong>what</strong> happens, for example, the view, user interactions</li>
</ul>
<p>Alternatively, you could decouple the component from the state machine by conditionally rendering with a default of no render.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/FzXtUh2ITWYn0AePrsqZZ3Tme-8hcrwfnwhh" alt="Image" width="800" height="641" loading="lazy"></p>
<p>Certainly, there must be a more natural way to set up conditional rendering without having to turn all your renders into <code>if/else</code> and <code>switch</code> statements.</p>
<h3 id="heading-conditional-rendering-from-a-context"><strong>Conditional rendering from a context</strong></h3>
<p>State accessed by a context doesn’t need to be passed directly.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/I4yIlaK9q13fHzI7H20RN7XcyM0KbCgtgO6d" alt="Image" width="581" height="601" loading="lazy"></p>
<p>React-Automata provides a pattern for conditional rendering of child components using React’s context and a <code>&lt;Sta</code>te&gt; component. Note tha<code>t the</code> value property can match on a string, array of strings, or even a glob-based pattern.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/9g7rEjSlDp5DZtsunVJMkr4lnLQzBzglx3k4" alt="Image" width="800" height="616" loading="lazy"></p>
<p>If the state value matches <code>Ringing</code>, the children inside of the <code>State</code> component will render. Otherwise, nothing.</p>
<p>State from context can help clarify the number of possible finite state view combinations. As in the case above, it’s clear there are only two possible configurations.</p>
<p>If view configurations start to get out of hand, React-Automata offers a render prop pattern that passes in a boolean based on the value.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/JR-iT393EkkGzs5vqgMcMdI1LnAbiE9Bze3-" alt="Image" width="800" height="566" loading="lazy"></p>
<p>Similarly, it’s possible to conditional render based on context actions.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/EVHZhlEFxplZquVI9C9pihSIEW1jQHhsYTkl" alt="Image" width="800" height="566" loading="lazy"></p>
<p>Conditionally rendering based on state or actions maintains a coupling between the statechart and components, but less explicitly through context. How might you give components their isolated state apart from statecharts?</p>
<h4 id="heading-state-from-actions"><strong>State from actions</strong></h4>
<p>It’s possible to use statecharts to update the internal state of a linked component using actions as triggers.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xe2pZXijfRO5YUV19NX1LBZfMdUONssLBqnY" alt="Image" width="800" height="500" loading="lazy"></p>
<p>React-automata checks the methods on a component and calls the functions if the names match the actions being fired.</p>
<p>As an example, the onEntry action <code>startRing</code> is fired as the state machine enters <code>Ringing</code>, causing the <code>AlarmClock</code> state to change to <code>ringing</code>. On leaving the <code>Ringing</code> state, <code>stopRing</code> is fired, and <code>ringing</code> is set to <code>false</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/mrkROREfV5flyHGYngYrWHyFSWVHSNS-vrdq" alt="Image" width="800" height="717" loading="lazy"></p>
<p>Note that, although of these methods are called with params, the methods already have access to whatever they need from <code>machineState</code> through props.</p>
<p>Using internal component state managed through actions leads to a strong decoupling of components from state charts. However, it can also create a degree of clutter or confusion in components. It is not explicitly clear how or when methods will be called without examining the names of actions in the statechart. For this reason, I often call my actions and methods <code>enterX</code> or <code>exitX</code> in order to make it explicitly clear why and where they are being fired.</p>
<h3 id="heading-external-state-machines">External state machines</h3>
<p>Another option worth considering is storing state outside of your UI framework. As with other state management libraries like Redux, components can be connected to an external state machine and updated with “on state change” and “on action” events.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Cpdc3lKa2eFWX82Vu7SoPHXmcb4mWTpKAY9b" alt="Image" width="511" height="378" loading="lazy"></p>
<p>As an example, <a target="_blank" href="https://github.com/avaragado/xstateful">XStateful</a> is a wrapper around XState that handles state, transitions, emitting events, triggering actions, and more.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/8KMPv6PSbvRMQXebFnVL6PQKY6nlJn40TUHC" alt="Image" width="800" height="574" loading="lazy"></p>
<p>XStateful works well with a React connector called <a target="_blank" href="https://github.com/avaragado/xstateful-react">XStateful-React</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/FBxnxH0x9tzYnBpMJvtyLgndKtMlhZxCgPrw" alt="Image" width="525" height="544" loading="lazy"></p>
<p>XStateful-React has much in common with React-Automata. But there is at least one signficant difference — the state machine instance is not managed within any component.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/vjYPif3blpUKKDprAMfUigXfz5r1vpyPqzfG" alt="Image" width="553" height="254" loading="lazy"></p>
<p>So how does external state from reducers work in XStateful?</p>
<h3 id="heading-state-and-data">State and data</h3>
<p>Applications often require more than just the state node in a state graph— they require data as well. Often this data needs to be synced across components, in a way that can be frustrated if it must be passed from the uppermost shared parent.</p>
<p>There are existing popular solutions for syncing data, such as Redux, or <a target="_blank" href="https://github.com/rematch/rematch">my state management wrapper for Redux</a>. Unfortunately, these don’t play well with many state wrappers such as React-Automata due to an open issue with passing refs in React Redux (see this <a target="_blank" href="https://github.com/reduxjs/react-redux/issues/914">open issue with connect() and React.forwardRef</a>).</p>
<p><strong>A complete state solution should manage both state and data.</strong></p>
<p>XStateful offers just such a state and data solution using a <a target="_blank" href="https://blog.kentcdodds.com/the-state-reducer-pattern-%EF%B8%8F-b40316cfac57">state reducer pattern</a>, similar to Redux.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/8xMXiOZdWjR-P3ctNVeMB4LE4v7ZvPTUuybt" alt="Image" width="622" height="762" loading="lazy"></p>
<p>State machine subscribers listen and update changes based on actions emitted from the state machine. Note that XState refers to data as <strong>extended state</strong>, or <code>extstate</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/hdrk3HqBbfBkNfd2gWC1VEKHSj1Py-isMhIA" alt="Image" width="800" height="793" loading="lazy"></p>
<p>This particular Reducer pattern may seem unfamiliar, however, it’s heavily used in projects such as <a target="_blank" href="https://reasonml.github.io/reason-react/docs/en/state-actions-reducer.html">ReasonReact</a>.</p>
<p>Data can also be accessed in conditional renders on the property <code>cond</code>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4jrU5i-bzBirWwqhn3ojmLpGkk3peLjRY8BW" alt="Image" width="800" height="510" loading="lazy"></p>
<p><strong>Be careful</strong> with using state to conditionally render components, as it creates a non-deterministic set of possible states. No longer are you limited to the number of states, but now to the number of state and data combinations. You lose out on deterministic features, discussed later in the testing section.</p>
<p>This data can be passed into your component using a render prop pattern.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/r63dar8rwDffa7lnxUoUjYpeUlY0gGfl8YTT" alt="Image" width="800" height="510" loading="lazy"></p>
<p>There is less of a need for state management tools like Redux if data can be stored within a complete state machine tool like XStateful.</p>
<h3 id="heading-testing">Testing</h3>
<p>State machines also offer a better path for front-end testing.</p>
<p><strong>The deterministic nature of state machines creates the possibility of simplified front-end testing.</strong></p>
<p>In React-Automata you can autogenerate snapshot tests using <code>testStatechart</code>, a method that takes the XState configuration and the component.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/32aHtwD8mghMTy8m1zwteefbxEX8wSSDhWgl" alt="Image" width="800" height="528" loading="lazy"></p>
<p><code>testStatechart</code> runs through the state graph and creates a <a target="_blank" href="https://jestjs.io/docs/en/snapshot-testing">Jest snapshot test</a> for each possible configuration of the component. It will toggle on and off your various <code>&lt;State</code> /<code>&gt;, &lt;</code>Action /&gt; components, leading to a recording of all possible conditional rendering combinations.</p>
<h3 id="heading-devtools">Devtools</h3>
<p>Devtools play an active role in what makes a library developer-friendly — debugging can be the hardest or most straightforward part of your job.</p>
<p>In this respect, React-Automata offers a helpful integration via Redux Devtools. Each connected component becomes a named instance in the devtools, and each transition and action are displayed chronologically as actions are presented in Redux devtools.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/q9HFedJVnw4i1qaVE26n3x9lB03JgZ0jfBfE" alt="Image" width="800" height="280" loading="lazy"></p>
<p>XState offers an entirely new set of variables to track. Consider the following <a target="_blank" href="https://codepen.io/mogsie/pen/YapZjZ">example by Erik Mogensen</a> on the kinds of information an XState debugger may track.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/culeh91to9lyS13adQMF0gyawStWoPWeAmpR" alt="Image" width="800" height="213" loading="lazy"></p>
<p>This is not to say that state machine devtools need to look like our existing devtools. State machine devtools present an opportunity for a more visual debugging experience.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>While we’re still in the early days of statecharts in JS, there are enough options available to start developing applications on top of XState. We can learn from these development patterns to both improve available libraries and to create tools to support the enormous potential of visual-based programming.</p>
<p>Having developed applications with statecharts over the past three months, I’ve personally found these new patterns to be a breath of fresh air. Collaboration has become much more comfortable, as team members can visually grasp the underlying logic of a significant and growing system.</p>
<p>My hope is that this article will help others find statechart-based development more approachable. If you found it helpful, give a clap and pass it on :)</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to visually design state in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Shawn McKay A roadmap for developing applications with state machines & statecharts _Photo by [Unsplash](https://unsplash.com/photos/lRssALOk1fU?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText" rel="noopener" target="_blank" ti... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-visually-design-state-in-javascript-3a6a1aadab2b/</link>
                <guid isPermaLink="false">66c356087ef110ecbf367adc</guid>
                
                    <category>
                        <![CDATA[ Statecharts ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 20 Jul 2018 15:39:10 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*yZWunekTH1rb4DgIGwoPXw.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Shawn McKay</p>
<h4 id="heading-a-roadmap-for-developing-applications-with-state-machines-amp-statecharts"><em>A roadmap for developing applications with state machines &amp; statecharts</em></h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/Aok0bLw6goCsqIi-E0awku8Os9f6qvl969AH" alt="Image" width="800" height="522" loading="lazy">
_Photo by [Unsplash](https://unsplash.com/photos/lRssALOk1fU?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="_blank" title=""&gt;rawpixel on &lt;a href="https://unsplash.com/search/photos/map?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText" rel="noopener" target="<em>blank" title=")</em></p>
<p>Why does state management seem particularly tricky in JavaScript? Is it the inherent complexity of modern apps, or just the tools? How do other fields of engineering develop reliable and predictable systems? Is it possible to draw a system and transform it into code, and vice versa?</p>
<p>Let’s explore a paradigm shift in state management towards visually designing systems with <strong>state machines</strong> &amp; <strong>statecharts</strong>.</p>
<h3 id="heading-concepts-gt-libs">Concepts &gt; Libs</h3>
<p>State management has been on my mind for a while now. I’ve experimented with various state management libraries: Flux, Reflux, Redux, Dva, Vuex, Mobx, and also <a target="_blank" href="https://github.com/rematch/rematch">my own</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/QgmolkLumTmVxfq7iqvnfE61r7hf4cElnIKG" alt="Image" width="800" height="462" loading="lazy"></p>
<p>There’s no point arguing which is the 10x solution. State libs are different flavors with the same ingredients. They are a piece of the puzzle—they make it easier to sync and connect data.</p>
<p>The solutions that require our focus next concern the bigger picture:</p>
<p>We need to get better at <strong>planning &amp; designing systems</strong>.</p>
<h3 id="heading-break-all-the-things">Break All The Things</h3>
<p>Think of a user interface that you would consider <strong>elegant</strong>. Something built to withstand a barrage of random user interactions — you know, the kind of unpredictability that occurs when a user pushes a button more times than expected, interacts with inputs in an unexpected order or otherwise leads you to question your faith in humanity. Real life is hard on systems.</p>
<p>I’ll predict the project you’re thinking of.</p>
<p>Well… you’re probably not thinking of something built for the web, where the philosophy seems to be “move fast and break things”.</p>
<p>Judging by the frequency of updates, you’re probably not thinking of mobile either.</p>
<p>You’re probably not even thinking of something built recently. We don’t necessarily seem to be getting better at building reliable products.</p>
<p>I think I know what you’re thinking of…</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/t8w6rHEwXZ-55I0XjfhIHQhs55ZDjuJV7Flj" alt="Image" width="800" height="712" loading="lazy"></p>
<p>Am I right? ….No?</p>
<p>You might not even recognize this as the Sony Walkman of the 1980s.</p>
<p>As a kid, I received a cassette player like this from a friend who had upgraded to a portable CD player. I understand that some younger readers may find the mention of both of these devices unfamiliar — think of the Walkman as an iPhone, but with larger buttons and greater destructive potential. My primary mission: break it.</p>
<p>I would try all combinations of buttons to see what might happen:</p>
<ul>
<li>Try to eject while the tape was fast forwarding</li>
<li>Hold fast-forward and rewind down at the same time</li>
</ul>
<p>Try as I might, the Sony Walkman held up better than most websites do today.</p>
<h3 id="heading-engineering-interfaces">Engineering Interfaces</h3>
<p>Electronics like the Walkman withstood the gauntlet of user testing without any capacity to hide or disable elements of the user interface. Any button could be pressed at any time, anything could happen. And yet it seemed <strong>unbreakable</strong>.</p>
<p>It led me to wonder:</p>
<p><strong>Perhaps electronics offer a better paradigm for how we can build interfaces on the web.</strong></p>
<p>What can we learn from the <strong>ancient</strong> design process of electronics? How can we better <strong>engineer</strong> applications? Marty, we need to go back to the future!</p>
<h3 id="heading-electronics-amp-the-web">Electronics &amp; The Web</h3>
<p>Can electronics teach us a better way to create applications in the browser?</p>
<p>Consider that <strong>components</strong> produced one of the most significant shifts in web development over the past five years. Perhaps there are other concepts we can borrow from electronic engineering?</p>
<p>As web developers, we’ve had it good. Like. Really good. Found a bug? Deploy an update to your server within the hour.</p>
<p>Other fields of engineering aren’t so forgiving. A problem in hardware often results in a device going in the trash. Embedded developers must be careful to ensure a firmware update doesn’t drain the battery or crash all existing devices.</p>
<p><strong>Web developers have the luxury to be reckless.</strong></p>
<p>Not to mention, app developers have rarely faced the same resource limitations as the creators of electronic devices. When was the last time your primary focus was <strong>performance</strong> and <strong>memory usage</strong>, rather than just making the damn thing work? A threshold of 60 frames per second is a low bar. But the bar is rising as we start building increasingly complex apps to run on less powerful mobile and IoT devices. We are bordering on an engineering problem that low-level engineers have experienced for decades.</p>
<p><strong>Constraints breed creativity</strong>. Limitations lead to better design.</p>
<p>To see how embracing limitations can lead to better design, we’ll need to drive back towards basic state management fundamentals.</p>
<h3 id="heading-ye-oldnew-state-management-fundamentals">Ye Old/New State Management Fundamentals</h3>
<p>The direction of conversations in the web community tends to lean towards NPM packages rather than fundamental computer science principles.</p>
<p><strong>Engineers aren’t asking “which library is better? as much as they’re asking “how do we design a better system”?</strong></p>
<p>We can start with some basic principles of good design:</p>
<ul>
<li>distinguish between indeterminate <strong>data</strong> and finite <strong>states</strong></li>
<li>limit possible transitions from one state to another</li>
<li>design visually</li>
</ul>
<p>I’ll work through these along with my own path, and 8 realizations that followed.</p>
<h3 id="heading-1-state-data">1. State !== Data</h3>
<p>In programmatic systems, the difference between <strong>state</strong> and <strong>data</strong> is blurry. They both live in memory, and so are treated the same.</p>
<p>In React, <strong>state</strong> and <strong>data</strong> share the same name and mechanisms:</p>
<ul>
<li>getting: <code>this.state</code></li>
<li>storing : <code>this.state = {}</code></li>
<li>updating: <code>this.setState(nextState)</code></li>
</ul>
<p>In electronics, there is less confusion over the distinction between <strong>state</strong> and <strong>data</strong>.</p>
<p><strong>State</strong> represents a finite number of modes that the system can be in — often defined by the circuitry itself. For our Walkman, think “Playing”, “Stopped”, “Ejected”. Like a “mode” or “configuration”, state is countable.</p>
<p><strong>Data,</strong> on the other hand, is stored in memory with a nearly infinite set of possible settings. For our Walkman, think of the track that is playing, “Song 2”. Data, like music, may have infinite possibilities.</p>
<p>Whatever this <code>DataLoader</code> component below does, the state can only generate a limited set of views: “loading”, “loaded”, or “error”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1qn8vO-gCRq04nCZLSuPHRXBb7O8csOWr7bc" alt="Image" width="800" height="1414" loading="lazy"></p>
<p>Separating state and data can lead to less confusion, and allows us to construct applications based on <strong>finite state machines</strong>.</p>
<h3 id="heading-2-state-is-finite">2. State is Finite</h3>
<p>Electronics developers have long known that a predictable interface is one with a limited and controlled number of states. Without a controlled number of states, systems become difficult to debug and impossible to thoroughly test.</p>
<p>In a finite state machine, states are explicitly defined. <strong>Transitions</strong> are the set of possible <strong>events</strong> you can trigger to move between states.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/GzMSdQyOzGH82UmnnebDYD4gjx56cInsCWww" alt="Image" width="520" height="486" loading="lazy"></p>
<p>As an example, triggering a transition with the event “STOP” will move the state to “Stopped”.</p>
<p>In React, we could define a basic Walkman as having at least two states: “Stopped” or “Playing”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/w9GtPNNc0Qkk7-BLfkNclkArMmbkLlEX0niP" alt="Image" width="800" height="982" loading="lazy"></p>
<p>Check out this <a target="_blank" href="https://codesandbox.io/s/2v55q3j5q0">CodeSandbox</a>.</p>
<p>In a finite state machine, the system is always in one of the possible configurations. The view has no possibility of being anything but “Playing” or “Stopped”. Testing both can give us confidence the system works the way it should.</p>
<h3 id="heading-3-manage-complexity-in-state-machines">3. Manage Complexity in State Machines</h3>
<p>Let’s look at what happens when we start adding two new states to the state machine example: “Rewinding” &amp; “FastForwarding”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/eRuPPcRGv7MOZrJ0Jch9H0HUErUksz8iwSQb" alt="Image" width="800" height="1085" loading="lazy"></p>
<p>When states are equivalent, they are deceptively easy to add. Each state is like its module that can be developed and tested in isolation. But be careful, state transitions should not always be possible.</p>
<p>We should worry about <strong>uncontrolled transitions</strong> between states.</p>
<p>Maybe you caught it. We introduced a bug above. Take a minute and see if you can discover what went wrong.</p>
<h3 id="heading-4-guard-transitions">4. Guard Transitions</h3>
<p>It seems the cassette tape is all tangled up as we’ve allowed users to jump between <code>rewinding</code> and <code>fastForwarding</code> without stopping the tape in between.</p>
<p>As a solution, we can add <strong>guards</strong> to our state transitions. Guards are conditions that must be met for a transition to occur. As an example, we can ensure that the events <code>FASTFORWARD</code> , <code>REWIND</code> , &amp; <code>PLAY</code> can only trigger when the state is “Stopped”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/-KBLie7LReY9irWrdfGqQrgeDVQUmPTZ12um" alt="Image" width="800" height="663" loading="lazy"></p>
<p>Unexpected state transitions are bound to happen unless we rethink the way we plan and design our state management.</p>
<p>As we add additional states like <code>ejected</code>, we have to think through which state transitions can be allowed and under which conditions. With a Walkman, you can eject the tape by pressing stop while the tape is in the stop mode. To add this functionality, we have to add even more guards and determine which transitions are possible.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/TNd2gmZ6olbEgYRznbzFd-ULawTF-Px6ceFG" alt="Image" width="800" height="418" loading="lazy"></p>
<p>The likelihood of <strong>unhandled state combinations</strong> multiplies as additional states are added. This is not a scalable solution. Each additional state results in a check of all transition guards.</p>
<p>It starts to feel more like state is managing you.</p>
<p>The problem with managing guards stems from the way state is being represented: “Stopped”, “Playing”, “Rewinding”.</p>
<p>The ideal data structure for state is not a string or an object.</p>
<p>But then what is it?</p>
<h3 id="heading-5-state-is-a-graph">5. State is a Graph</h3>
<p>The ideal data structure to represent state is often a graph. <strong>State graphs,</strong> commonly known as <strong>state diagrams</strong>, provide an intuitive way to design, visualize, and control state transitions at each node.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/OzKS67LoGJGc4l8Iux99Zp-8mKS9Z7OLEyES" alt="Image" width="800" height="200" loading="lazy"></p>
<p>This is not new news — electronic engineers have been using state diagrams to describe complex systems for decades.</p>
<p>Let’s look at an example on the web. AWS Step Functions provide a visual interface for graphing the workflow of an application. Each node controls a lambda — a remote function called in the cloud — with the output of each function triggering the input of the next.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/w7YWq3WEbXndpgpj8N0aihnKvIlsA26CVD8m" alt="Image" width="800" height="382" loading="lazy">
<em>AWS Step Functions</em></p>
<p>In the example above, it’s clear to see how a user’s actions move through each step, including possible errors and how to handle them. Adding additional steps doesn’t result in exponential increases in complexity.</p>
<p>An engineer might remark how much Step Functions have in common with <strong>PLC (Programmatic Logic Controller) Block Diagrams</strong>. A designer might remark how much they have in common with <strong>workflow</strong> diagrams. Shouldn’t the way we design state have more in common with the way we plan applications?</p>
<h3 id="heading-6-scaffold-on-state-graphs">6. Scaffold on State Graphs</h3>
<p>State graphs become the scaffolding for your application.</p>
<p>As an example, a state graph of our walkman could produce a more visually understandable and approachable representation.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/2zAjA1aOXrHbugxcUeQN3WNJjz0W64g5AkNP" alt="Image" width="800" height="379" loading="lazy">
<em>Walkman State Graph</em></p>
<p>Without delving into code concerning guards, we can tell there should be no possibility to jump from “Rewinding” to any other state but “Stopped”. Rather than outlining all the transitions your interface shouldn’t do, you lay out what it can do. Development shifts from a defensive <strong>bottom-up</strong> coding approach to a <strong>top-down</strong> designing approach. This shift alone is 10x.</p>
<p>State graphs are more intuitive, more accessible to debug, and more able to absorb changes in requirements. Alongside state machines, changes in each state can be isolated from their neighboring states. Not to mention that much of the complex transition “guard” logic can be encompassed in a visually comprehensible format.</p>
<p><strong>Unfortunately, state graphs can be a ticking time bomb.</strong></p>
<p>Densely connected graphs don’t scale. Consider what would happen if we added another 4 states to the graph above. Readability reduces and repetition increases, with entangled arrows pointing in all directions competing for space. This <strong>spaghettification</strong> of a state graph is known as a <strong>state explosion</strong>.</p>
<p>Luckily, there is a way to reduce the visual complexity of designing complex state graphs using a formalized way of describing systems: let’s explore <strong>statecharts</strong>.</p>
<h3 id="heading-7-master-statecharts">7. Master Statecharts</h3>
<p>I first learned about statecharts from <a target="_blank" href="https://medium.freecodecamp.org/how-to-model-the-behavior-of-redux-apps-using-statecharts-5e342aad8f66">Luca Matteis’ presentation on How to model the behavior of Redux apps using statecharts</a> at the Vancouver React Meetup. The next day at work, I brought up this “new” paradigm for state management, only to find many of my engineering co-workers were already familiar with the concept. I work at an <a target="_blank" href="http://semios.com">IOT based company</a> alongside many hardware and embedded developers. We’re hiring ;)</p>
<p>The concept of a statechart dates back to 1987 when mathematician David Harel published <a target="_blank" href="http://www.inf.ed.ac.uk/teaching/courses/seoc/2005_2006/resources/statecharts.pdf">a paper</a> on visually describing complex systems, such as the below example of a quartz watch.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/f-quhmLt3aFmT5fJzios3yvARyEjubamkyV6" alt="Image" width="800" height="434" loading="lazy"></p>
<p>Statecharts are both intuitive and easy to master once you understand the language.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/zSumkSO2cqGP-rYYmCoLmvfpErtW6GDCVxRz" alt="Image" width="800" height="213" loading="lazy"></p>
<p>Statecharts introduce a variety of new state types:</p>
<ul>
<li><strong>initial state</strong> — the starting state marked by a dot with an arrow.</li>
<li><strong>nested states</strong> — states that have access to the transitions of their parent.</li>
<li><strong>parallel states</strong> — two non-touching states represented by dotted lines.</li>
<li><strong>history state</strong> — a state that <strong>remembers</strong> and can return to its previous value.</li>
</ul>
<p><img src="https://cdn-media-1.freecodecamp.org/images/oOZGxYZfej-hZFJR1ABU3NAF4YJAnW-EyyuY" alt="Image" width="800" height="140" loading="lazy"></p>
<p>Besides, statecharts can encompass how and when <strong>transitions</strong> &amp; <strong>actions</strong> are triggered:</p>
<ul>
<li><strong>transition</strong> — a function that triggers a state change based on a named <strong>event</strong>. “Stopped” → transition(‘Play’) → “Playing”</li>
<li><strong>guard</strong> — a condition that must be met for a transition to occur. For example, “play” cannot be triggered if no tape is present, or if the tape is at its end. “Stopped” → transition(‘Play’) <strong>[hasTape]</strong> → “Playing”. Multiple transitions can be possible, given an order.</li>
<li><strong>action</strong>— triggers that occur based on a state change. For example, triggering a tape to start playing when the state enters “playing”. Actions may occur <code>onEntry</code> and/or<code>onExit</code>.</li>
</ul>
<p>Rewriting the Walkman example as a statechart removes the redundancy found in the state graph. Notice how there is no longer a need for repetition with “STOP” events. Statecharts are scalable — it’s not hard to add additional parallel states such as “Recording” and “Volume”.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/dG-3oXwGlHH8n-mGMvCh8oKUBtVUd7mRiXD0" alt="Image" width="800" height="717" loading="lazy"></p>
<p>Statecharts are more than just a concept for <strong>visually</strong> describing applications.</p>
<p><strong>Statecharts can generate the state machines that underly an application.</strong></p>
<p>You can convert visuals to code, and vice versa. View your application logic as a chart, or draw it.</p>
<h3 id="heading-8-statechart-tools">8. Statechart Tools</h3>
<p>Statecharts offer a promising future for genuinely <strong>designing</strong> systems — and not just on paper. While tools have been around for other programming languages, JavaScript is just now starting to show a boom in statechart tooling.</p>
<p>C &amp; Java developers have tooling available for coding with and alongside statecharts. As an example, <a target="_blank" href="https://www.itemis.com/en/yakindu/state-machine/">Yakindu Statechart Tools</a> brings together the worlds of visual design and code. I recently learned Yakindu also includes a <a target="_blank" href="https://blogs.itemis.com/en/typescript-code-generation-with-yakindu-statechart-tools">Typescript code generator</a>.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/-zcZ55mMe5L0lysnKeFPXJlGaa7SPR2cIbqz" alt="Image" width="800" height="445" loading="lazy"></p>
<p>The same tooling is finally becoming available for JavaScript as well.</p>
<p><a target="_blank" href="http://sketch.systems/">Sketch Systems</a> provides a way of designing systems in markdown that can then be used to prototype in JavaScript. While Sketch Systems does not yet support <strong>actions</strong> or <strong>guards</strong>, I’ve found it very useful for prototyping and testing state charts.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/YUfyjSO1Fkv-eO2LH6Nf15i--zzzPnY9adkF" alt="Image" width="800" height="450" loading="lazy">
_[https://bit.ly/2lZhqOB](https://bit.ly/2lZhqOB" rel="noopener" target="<em>blank" title=")</em></p>
<p>Sketch Systems allows you to export your charts to <a target="_blank" href="https://github.com/davidkpiano/xstate">XState</a>, a statechart-based JavaScript library with its visualization and clickable state prototyping tool.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/CorF8tAeQ5g4qd3c4F1TkTflhcuUspsI6mi3" alt="Image" width="800" height="711" loading="lazy">
_[https://bit.ly/2uJydt9](https://bit.ly/2uJydt9" rel="noopener" target="<em>blank" title=")</em></p>
<p>Imagine more advanced tooling within your editor. Imagine your workflow as you toggle between visually designing and manually coding your application logic. It’s worth the work we’ll have to put in as a community to advance the tooling, libraries, and editor plugin’s we want to better support using statecharts.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Complexity snuck up on us in the JavaScript community. I don’t think we were ready for it. I’ll admit it took me a long time to get good at <strong>planning</strong> applications. I’d sketch out a component tree and some state shape. Watch prototypes iterate into production. But how could I be any good at planning applications without a formalized visual language to design state diagrams?</p>
<p>For a long time, I’ll confess that I approached state management more like a mystifying art. I was unaware that there was much to be learned from other areas of computer science with a long history of building and managing complex systems. I grew to understand that there’s value in looking to the past, as well as looking sideways at the fields of engineering around us.</p>
<p>We can learn from engineers who have pioneered and developed decades old solutions for creating complex — yet predictable — systems. We can build upon tools &amp; libraries as an ecosystem to support the visual design of application logic. And we will do it because JavaScript needs all of this.</p>
<p>The future of designing applications in JavaScript is looking brighter than ever. This article has all been very high level and likely left more questions than answers. In <a target="_blank" href="https://medium.freecodecamp.org/patterns-for-using-react-with-statechart-based-state-machines-33e6ab754605"><strong>part 2</strong></a>, I’d like to look more in-depth at patterns for using statecharts with components.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
