Zustand'ı projenize kurmak için:
npm install zustand
# veya
yarn add zustand
Bir Zustand store'u oluşturma ve kullanma ile ilgili temel bir örnek:
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} burada...</h1>
}
function Controls() {
const increasePopulation = useStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>bir tane artı</button>
}
Başlangıç durumu ve eylemleri ile bir store oluşturma:
import create from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
reset: () => set({ count: 0 }),
}))
Store'u bileşenlerinizde kullanın:
function Counter() {
const { count, increment, decrement, reset } = useStore()
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={reset}>Sıfırla</button>
</div>
)
}
Durumu kısmi veya tamamen güncelleyin:
const useStore = create((set) => ({
firstName: 'John',
lastName: 'Doe',
age: 30,
updateName: (firstName, lastName) => set({ firstName, lastName }),
incrementAge: () => set((state) => ({ age: state.age + 1 })),
}))
Asenkron işlemleri yönetin:
const useStore = create((set) => ({
users: [],
fetchUsers: async () => {
const response = await fetch('https://api.example.com/users')
const users = await response.json()
set({ users })
},
}))
Store'unuza ara katman yazılımı ekleyin:
import create from 'zustand'
const myMiddleware = (config) => (set, get, api) =>
config(
(...args) => {
console.log(' uygulama', args)
set(...args)
console.log(' yeni durum', get())
},
get,
api
)
const useStore = create(
myMiddleware((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
}))
)
Durumu localStorage'a kaydetmek için persist ara katman yazılımını kullanın:
import create from 'zustand'
import { persist } from 'zustand/middleware'
const useStore = create(
persist(
(set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
}),
{
name: 'food-storage', // benzersiz isim
getStorage: () => localStorage, // (isteğe bağlı) varsayılan olarak 'localStorage' kullanılır
}
)
)
Redux DevTools'u etkinleştirin:
import create from 'zustand'
import { devtools } from 'zustand/middleware'
const useStore = create(devtools((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
})))
Zustand'ı TypeScript ile kullanın:
import create from 'zustand'
interface BearState {
bears: number
increasePopulation: () => void
removeAllBears: () => void
}
const useStore = create<BearState>((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))
Verimli güncellemeler için seçiciler kullanın:
const useBearStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))
function BearCounter() {
const bears = useBearStore((state) => state.bears)
return <h1>{bears} burada...</h1>
}
Birden fazla store'u birleştirin:
const useBearStore = create((set) => ({
bears: 0,
addBear: () => set((state) => ({ bears: state.bears + 1 })),
}))
const useFishStore = create((set) => ({
fishes: 0,
addFish: () => set((state) => ({ fishes: state.fishes + 1 })),
}))
const useStore = create((set) => ({
...useBearStore(set),
...useFishStore(set),
}))
Zustand ile özel hook'lar oluşturun:
import { useCallback } from 'react'
import create from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
export const useCounter = () => {
const { count, increment } = useStore()
const incrementAsync = useCallback(() => {
setTimeout(increment, 1000)
}, [increment])
return { count, increment, incrementAsync }
}
Immer kullanım örneği:
import create from 'zustand'
import produce from 'immer'
const useStore = create((set) => ({
todos: [],
addTodo: (todo) =>
set(
produce((state) => {
state.todos.push(todo)
})
),
}))
Zustand store'larınızı test edin:
import { create } from 'zustand'
import { act } from 'react-dom/test-utils'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
}))
describe('useStore', () => {
it('should increment counter', () => {
const { result } = renderHook(() => useStore())
act(() => {
result.current.increment()
})
expect(result.current.count).toBe(1)
})
})
2024 © Tüm hakları saklıdır - buraxta.com