react์์ Zustand๋ฅผ ์ฌ์ฉํ๋ ๋ฐฉ๋ฒ
Zustand
GitHub - pmndrs/zustand: ๐ป Bear necessities for state management in React
๐ป Bear necessities for state management in React. Contribute to pmndrs/zustand development by creating an account on GitHub.
github.com
๋ฏธ๋ ๋ฆฌ๋์ค...
๋ฆฌ๋์ค์ ๋ณด์ผ๋ฌ ํ๋ ์ดํธ์ ๊ดํ ํผ๋ก๊ฐ์ด ์๋นํ๊ธฐ ๋๋ฌธ์
๊ฐ๋จํ state๋ฅผ ๋ค๋ฃจ๊ธฐ์ Zustand๋ ๊ต์ฅํ ์ ์ฉํ๋ค.
import create from 'zustand'
const useStore = create(set => ({
bears: 0,
increasePopulation: () => set(state => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 })
}))
create๋ฅผ ํตํด์ store๋ฅผ ๋ง๋ค์ด ์ค ํ
๊ฐ ํจ์๋ฅผ ํตํด์ state๋ฅผ ๋ณํ์ํจ๋ค.
๊ทธ ์์ฒด๋ก ๋ฆฌ๋์์ ์ก์ ์ ๋์ฒดํ ์ ์๋ค.
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>
}
state๋ฅผ ํ์ธํ๊ฑฐ๋, ์ก์ ์ ์ฃผ๋ ๊ฒ๋ ์์ ๊ฐ์ด ํ ์ ์๋ค!
import shallow from 'zustand/shallow'
// Object pick, re-renders the component when either state.nuts or state.honey change
const { nuts, honey } = useStore(state => ({ nuts: state.nuts, honey: state.honey }), shallow)
// Array pick, re-renders the component when either state.nuts or state.honey change
const [nuts, honey] = useStore(state => [state.nuts, state.honey], shallow)
// Mapped picks, re-renders the component when state.treats changes in order, count or keys
const treats = useStore(state => Object.keys(state.treats), shallow)
์์ ๋ณต์ฌ์ ๋ํด์๋ ์ง์ํ๊ณ ์๋ค.
๋ฏธ๋ค์จ์ด๋ redux-like ๋ฌธ๋ฒ๋ค๋ ์ง์ํ๊ณ ์์ง๋ง
ํ์๋ ๊ทธ๋ฐ ๊ฒ๋ค์ ๋ฆฌ๋์ค์์ ํ๊ณ ์ถ๋ค...