๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ป DEV

[NextJS] Zustand ์‹œ์ž‘ํ•˜๊ธฐ(1)

by Rising Oneโ˜… 2023. 8. 21.
728x90
๋ฐ˜์‘ํ˜•
SMALL

Zustand ๋Œ€ํ‘œ์ด๋ฏธ์ง€

 

ํ•„์š”์„ฑ 

Web application์„ ์ œ์ž‘ํ•˜๋ฉด์„œ, Store(์ƒํƒœ)๋ฅผ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์€ ๋งค์šฐ ์ค‘์š”ํ•ด์กŒ์Šต๋‹ˆ๋‹ค. ์ƒํƒœ๊ด€๋ฆฌ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ Recoil ์—ญ์‹œ ํ›Œ๋ฅญํ•˜์ง€๋งŒ, ์ด๋ฒˆ ์ฐจ๋ก€์—์„œ๋Š” Zustand๋ฅผ ํ•™์Šตํ•ด๋ณด๊ณ ์ž ํ•ฉ๋‹ˆ๋‹ค. ๊ทธ ํ•™์Šต์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค. 


์ ‘๊ทผ

 

  1. Installation (์„ค์น˜)

- npm install zustand

 

  2. Store ์ƒ์„ฑํ•˜๊ธฐ

 

  3. ์ปดํฌ๋„ŒํŠธ ๋ฐ”์ธ๋”ฉ

 


๋ฐฉ๋ฒ•


  1. Installation (์„ค์น˜)

(NextJS ๋˜๋Š” React ํ”„๋กœ์ ํŠธ๋ฅผ ์ƒ์„ฑ ํ›„ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.)

 

์‚ฌ์šฉ์„ ์œ„ํ•ด npm ํŒจํ‚ค์ง€๋กœ ์„ค์น˜๋ถ€ํ„ฐ ์ง„ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

# npm
npm install zustand

 - ์ดํ›„ ์ •์ƒ์ ์œผ๋กœ ์„ค์น˜๊ฐ€ ๋˜์—ˆ๋‹ค๋ฉด, ํ”„๋กœ์ ํŠธ ๋‚ด package.json ํŒŒ์ผ > "dependencies"์— ๋‚˜์—ด๋จ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

 


  2. Store ์ƒ์„ฑํ•˜๊ธฐ

- Store๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค. (Store๋Š” Hooks์ž…๋‹ˆ๋‹ค.)

- ๋‚ด๋ถ€์—๋Š” primitives, objects, functions ๋“ฑ ๋ฌด์—‡์ด๋“  ๋„ฃ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

- ํ•จ์ˆ˜ "set"์€ ์ƒํƒœ๋ฅผ ๋ณ‘ํ•ฉํ•ฉ๋‹ˆ๋‹ค.

 

import { create } from 'zustand'

const useStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

 

  3. ์ปดํฌ๋„ŒํŠธ ๋ฐ”์ธ๋”ฉ

- ๊ณต๊ธ‰์ž๊ฐ€ ์—†์–ด๋„ ์–ด๋””์—์„œ๋‚˜ hooks๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

- ์ƒํƒœ๋ฅผ ์„ ํƒํ•˜๋ฉด ํ•ด๋‹น ์ƒํƒœ๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ ์†Œ๋น„ ๊ตฌ์„ฑ ์š”์†Œ๊ฐ€ ๋‹ค์‹œ ๋ Œ๋”๋ง๋ฉ๋‹ˆ๋‹ค.

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>
}

 

 


์ด์ƒ์œผ๋กœ, Zustand ํ•™์Šต์„ ์‹œ์ž‘ํ•ด๋ดค์Šต๋‹ˆ๋‹ค.

์ถ”๊ฐ€ ์งˆ๋ฌธ์„ ๋Œ“๊ธ€์„ ๋‹ฌ์•„์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค^^!

์˜ค๋Š˜๋„ ํŒŒ์ดํŒ…์ž…๋‹ˆ๋‹ค! 

728x90
๋ฐ˜์‘ํ˜•
LIST

๋Œ“๊ธ€