DEV Community

Matías Hernández Arellano
Matías Hernández Arellano

Posted on

Quick post: Modeling a video player with xstate

This is quick post to showcase part of the work for a bigger article.

I've been diving into xstate and I'm really exciting for what can be done in simple way with xstate and state charts.

So, this are the demos of building a simple video player with xstate.

So, first. What we will build?.

A simple video player that can play, pause, stop and reset a video from a url as source.

To get an idea of how this looks, check this codesandbox with the pure React version of the player

This demo code is using useReducer to model and handle the states and the events.

Now, let's introduce xstate.
xState way of thinking is a bit different from React's useReducer hook, it force you to think in every possible state of your UI/component and in the transitions.
One thing you get from free with this approach, is that is really easy, even just happen, to model restrictions: Can this state trigger some event?

Check the machine configuration that we will use by visiting the awesome visualizator from stately.

https://stately.ai/viz/b57eba4b-e10e-4210-9cf0-1d8ef58cf3a1

Now, since this is a short post I will leave you with a set of codesandboxes with examples in different frameworks about the implementation of the same video player but using the state machine posted here.

React version

Svelte version

Vue version

What would you like to know about xstate and state charts/machines?

Discussion (0)