반응형
말로만 듣던 쉽고 편하다는 zustand를 프로젝트에 적용하기 위해 사용 해 보았다.
# 이하 예제에서 할것
- state를 true로 만들기
- state를 토글로 관리
- count +1 및 초기화
1 . 먼저 create-react-app으로 만든 프로젝트에 아래 경로처럼 store를 관리할 파일을 만듬.
=> src\store\store.js를 만들어 줌
//store.js
// zustand의 create를 사용하여 store를 생성.
import {create} from 'zustand'
//create 안에는 기본값을 갖는 state를 설정 , 함수명 형식으로 변경할 state에 대해 작성.
//set()은 상태를 변경하는 메서드
// state를 false => true로 바꿔주고자 할때
export const useSetState = create((set) => ({
state: false,
setState: (newValue) => set({ state: newValue }),
}));
// toogle state
export const useBooleanStore= create((set)=>({
booleanState : false,
setBooleanState: () => set((state) => ({ booleanState: !state.booleanState })),
}));
// count 및 remove
// setCount : 현재 state를 받아와서 1증가한 값을 새로운 count로 설정,
// removeCount : count값을 0으로 설정
export const useCountStore = create((set)=>({
count : 0,
setCount : () => set((state)=>({count : state.count+1})),
removeCount : () => set(()=>({count : 0})),
}))
2 . component에 가져와서 사용 하면 끗.
=> src\pages\test.jsx
//test.jsx
//zustand로 관리할 store를 import
import { useSetState, useBooleanStore, useCountStore, } from '../store/store.js';
const Test = () => {
const { state, setState } = useSetState();
const { booleanState, setBooleanState } = useBooleanStore();
const { count, setCount, removeCount} = useCountStore();
//현재 false인 State를 true로 변경하기
function handleClick() {
setState(true);
}
//토글 state
function handleClick2() {
setBooleanState();
}
//setCount()를 호출하여 count +1
//removeCount()를 호출하여 count 0으로 초기화
return(
<>
<p>Boolean state value: {booleanState.toString()}</p>
<button className="mt-5" onClick={handleClick}>Set to {state ? "true" : "false"}</button>
<button onClick={handleClick2}>Set to {booleanState ? " toggle true" : "toggle false"}</button>
{<div>count : {count}</div>}
<button onClick={() => setCount()}>Increment Count</button>
<button onClick={() => removeCount()}>remove Count</button>
</>
)
}
export default Test;
redux는 action 하나마다 switch case..return..
쓸때는 dispatch({type: "어쩌구"}) 하면서 길고 장황하게 쓰는 반면
zustand는 심플해서 좋은것 같다.
참고 :
반응형
'Web Front-end > react' 카테고리의 다른 글
서버 사이드 렌더링이란? (SSR / Server Side Rendering) (0) | 2023.01.10 |
---|---|
React로 로그인, 로그아웃 기능 구현하기(짱 쉽게) (0) | 2022.12.06 |
리액트에서 자주 쓰이는 자바스크립트 문법 3가지 (0) | 2022.11.11 |
리액트 메모 모음 (0) | 2022.11.04 |