Zustand for State Management PART 1
A small, fast, and scalable bearbones state management solution
What is Zustand?
Zustand is a small, fast, and scalable state management solution for React18. It provides a simple and intuitive API based on hooks.
-
Bearbones State Management: Zustand is not boilerplatey or opinionated, but it has enough convention to be explicit and flux-like.
-
Store Creation: Your store is a hook! You can put anything in it: primitives, objects, functions. The set function merges state
-
Component Binding: You can use the hook anywhere, without the need of providers. Select your state and the consuming component will re-render when that state changes
Dive into Code (Example)
Importing Zustand:
import create from "zustand";
Here, we’re importing the create function from the zustand library.
Defining a Mock User Fetch Function:
const getUser = () => {
return new Promise((resolve) => {
setTimeout(() => {
const user = {
name: "Professor Plum",
email: "prof@plum.ac",
};
resolve(user);
}, 1000);
});
};
This function simulates an asynchronous operation, such as fetching user data from an API. It returns a promise that resolves with a user object after 1 second.
Creating User Store:
const useUserStore = create((set) => ({
isAuthenticated: false,
name: null,
email: null,
login: async () => {
const user = await getUser();
set({
isAuthenticated: true,
...user,
});
},
logout: () => {
set({
isAuthenticated: false,
name: null,
email: null,
});
}
}));
Here, we’re creating a user store using Zustand’s create function. The store has three properties: isAuthenticated, name, and email. It also has two methods: login and logout. The login method fetches the user data and updates the store, while the logout method resets the store to its initial state.
Creating Booking Store:
const useBookingStore = create((set) => ({
checkin: null,
checkout: null,
guests: 1,
addCheckin: (checkin) => {
set({ checkin });
},
addCheckout: (checkout) => {
set({ checkout });
}
}));
Similarly, we’re creating a booking store. This store manages the booking details, including the check-in date, check-out date, and the number of guests. It has two methods: addCheckin and addCheckout, which update the check-in and check-out dates, respectively.
Defining a Selector:
const guestsSelector = (state) => state.guests;
Selectors are functions that derive data from the state. Here, we’re defining a selector that returns the number of guests from the booking store.
Please go to PART 2 of this article form here..