Live data from Hacker News

useStateMachine: A ½ kb state machine hook for React

github.com

51–60 of 103 posts

Re: useStateMachine: A ½ kb state machine hook for React

#51

It’s interesting to me how certain design patterns get rediscovered over the years. A few years back FSM’s were a dirty word for crusty Java devs. I myself avoided them for that reason. Then one day I had a perfect use case for one and took the plunge and was amazed by how useful a pattern it is. I’m embarrassed at how long it took me to get hip to it. I’m writing a feature at my job right now that makes heavy use of…

Finite state machines will never not be useful for the same reason regular expressions will always be useful. They're a supremely simple model of computation, making them easy to reason about.

The problem with state machines in Java is not the state machine's fault, it's Java's fault.

Re: useStateMachine: A ½ kb state machine hook for React

#52
post #30

Earlier quoted context omitted.

No, I know what state machines are. What I’m contesting is the argument that this is an intuitive way to structure code. It could be intuitive to reason about, or even white board the states your application can be in, but this doesn’t look like concise and elegant code. From your examples: https://xstate-catalogue.com/machines/confirmation-dialog I’ve written a million confirm-dialogs in my lifetime, and that exampl…

I think your problem is that many things don’t have to be a state machine. And you’re right. It’s simply not a good idea to create a confirmation dialog like that. However, some things just _are_ state machines. You don’t usually see them in the GUI (except for example wizards), but many parsers can trivially be implemented with state machines.

I actually believe there would be fewer UI bugs if more UI was modeled as a state machine. After all, all diagrams and design is often based on "when X is shown and Y is pressed, we go to Z". But in code that's expressed in a way that makes it possible to have a mismatch between multiple half baked states.

Re: useStateMachine: A ½ kb state machine hook for React

#55
post #10

Earlier quoted context omitted.

Interesting. I have the opposite experience, the more I use them the more clunky they feel. * If there’s only useState, then everything is mostly fine. All is good. * To avoid unnecessary re-rendering you’ll have to move callbacks into useCallback. These callbacks then also need to specify all of their dependencies. So many lines of code that are merely noise. * They encourage having state locally in the component wh…

>You forget one value in your dependency list and the weirdest things happen. This is what I hate in angular1 , there are at least 3-4 ways you can mess up a simple data-binding and there is no error or warning to inform you that something is not right so you waste a lot of time to figure it out. I used react a few years back but it seems that this days it got hyper complex.

As far as I can tell you can just not use hooks, if you (and the rest of your contributors) agree.

Re: useStateMachine: A ½ kb state machine hook for React

#56

Can anyone provide an example of a situation where something like this is a pragmatic solution? Please also provide the drop dead simple version too and explain why this would be more elegant and intuitive in comparison. Types of examples I am not interested in seeing: - a DropDown list using a state machine (or something similarly simple that’s been solved a million times in a simple way). Edit: I just think stuff l…

Auth logic or similar. Somewhere area in app that may be genuinely complicated and can't go wrong, where you need granular control over a set of states which often have sub states, and where there are things like remote requests to different services occurring.

And you can just write this stuff as basically lots of nested if statements but...

As an actual example, I have a state machine in an app I work on:

1. check if there's a session (if so goto 4). 2. If not go to email input. 3. On submit go to password input. 4. authorized. However: 2 and 3 and some of the time 1 have network requests, so handle those. Password can be entered wrong three times (error message changes accordingly, oh also no. retries are modifiable at admin level), which bumps user back to 2 (error message changes accordingly). User may have turned on PIN security, if so that will be an extra step before allowed into app. They may also have it turned on, but not one set, which is a slightly different flow. And they can turn it off/on from within app. Oh and biometric, same deal as PIN. Also can drop back to username/pword instead of OTP in some circumstances.

That's most stuff I think off top of head. That's a hierarchical state machine written using XState. It's easy to test (UI is seperate from the machine, and I can just plug in API functions for the remote calls). It's relatively easy to read (xstate API produces stuff that reads like a diagram, it's easy to explain what's going on). It's easy to add/remove states

Re: useStateMachine: A ½ kb state machine hook for React

#57

Can anyone provide an example of a situation where something like this is a pragmatic solution? Please also provide the drop dead simple version too and explain why this would be more elegant and intuitive in comparison. Types of examples I am not interested in seeing: - a DropDown list using a state machine (or something similarly simple that’s been solved a million times in a simple way). Edit: I just think stuff l…

