상태 관리는 현대 웹 개발, 특히 복잡한 애플리케이션에서 중요한 측면입니다. 여기에는 시간이 지남에 따라 변경될 수 있는 데이터를 처리하고 이 데이터가 전체 애플리케이션에서 일관되게 표시되도록 보장하는 작업이 포함됩니다. 효과적인 상태 관리는 애플리케이션을 더욱 예측 가능하고 유지 관리 가능하게 만듭니다.
Zustand는 React 애플리케이션을 위한 작고 빠르며 확장 가능한 상태 관리 솔루션입니다. Jared Palmer와 Daishi Kato가 만든 Zustand는 다른 솔루션에 비해 상태 관리를 덜 번거롭게 만드는 간단하고 직관적인 API를 제공합니다.
Zustand에 대해 자세히 알아보기 전에 웹 애플리케이션의 다양한 상태 유형을 이해해 보겠습니다.
Zustand는 로컬 및 전역 상태 관리에 탁월하며 원격 상태 관리용 솔루션과 통합될 수 있습니다.
Zustand 사용을 시작하려면 먼저 npm, Yarn 또는 pnpm을 통해 설치하세요.
Zustand에는 눈에 띄는 여러 기능이 있습니다.
Zustand의 기본 구현을 살펴보겠습니다.
이 예에서는 Bears 상태와 이를 수정하는 두 가지 작업이 있는 저장소를 만듭니다. 그런 다음 BearCounter 및 Controls 구성 요소는 useStore 후크를 사용하여 상태에 액세스하고 수정할 수 있습니다.
Zustand를 다른 인기 있는 상태 관리 솔루션과 비교해 보겠습니다.
Zustand의 장점:
단점:
Zustand의 장점:
단점:
Zustand의 장점:
단점:
Zustand의 시스템 설계는 몇 가지 주요 원칙을 기반으로 합니다.
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 ( ) }
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 ({items.map((item) => () }{item.name} - ${item.price}))}Total: ${total}
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 ( ) }
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) returnLoading...; if (error) returnError: {error}; if (!user) return null; return (); }{user.name}
Email: {user.email}
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)
위 내용은 Zustand, 언제, 어떻게, 왜의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!