์‹œ๋ƒ…์Šค

react์—์„œ Zustand๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ• ๋ณธ๋ฌธ

ReactJS

react์—์„œ Zustand๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

ted k 2021. 12. 3. 15:09

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 ๋ฌธ๋ฒ•๋“ค๋„ ์ง€์›ํ•˜๊ณ  ์žˆ์ง€๋งŒ

ํ•„์ž๋Š” ๊ทธ๋Ÿฐ ๊ฒƒ๋“ค์€ ๋ฆฌ๋•์Šค์—์„œ ํ•˜๊ณ  ์‹ถ๋‹ค...

Comments