I think the value of a state machine is treating all of the associated states in a single conceptual model or level. You can definitely do everything directly in a bunch of if statements and tracking state in separate variables, but that opens yourself to more potential bugs, higher maintenance cost, less big picture understanding, and even larger performance costs (separate codes means the compiler can't optimize as well; means hardware caches aren't as effective; there's more overhead to run separated functions; etc, etc).

Here's hopefully a more apt example: imagine wanting to have a multiple document interface (MDI) that shows a bunch of 'window' like views. Some examples of the idea are react-grid-layout, golden-layout, react-mosaic. Each window can be minimized, maximized, moved, flashed, and closed ... all with flashy animations. You could create a whole bunch of components that allow you to capture all the different states and toggle them in different components, and effectively have the MDI business logic sprinkled all through out YOUR code, not just the 'library' code. Alternatively, you could use a state machine that captures all the states in a single spot and manages that all efficiently and safely, you just call an api to trigger state changes throughout your code.

As some other comments have mentioned, this is a fundamental part of computer science. You can get by without knowing it cause you can write a bunch of ifs and state logic all over the place. If you only know how to use a hammer, ya you could still hammer a screw in. Understanding how different data structures of different patterns fit together provides you new tools to do things in different ways when appropriate. Learn how to manage complexity, not fear it, cause there's nothing dangerous about state machines. In fact, I'd argue that anyone that thinks state machines make things more complex just isn't looking at a large enough scale because state machines should make things less complex by wrapping all the complexity inside them (when used appropriately).

Re: useStateMachine: A ½ kb state machine hook for React

#58
post #10

Earlier quoted context omitted.

Interesting. I have the opposite experience, the more I use them the more clunky they feel. * If there’s only useState, then everything is mostly fine. All is good. * To avoid unnecessary re-rendering you’ll have to move callbacks into useCallback. These callbacks then also need to specify all of their dependencies. So many lines of code that are merely noise. * They encourage having state locally in the component wh…

> You forget one value in your dependency list and the weirdest things happen. Don't you get eslint warnings right in your editor? If you're using VS Code there's an extension for that...

Not only this but I need the freedom to control the dependency list for an effect. Sometimes it isn't as simple as "every variable being referenced inside the effect."

Re: useStateMachine: A ½ kb state machine hook for React

#59
post #28

Earlier quoted context omitted.

Can you even describe the use of a state machine for UIs as "over-abstraction"? To me it seems more like an "under-abstraction", since one usually compiles a more abstract definition into a state machine - often a regular expression or some kind of grammar.

Was just discussing this with a friend this morning. It might be better to describe it in terms of trade-offs versus the overuse of the ‘over-abstraction’ allegation. So, in a lot of cases in the UI, we are turning what is very recognizable and traditionally understood code into a new form to fit the state-machine world view in a more 1:1 way. Again, it’s a trade off. What did we gain from this transformation? I don’…

Did you start programming with OOP or Functional programming? Did learning how to programming in the other form seem difficult to understand why you would do things that way, or seem obtuse vs just using the ways you already know?

I think using state machines is just a very different way of looking at code, and it does take some mind bending to think that way; but once you do, it's much easier to blend the code together the same way you'll see imperative and functional code blended together these days and not think twice about it.

Re: useStateMachine: A ½ kb state machine hook for React

#60
post #33
post #10

Earlier quoted context omitted.

Interesting. I have the opposite experience, the more I use them the more clunky they feel. * If there’s only useState, then everything is mostly fine. All is good. * To avoid unnecessary re-rendering you’ll have to move callbacks into useCallback. These callbacks then also need to specify all of their dependencies. So many lines of code that are merely noise. * They encourage having state locally in the component wh…

Seconded. Plus, you start writing wrapper functions for standard Javascript APIs (e. G. window.setInterval) to force them into Reacts data model.

Why would you do that? What’s wrong with this?

    useEffect(() => {
      const interval = setInterval(myFunc, 1000)
      return () => clearInterval(myInterval)
    },[])
I think one of the keys to React is not to fear the boilerplate.

If you find yourself typing the same code too often, there’s probably a higher level abstraction that you should find, way above the level of setInterval.

I find coders often try to DRY up low level code to the detriment of actually dealing with their _application_ architecture.

In general, you should use the tools as provided, boilerplate and all, and then focus your real brain energies on the specific domain problems that only your application needs.

Creating thin wrappers on external tools to squeeze the last tiny bits of DRYness is not only usually a waste of time, but it makes your code unreadable. People know how setInterval and useEffect work. If I see useInterval I have to go read your code to know what’s happening. Especially if you made it configurable. And people _will_ tend to add configuration to these wrappers over time as needs change.

Post reply on HN