REACT

[React] Zustand 적용하기 #1

user-anonymous 2024. 2. 5. 23:55
728x90

Zustand란?

Zustand는 상태관리 라이브러리로 간단한 API 기반 훅스의 구조를 가지고 있다. 또한 Zustand는 오픈 소스로 안정화를 위해 많은 개발자들이 현재 힘쓰고 있다.

 

우리가 흔히 들어본 Redux와 사용법이 다르다. Zustand는 간단하다는 장점이 있다.

Redux는 store.js를 사용하기 위해 따로 설정해줘야 하는 코드가 많다.   

- createStore

- combineReducer

- Reducer...

import { combineReducers } from "redux";
import nameTag from "./nameTag";
import location from "./location";
import excel from "./excelData";

const rootReducer = combineReducers({ nameTag, location, excel });

export default rootReducer;

...복잡

 

하지만 Zustand는 

각 상태 조각들은 별도의 스토어에 정의되어 관련 상태 속성 및 관련 작업의 모듈화를 할 수 있다.

 

 

Zustand 사용하기

Zustand는 자바스크립트 라이브러리로 Nodejs로 실행된다.그리하여 .nodejs.와 zustand를 설치해준다.

yarn add zustand 
npm install zustand

 

Zustand를 사용하기 위해 create 함수를 import 해준다.

import {create} from "zustand"

 

create 함수는 콜백함수로 커스텀 훅을 리턴해준다. 

create 함수는 set 파라미터 함수를 보내준다. 이 해당 set 함수는 store 안에 있는 상태들을 조작할 수 있도록 사용된다. 

const useChangeText = create ((set) => {
   return {
   		text : "happy",
        changeToSad : () => set((state) => ({text : "sad" })),
        };
});

 해당 store에는 총 2개의 상태가 있다. 바로 text와  changeToSad다. useChangeText는 커스텀 훅이다. 

우리는 이 훅을 사용하여 컴포넌트에서 가장 최신의 state값을 가져올 수 있다. 

 

이 훅을 컴포넌트 A와 B 에서 사용 중이라면, 만일 B 컴포넌트에서 상태 변화가 일어날 경우 이는 A 컴포넌트에도 동일하게 새롭게 state값이 변화 될 것이다.

 

.Custom 훅은 또 React-Redux에서 useSelector와 비슷하게 작동한다. 이는 스토어에서 상태를 선택해서 가져올 수 있도록 해준다. 훅을 호출한 후 콜백 함수에게 전달해준다면 이 함수는 현재 값을 넘겨준다.

const ShowText = () => {
	const displayText = useText((state)=> state.text);
    return <div> {displayText}</div>
};

 

그러면 ShowText 컴포넌트에 displayText가 store로 text의 state 값을 가져와서 출력해준다. 

 

다른 경우로, state 값을 바꾸는 역할을 하는 함수를 호출하고 싶다면 

const ChangeText = () => {
	const chgText = useChangeText ((state) => state.changeToSad);
    return (
    <button onClick ={chgText}>슬픔이</button>
    )
}

useChangeText의 커스텀 훅에서 text를 sad로 변경해주는 함수를 쉽게 호줄해줄 수 있다.

 

참고

- https://refine.dev/blog/zustand-react-state/#getting-started-with-zustand

728x90
반응형