DEV Community

Mikey Stengel
Mikey Stengel

Posted on • Edited on

7 3

State machine advent: The simplest state machine that will improve your code today (1/24)

As outlined in the introduction post, many bugs occur because we allow our applications to be in invalid states.

The concept of state machines is all about explicitly modeling your application states so they cannot be in an invalid state. Importing a new library like XState into your app can be intimidating, especially when already using another state management solution.
To get familiar with the concept of finite automata and to eliminate some low hanging bugs, you can create your first state machine with nothing but TypeScript and React.

import React, { useState } from 'react';

enum FETCH_TODO_STATES {
  'IDLE' = 'idle',
  'FETCHING' = 'fetching',
  'ERROR' = 'error',
  'DONE' = 'done'
}

const Todos = () => {
  const [fetchTodoStatus, setFetchTodoStatus] = useState<FETCH_TODO_STATES>(
    FETCH_TODO_STATES.IDLE,
  );

  // Use setFetchTodoStatus in your event handlers or useEffect hook ...
};
Enter fullscreen mode Exit fullscreen mode

Instead of defining boolean flags like hasError, isFetching, you define an enum (or object if you are using JavaScript) with a declarative description of the current state. In conjunction with the useState hook, your app can only be in one of the three states at any given moment. This simple change eliminates tons of invalid states while also reducing the complexity of your code. 🎉

An example of an invalid state would be {hasError: true, isFetching: true} which should never happen at any given moment. Yet, if you were to use booleans, it could happen and ultimately lead to bugs.

About this series

Throughout the first 24 days of December, I'll publish a small blog post each day teaching you about the ins and outs of state machines and statecharts.

The first couple of days will be spent on the fundamentals before we'll progress to more advanced concepts.

Top comments (1)

Collapse
 
fantasticsoul profile image
幻魂

try setup(powered by concent) in react:
js ver: codesandbox.io/s/concent-guide-xvcej
ts ver: codesandbox.io/s/concent-guide-ts-...
function component and class component share business logic code easily.

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay