So whilst wiring up my the frontend CRUD buttons to the backend routes in this project that I am currently working on, I realized I needed to implement a simple flux architecture to manage global state.
However, I haven’t used Redux in a while, and based on my experience, setting up reducers, and their various dispatch statements, was rather tedious, especially for a small project, so I decided to google what alternatives to Redux was there.
And then I came across Zustand. From the online reviews Zustand seemed to be pretty popular; and when I headed over to its docs, integration seemed fairly simple.
I poured over the docs on my way to the BBQ with my partner’s family, and implemented some of it on the train.
And by the next morning (i.e. now), I have already implemented ‘reducers’ and ‘dispatch’ functionality for the getAll and create new actions.
Can’t believe how intuitive and quick to set up it is.
Let me briefly take you through the simple implementation I did.
Background on my app
The context is not so important, but all you need to know is that I need to get a global state topics from database, which is an array of topic items, and I am trying to create a new topic by clicking on a button. This means, after hitting the backend ’new topic’ route, I’ll need to persist the new topic data into the frontend topic state. Classic pattern resolvable by redux.
First, I defined the topicStore in /store.ts:
| |
As you can see, the store consists of a state, topics, set to an empty array, and a setTopics function that takes a data argument and set it to the topics state. I’ll get to the addTopic function later.
Next, I go to my app root, App() component, and use the states in the store:
| |
Then I set the topic state in the store within an effects hook:
| |
This initializes the global topics state with the data in the db.
Note, using Zustand, providers are not needed!
To consume the state, simply head to whichever component you want to use it in, and do the following:
| |
In my case, I needed to add the topic state within the handleSubmit() button - quite a typical pattern when you POST data to the DB.
And viola - the frontend is rendered beautifully.
3 steps in total?
- Store definition
- Initialize data
- Add it to wherever store needs to be updated.
A way more intuitive and simple primitive, especially for light weight use cases.
:)