DEV Community

Anand
Anand

Posted on • Updated on

State Chart in Real-world

Implementing Complex Requirement in React

Due to complex business requirements, the moment a React developer adds multiple useEffect, useState & useQuery, he/she finds that such component's code is not fun to read & change.

I worked on similar business requirement for our Login component :-

  • On load of Login page, fetch product offerings, and wait till it finishes.
  • Take the user to the error page if it fails.
  • Verify that product_code query parameter present in URL belongs to one of the products in product list recently loaded, if not then redirect to product offering page.
  • If product_code query parameter is valid, then verify if accessToken present in sessionStorage/cookie is valid and not expired, if yes redirect user to retrieve application flow.
  • if accessToken is not valid, load the latest marketing campaign. Wait till it get loaded and then redirect user to OAuth based login flow (we show latest campaign on login page).

I implemented the above using plain useEffect, useQuery of apollo and useState, but code was complex. I spent a couple of hours making it possible to comprehend, but wasn't satisfied with the end result. Most of you surely have similar business requirements. I am curious to find how you solve such a requirement using React or any other way.

Statechart based development

For a simple example app, it may look over-engineering to use state-machine (though conf talks by David explains how even, simple requirement hide complexities/bugs in it).
We use xstate to implement a long funnel in our application.
I was aware about state/transitions/events/guards in xstate. We used it to build the skeleton of our funnel and flow in pages. But we were yet to utilize -

These two concepts are what make it really useful to tackle non-trivial real world problems using state-charts. This is how my machine looked for above requirement -

Alt Text

Then I realise that state-chart spec (or XState docs) is vast because it does cover all our use cases. We still have a long way to adopt xstate fully, but I am sure it'd be worth since it offers following lofty benefits :-

  1. Formalism of logic and Visualization
  2. Ease of unit testing (compare to unit testing the logic written in react UI components)
  3. Auto Generated E2E test code
  4. Ease of applying Analytics

I am already seeing the first two benefits in our codebase, As a team, we are trying to reach the level where we can gain the benefit of (3. & 4.).

Top comments (0)