Pengurusan negeri ialah aspek penting dalam pembangunan web moden, terutamanya dalam aplikasi yang kompleks. Ia melibatkan pengendalian data yang boleh berubah dari semasa ke semasa dan memastikan data ini diwakili secara konsisten merentas keseluruhan aplikasi. Pengurusan keadaan yang berkesan membawa kepada aplikasi yang lebih boleh diramal dan boleh diselenggara.
Zustand ialah penyelesaian pengurusan keadaan yang kecil, pantas dan berskala untuk aplikasi React. Dicipta oleh Jared Palmer dan Daishi Kato, Zustand menawarkan API yang ringkas dan intuitif yang menjadikan pengurusan negeri kurang menyusahkan berbanding penyelesaian lain.
Sebelum menyelam lebih dalam ke dalam Zustand, mari kita fahami pelbagai jenis keadaan dalam aplikasi web:
Zustand cemerlang dalam mengurus kedua-dua negeri tempatan dan global, dan boleh disepadukan dengan penyelesaian untuk pengurusan negeri terpencil.
Untuk mula menggunakan Zustand, pasang dahulu melalui npm, benang atau pnpm:
npm install zustand # or yarn add zustand # or pnpm add zustand
Zustand hadir dengan beberapa ciri yang menyerlahkannya:
Mari kita lihat pelaksanaan asas Zustand:
import { create } from 'zustand' const useStore = create((set) => ({ bears: 0, increasePopulation: () => set((state) => ({ bears: state.bears + 1 })), removeAllBears: () => set({ bears: 0 }), })) function BearCounter() { const bears = useStore((state) => state.bears) return <h1>{bears} around here...</h1> } function Controls() { const increasePopulation = useStore((state) => state.increasePopulation) return <button onClick={increasePopulation}>one up</button> }
Dalam contoh ini, kami mencipta kedai dengan keadaan beruang dan dua tindakan untuk mengubah suainya. Komponen BearCounter dan Controls kemudiannya boleh mengakses dan mengubah suai keadaan menggunakan cangkuk useStore.
Mari bandingkan Zustand dengan penyelesaian pengurusan negeri popular yang lain:
Kebaikan Zustand:
Keburukan:
Kebaikan Zustand:
Keburukan:
Kebaikan Zustand:
Keburukan:
Reka bentuk sistem Zustand adalah berdasarkan beberapa prinsip utama:
This design allows Zustand to be both simple and powerful, providing excellent performance even in large applications.
Zustand makes it easy to persist state, which is crucial for many applications. Here's an example using the persist middleware:
import { create } from 'zustand' import { persist } from 'zustand/middleware' const useStore = create(persist( (set, get) => ({ fishes: 0, addAFish: () => set({ fishes: get().fishes + 1 }), }), { name: 'food-storage', // unique name getStorage: () => localStorage, // (optional) by default, 'localStorage' is used } ))
This will automatically save the state to localStorage and rehydrate it when the app reloads.
One of Zustand's strengths is that it can be used outside of React components. This is particularly useful for integrating with other parts of your application or for testing:
const { getState, setState } = useStore // Getting state console.log(getState().bears) // Setting state setState({ bears: 10 }) // Using actions getState().increasePopulation()
Let's look at some real-world examples of using Zustand:
import { create } from 'zustand' const useAuthStore = create((set) => ({ user: null, isAuthenticated: false, login: (userData) => set({ user: userData, isAuthenticated: true }), logout: () => set({ user: null, isAuthenticated: false }), })) // Usage in a component function LoginButton() { const { isAuthenticated, login, logout } = useAuthStore() const handleAuth = () => { if (isAuthenticated) { logout() } else { // Simulate login login({ id: 1, name: 'John Doe' }) } } return ( <button onClick={handleAuth}> {isAuthenticated ? 'Logout' : 'Login'} </button> ) }
import { create } from 'zustand' const useCartStore = create((set) => ({ items: [], addItem: (item) => set((state) => ({ items: [...state.items, item] })), removeItem: (itemId) => set((state) => ({ items: state.items.filter((item) => item.id !== itemId), })), clearCart: () => set({ items: [] }), total: 0, updateTotal: () => set((state) => ({ total: state.items.reduce((sum, item) => sum + item.price, 0), })), })) // Usage in components function CartSummary() { const { items, total, removeItem } = useCartStore() return ( <div> {items.map((item) => ( <div key={item.id}> {item.name} - ${item.price} <button onClick={() => removeItem(item.id)}>Remove</button> </div> ))} <div>Total: ${total}</div> </div> ) }
import { create } from 'zustand' import { persist } from 'zustand/middleware' const useThemeStore = create(persist( (set) => ({ theme: 'light', toggleTheme: () => set((state) => ({ theme: state.theme === 'light' ? 'dark' : 'light', })), }), { name: 'theme-storage', } )) // Usage in a component function ThemeToggle() { const { theme, toggleTheme } = useThemeStore() return ( <button onClick={toggleTheme}> Switch to {theme === 'light' ? 'dark' : 'light'} mode </button> ) }
Zustand offers a refreshing approach to state management in React applications. Its simplicity, flexibility, and performance make it an excellent choice for both small and large projects. By reducing boilerplate and providing a straightforward API, Zustand allows developers to focus on building features rather than managing complex state logic.
While it may not have the extensive ecosystem of some older state management solutions, Zustand's design principles and ease of use make it a compelling option for modern React development. Its ability to work outside of React components and easy integration with persistence solutions further extend its utility.
For many React applications, Zustand strikes an excellent balance between simplicity and power, making it worth considering for your next project.
Zustand also handles asynchronous functions/code really well and without the need for any Middleware setup.
Let's talk a bit about that:
One of Zustand's strengths is its simplicity in handling asynchronous operations without the need for additional middleware or complex setups. This makes it particularly easy to work with API calls, data fetching, and other asynchronous tasks.
Zustand's approach to asynchronous code is straightforward:
Here's an example of how to implement asynchronous code in Zustand:
import { create } from 'zustand' const useUserStore = create((set) => ({ user: null, isLoading: false, error: null, fetchUser: async (userId) => { set({ isLoading: true, error: null }); try { const response = await fetch(`https://api.example.com/users/${userId}`); if (!response.ok) throw new Error('Failed to fetch user'); const userData = await response.json(); set({ user: userData, isLoading: false }); } catch (error) { set({ error: error.message, isLoading: false }); } }, })); // Usage in a component function UserProfile({ userId }) { const { user, isLoading, error, fetchUser } = useUserStore(); React.useEffect(() => { fetchUser(userId); }, [userId]); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error: {error}</div>; if (!user) return null; return ( <div> <h1>{user.name}</h1> <p>Email: {user.email}</p> </div> ); }
In this example:
Unlike Redux, which often requires middleware like Redux Thunk or Redux Saga for handling async operations, Zustand's approach is much more straightforward. This simplicity can lead to less boilerplate and a gentler learning curve, especially for developers new to state management.
MobX and Recoil also offer ways to handle async operations, but Zustand's approach might be considered more intuitive due to its direct use of async/await syntax without additional abstractions.
Pengendalian kod tak segerak Zustand menunjukkan falsafah kesederhanaan dan fleksibilitinya. Dengan membenarkan pembangun menulis fungsi async terus di kedai tanpa sintaks atau perisian tengah khas, Zustand memudahkan untuk mengurus operasi keadaan kompleks sambil memastikan pangkalan kod bersih dan boleh dibaca.
Pendekatan kepada kod tak segerak ini, digabungkan dengan ciri Zustand yang lain seperti saiz berkas kecil dan persediaan mudah, menjadikannya pilihan terbaik untuk projek semua saiz, terutamanya yang melibatkan pengurusan keadaan tak segerak yang ketara.
Semoga "panduan agak" ini berguna dan bernas untuk mana-mana daripada anda yang berfikir tentang cara mengurus keadaan aplikasi global anda.
Terima kasih dan Selamat mengekod.
Sila lihat laman web saya di https://www.ricardogesteves.com
Ikuti saya @ricardogesteves
X(twitter)
Atas ialah kandungan terperinci Zustand, Bila, bagaimana dan mengapa. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!