zamknij
Back to homepage

We’re here for you

At GMI, we believe our clients are more than just partners. We invest time to understand your business, users, and needs, shaping success together

Ilona Budzbon Sales & Marketing

How can I help You?

Contact Form

GMI Softweare dedicated to handling the provided information to engage with you regarding your project. Additional data is utilized for analytical reasons. Occasionally, we may wish to inform you about our other offerings and content that might be relevant to you. If you agree to be reached out to for these reasons, kindly mark the checkbox below. You can opt out of our communications anytime. To understand our opt-out process and our commitment to privacy, please refer to our Privacy Policy.
This field is for validation purposes and should be left unchanged.

Finite State Machine in React: A Comprehensive Guide

The realm of frontend development is a dynamic landscape, continually evolving and presenting new challenges. One of the methodologies that have proven to be incredibly useful in this context is the Finite State Machine (FSM). Though not traditionally associated with frontend development, FSMs have been instrumental in dealing with complex software projects, particularly in enhancing security.

ania
Ania Nowacka
Content Specialist
27 February 2024 6 MIN OF READING

The realm of frontend development is a dynamic landscape, continually evolving and presenting new challenges. One of the methodologies that have proven to be incredibly useful in this context is the Finite State Machine (FSM). Though not traditionally associated with frontend development, FSMs have been instrumental in dealing with complex software projects, particularly in enhancing security.

What is a Finite State Machine?

A Finite State Machine is a mathematical model of computation, or an abstract machine, that outlines the behavior of a system. It shares similarities with other models like the Turing Machine but differs in terms of computational power. FSMs are inherently limited by the finite number of states they possess, which is why they are “finite.”

The fundamental rule of a state machine is that it can exist in only one state at any given time. The transitions between states occur based on certain actions triggered by a proper combination or predetermined sequence of events.

These FSMs are ubiquitous in our daily lives. They are present in everyday objects and systems around us, such as vending machines, elevators, or traffic lights.

Real-Life Examples of Finite State Machines

To better understand the concept of FSMs, consider the example of traffic lights:

  • States:
    1. Stop – Red light
    2. Get ready to drive – Red and Yellow light
    3. Drive – Green light
    4. Get ready to stop – Yellow light
  • Transitions:
    1. Stop → Ready to drive
    2. Ready to drive → Drive
    3. Drive → Get ready to stop
    4. Get ready to stop → Stop

This example clearly demonstrates the finite number of states and transitions. Furthermore, it highlights the fact that traffic lights can only exist in a single state at any given moment, illustrating the concept of a finite state machine.

FSM in Software Development

The application of FSMs extends far beyond traffic lights and vending machines. They play a significant role in software development and computer science, particularly in game development.

Consider a 2D indie game where the main character is a cat. The game responds to keyboard events, triggering different states and animations of the cat.

  • States:
    1. Run
    2. Slide
    3. Jump
    4. Stay

From a code perspective, it reacts to keyboard events:

  • Arrow up – Triggers jump event that sets “jumps” state
  • Arrow right – Triggers run event that sets “runs” state
  • Arrow down – Triggers slide event that sets “slides” state
  • Arrow left – Triggers stay event that sets “stays” state

The use of FSMs in frontend development might initially appear complex and time-consuming. However, similar to using TypeScript in a software project, it might slow you down slightly and introduce a layer of complexity, but the overall benefits are worth the effort.

Implementing Finite State Machines in React

To illustrate the implementation of FSMs in a React app, let’s consider a simple signup form divided into three parts. Each part is rendered on the screen based on a given state at a particular time.Firstly, define all the parts, their components, and their initial state. After that, define the state and the component itself.

Despite its simplicity, this approach has potential risks, especially when you’re working as part of a development team. This creates a bad state because step three doesn’t exist in our form. Other examples of wrong states include skipping a step when all steps are required to follow a sequence. The occurrence of these wrong states in production could lead to unsightly bugs and inconsistencies. What if you could define all possible states and transitions in one place? A contract that lets you see the entire logic, ensuring that nothing more or less will happen. That “something” is the Finite State Machine.

Refactoring the Form to Finite State Machines

Let’s focus on refactoring the onNext and onPrevious functions. We want to create a machine model that has:

  • States:
    1. Company
    2. Director
    3. Contact
  • Events:
    1. Next → Transition to the next state in order
    2. Previous → Transition to the previous state in order

The implementation of the machine model would look something like:

const formMachine = createMachine({
  id: "form",
  initial: "company",
  states: {
    company: {
      on: {
        NEXT: "director",
      },
    },
    director: {
      on: {
        NEXT: "contact",
        PREVIOUS: "company",
      },
    },
    contact: {
      on: {
        PREVIOUS: "director",
      },
    },
  },
});

This code snippet illustrates the creation of a machine that takes an object composed of a unique identifier, the name of the initial state, and states that contain all of the states. Each state reacts to two events: “previous” and “next,” which set the corresponding states.

With the help of tools like the xstate visualizer, you can visualize all the possible states and events of your finite state machine. While it might seem a lot for a small feature, the benefits of FSMs manifest as you add more features.

Enhancing Security with Finite State Machines

Remember the problem we had before with the classic approach? Steps and Views were decoupled. We could implement this in a better way in our finite state machine by changing the context and the map function.

By adding some type-safety to our machine and moving types and helpers to different files, we create a code that is more robust and secure.

Understanding the Value of State Machines in React

While it may look complicated initially, remember that you could be working on a critical project for a major company where the smallest bug can cost significant amounts of money. The finite state machine approach offers:

  1. Type safety: You cannot use a state not defined in your type. Otherwise, it will result in a compilation error.
  2. Freedom from wrong states and transitions: There’s no way someone would go from part 1 to part 3 without changing the machine definition.
  3. Logic described in one place: The entire logic of the state transitions is described in one place, making it self-explanatory.

Conclusion

Through this guide, we delved into the concept of Finite State Machines and their application in the world of React and frontend development. Despite not being a traditional frontend development methodology, FSMs can deliver immense value, especially in complex software projects that demand high levels of security and efficient state management.As you explore the world of programming further, keep in mind that tools and methodologies like FSMs can be your best ally in managing complexity and building robust, secure, and efficient applications. With the Finite State Machine approach, you can confidently navigate the dynamic landscape of frontend development, ready to tackle any challenge that comes your way.