Akita + React Hooks = a Recipe for Sensational State Management
I’ve been working with Akita pretty much since its inception, and while I’ve created many, many Akita stores in Angular, and wrote about it extensively, and even played around with an Akita/Svelte combo, I had yet to use it myself in a React App. I’ve decided to check that box, and whip up a classic todo app in React, using Akita for state management. Let’s get cooking 👩🍳👨🍳
This article assumes some familiarity with Akita State Management. To learn more about Akita and all its capabilities, check out one of the articles I’ve listed above or its great documentation.
Getting Started — What Do We Want to Save, and Where Do We Want to Save It?
We start by creating the model for the entity we want to save, in this case a ToDo
item:
This includes the model itself, as well as a function to generate new ToDo
items. Note that the guid()
method is our first little morsel from Akita 😋
We also add a VISIBILITY_FILTER
filters enum, which we’ll use later to filter the display of the items.
Next up is adding an Akita EntityStore
:
The store is used to hold our ToDo items (the state), as well as the currently selected VISIBILITY_FILTER
(aka the UI state). To read more about managing UI state with Akita check out this article. As you can see, very little code is needed at this stage — this is part of the charm of Akita, it saves a ton of boilerplate 💪
Every Akita entity store comes with a set pair of EntityQuery (for reading data from the store) and EntityService (for modifying the store). Let’s add the query first:
Once again, Akita’s EntityQuery
provides us with any basic selection functions we need (check the docs for more on that). All we need to add is a function that returns the currently selected VISIBILITY_FILTER
, and one that returns the ToDo
items, filtered by it. Let’s move on the service:
The service is also pretty lean — the basic CRUD operations are already supplied by the EntityStore
, all we need to do is call them.
The Secret Sauce: useObservable
Starting from v.16.8.0, React provides us with a bunch of hooks that let us interact with the lifecycle directly. You can read more about React Hooks here.
I’ll import useObservable, which uses those hooks (specifically, useRef, useState, and useEffect) and a given Observable, to update a React state with its emitted values. You can read more about useObservable here.
Using that, with the query’s selectVisibleTodos$
method as input, gives us the last piece of the puzzle:
And voilà! That’s all the ingredients we need for an efficient, DRY todo app!
You can also see the full app in action here:
Follow me on Medium to read more about React, Akita, and JS!