Tillitsdone
down Scroll to discover

Advanced Zustand: Middleware & Persisted State

Dive deep into Zustand's powerful features: middleware implementation and state persistence.

Learn how to enhance your React applications with advanced state management techniques.
thumbnail

Advanced Zustand: Middleware and Persisted State

An abstract geometric pattern representing data flow and state management featuring interconnected nodes and flowing lines in bright cyan and electric green colors against a pure black background captured from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Zustand has become a go-to state management solution for many React developers, thanks to its simplicity and powerful features. Today, we’ll dive deep into two advanced concepts that can take your Zustand implementation to the next level: middleware and persisted state.

Understanding Zustand Middleware

Think of middleware as your store’s personal bodyguard - it intercepts and processes actions before they reach your state. This opens up a world of possibilities for logging, debugging, and adding custom behaviors to your store.

Let’s start with a practical example:

import create from 'zustand'
import { devtools, persist } from 'zustand/middleware'
const useStore = create(
devtools(
(set) => ({
bears: 0,
increaseBears: () => set((state) => ({ bears: state.bears + 1 })),
})
)
)

Abstract flowing waves of energy in holographic silver and white rippling through a black void representing data transformation and flow shot from a diagonal perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Creating Custom Middleware

Sometimes, you need middleware tailored to your specific needs. Here’s how you can create your own:

const logger = (config) => (set, get, api) =>
config(
(...args) => {
console.log(' applying', args)
set(...args)
console.log(' new state', get())
},
get,
api
)

Persisted State: Making Your Store Immortal

One of the most powerful features of Zustand is its ability to persist state across page reloads. This is particularly useful for maintaining user preferences, shopping carts, or any data that should survive a browser refresh.

Crystalline formations growing and interconnecting in bright electric blue and white against a black background symbolizing data persistence and growth captured from a low angle perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Here’s how to implement persisted state:

const useStore = create(
persist(
(set, get) => ({
fishes: 0,
addFish: () => set({ fishes: get().fishes + 1 }),
}),
{
name: 'food-storage', // unique name
getStorage: () => localStorage, // (optional) by default, 'localStorage' is used
}
)
)

Advanced Persistence Patterns

You can get even more granular with persistence by:

  • Selecting specific parts of your state to persist
  • Implementing custom storage solutions
  • Handling version migrations
  • Managing rehydration

Remember, while persistence is powerful, use it wisely. Not everything needs to be persisted, and over-persistence can lead to stale data issues.

Organic texture pattern showing interconnected nodes in bright neon green against deep black background representing a living breathing system of data storage shot from a bird's eye view perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

When you combine middleware with persisted state, you create a robust state management system that can handle complex scenarios while maintaining excellent developer experience. The key is finding the right balance for your specific use case.

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.