Framework/React

[React] Zustand ์„ค์น˜ ๋ฐฉ๋ฒ• ๋ฐ ์˜ˆ์ œ ์‚ดํŽด๋ณด๊ธฐ

yuri lee 2023. 4. 17. 21:17
๋ฐ˜์‘ํ˜•

Intro

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” Zustand ์„ค์น˜ ๋ฐฉ๋ฒ• ๋ฐ ์˜ˆ์ก”๋ฅผ ์‚ดํŽด๋ณด๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค. ๊ทธ์ „์— ์•ž์„œ zustand ๊ฐ€ ๋ฌด์—‡์ธ์ง€ ๊ถ๊ธˆํ•˜์‹  ๋ถ„๋“ค์€ ์œ„ ํฌ์ŠคํŒ… ์ฐธ๊ณ  ๋ถ€ํƒ๋“œ๋ฆฝ๋‹ˆ๋‹ค :) 

 

How to install Zustand

Zustand ์„ค์น˜๋ฐฉ๋ฒ•์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.  ๊ฐ์ž ์‚ฌ์šฉํ•˜๋Š” ํŒจํ‚ค์ง€ ๊ด€๋ฆฌ ํˆด(npm / yarn)์— ๋งž์ถฐ ์„ค์น˜ํ•ด์ฃผ์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

1. npm 

npm install zustand

 

2. yarn 

yarn add zustand

 

Zustand Simple Example

๊ฐ„๋‹จํ•œ ์˜ˆ์ œ๋กœ ์นด์šดํ„ฐ๋ฅผ ๋งŒ๋“ค์–ด ๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

zustand๋ฅผ importํ•˜๊ณ , ์ƒํƒœ ์ปจํ…Œ์ด๋„ˆ๋ฅผ ์ƒ์„ฑํ•ด์ค๋‹ˆ๋‹ค. ์ปจํ…Œ์ด๋„ˆ ์•ˆ์—๋Š” count, increment(), decrement()์ด ๋“ค์–ด์žˆ์Šต๋‹ˆ๋‹ค.

import create from 'zustand'

const useCounterStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 })),
}))

 

์ดํ›„ Counter ์ปดํฌ๋„ŒํŠธ์—์„œ ์•ž์„œ ๋งŒ๋“ค์–ด๋†“์€ useCounterStore๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์•„๋ž˜์™€ ๊ฐ™์ด ์นด์šดํ„ฐ๋ฅผ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. useStore() ํ›…์„ ์‚ฌ์šฉํ•˜์—ฌ ์ƒํƒœ๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ , ์—…๋ฐ์ดํŠธ ํ•˜๋Š” ๋ชจ์Šต์ž…๋‹ˆ๋‹ค. 

import React from 'react'
import { useStore } from 'zustand'

const Counter = () => {
  const { count, increment, decrement } = useCounterStore()

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  )
}

 

๋ฐ˜์‘ํ˜•