Zustand is a simple and efficient state management library that provides an easy way to manage and update state in React applications using hooks. When persisting state in the application—for example, saving certain state even after the browser is closed—Zustand's Persist middleware is particularly useful. Here, I'll demonstrate how to use Zustand's Persist middleware to store state in localStorage with a simple example.
Assume we have a React application where the user's theme preferences (such as dark mode and light mode) need to be saved so that the previously set theme is retained when the user reopens the application. Here are the steps to achieve this:
-
Install Zustand and import Persist Before starting, you need to install Zustand. You can install it using npm or yarn:
bashnpm install zustand npm install zustand/middleware -
Create a store Next, we need to create a store to save the user's theme preferences. We'll use the
persistfunction to persist this state:javascriptimport create from 'zustand'; import { persist } from 'zustand/middleware'; const useStore = create(persist((set) => ({ theme: 'light', // Default to light mode toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light' })) }), { name: 'user-settings', // This is the key name for storing data in localStorage getStorage: () => localStorage, // Specifies localStorage as the storage medium })); -
Use the store in a React component Now that the store is set up and can persist the user's theme preferences, using it in a React component is straightforward:
javascriptimport React from 'react'; import { useStore } from './store'; function App() { const { theme, toggleTheme } = useStore(); return ( <div className={theme}> <h1>Welcome to the Theme Toggler App</h1> <button onClick={toggleTheme}> Toggle Theme </button> </div> ); } export default App;
By following these steps, we've created a simple application where the user's theme preferences are saved in localStorage. Even after closing and reopening the browser, the previously set theme will be retained.
This is a basic example of using Zustand's Persist middleware for state management in a React application.