Tic-Tac-Toe.js: redux pattern in plain javascript

There’s this thing going on in the Front-End Development community where everybody wants to re-write their applications to use React. Sorry to disappoint, but that’s not the case here. At work I mostly use vanilla javascript, therefore it is more beneficial for me to learn the concepts rather than the frameworks themselves.

With the amazing help and guidance of @ricardobeat , I’ve managed to build this Tic-Tac-Toe game using Redux principles with vanilla javascript. No React, no jQuery, no micro-library, it doesn’t rely on anything else. It’s just plain JS. Isn’t it great? In this post I’d like to share the approach that made this possible. Let’s get into the details.

The important thing here is that we stick with the correct data flow. Which brings me to next topic.

Strict unidirectional data flow

Maybe you haven’t noticed, but on previous examples the data flow is always unidirectional. Game.js — the view — dispatches actions, store.js receives and process them with reducers which later triggers ‘store:update’ so finally we can render the UI updates.

Going multiplayer

Ok, we have everything working on the client-side. But how is Tic-Tac-Toe connecting two players?

Implementing the back-end in node.js + socket.io was really simple and that’s one of the coolest things about Redux. Because everything is based on actions, which are by definition simple objects, the only requirement on the Back-end would be: receiving the action and dispatching it to other players connected in the same room/game id.

The front-end side:

Everything starts on the client-side. When the page loads I generate a random ID, which will then be handed to the server.

The back-end side:

Design and usability

The game was designed to work in different resolutions. On desktop version the favicon updates according to the player turn, check that out when you start playing. On mobile it’s possible to save the app on home screen, there’s a special logo icon for that.

“Ok, so how can I play the game?”

Your friend should paste the id in the same field and click on the refresh icon located right after it.

Is there an easier way to connect in the same room?

If you are using iOS you can share your browser url using AirDrop . That way your friend would load the same room/game id by default.

Learnings

Redux has proven to be very easy to debug and fix issues. You have one single entity that represents the state of your application and the only way you can change it is by dispatching actions. I was also surprised how fast it was to integrate with a node.js server and make it broadcast certain actions to the front-end.