🖥️Frontend/React

[React] zustand

뉴발자 2023. 11. 18.
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

그림 1-1. zustand

 

 

zustand

리액트를 처음 접하는 개발자라면 Redux를 사용하기엔 무리가 있을 것이다.

 

이유는 복잡한 사용 방법때문이다.

 

그래서 프로젝트를 시작할 때 zustand를 채택해서 사용했다.

 

 

zustand는 Redux, Mobx와 같이 상태 관리 라이브러리 중 하나이다.

 

Redux와 같은 방식으로 상태를 관리하지만 라이브러리가 가볍고 사용 방법이 간단하다.

 

zustand는 Redux와 같은 Flux 방식으로 한 곳에서 상태를 관리한다.

 

한 곳에서 상태를 관리하게 되면 여러 컴포넌트에서 공유하는 상태를 관리하는데 효과적이다.

 

 

더욱 자세한 내용은 아래 블로그에 잘 정리되어있다.

 

https://velog.io/@greencloud/%EC%9A%B0%EB%A6%AC-%ED%8C%80%EC%9D%B4-Zustand%EB%A5%BC-%EC%93%B0%EB%8A%94-%EC%9D%B4%EC%9C%A0

 

우리 팀이 Zustand를 쓰는 이유

다른 것도 좋은데.

velog.io

 

 

zustand create

zustand를 사용하면 Redux보다 쉽고 가볍게 상태를 관리할 수 있게 된다.

 

먼저 Redux와 동일하게 store를 생성해준다.

 

interface를 생성한 뒤 사용할 상태 객체를 넣어주고 zustand의 create 함수를 통해 생성해주면 된다.

 

create로 생성할 state에 초기값을 넣어주고 state를 변경할 함수를 넣어주면 된다.

 

get을 사용하면 현재 state의 값을 가져올 수 있고, set을 사용하면 state의 값을 변경할 수 있다.

 

Redux와의 차이점은 Redux는 Provider로 감싸줘야 store의 state를 사용할 수 있지만, zustand는 바로 사용이 가능하다.

// useZustandStore.ts
import { create } from "zustand";

interface State {
  counter: number;
  setCounter: (data: number) => void;
}

const useZustandStore = create<State>()(get, set) => ({
  counter: 0,
  setCounter: (data) => { set({ counter: data }),
});

 

 

zustand 사용

create로 state를 생성한 후 사용할 컴포넌트 안에서 해당 state와 state의 상태를 변경할 함수를 선언해준다.

 

아래는 +, - 버튼을 누르면 state의 값이 증가, 감소하는 코드이다.

// App.tsx
import useZustandStore from "../store/useZustandStore";

const App = () => {
  const { counter, setCounter } = useZustandStore();

  return (
    <div>
      <p>{counter}</p>
      <button onClick={() => setCounter(counter + 1)}>+</button>
      <button onClick={() => setCounter(counter - 1)}>-</button>
    </div>
  );
};

export default App;

 

zustand에 set 함수를 정의하지 않아도 state 값을 변경할 수 있다.

// App.tsx
import useZustandStore from "../store/useZustandStore";

const App = () => {
  const onChangeState = () => {
    let state = "";
    
    if( state === "") {
      state = "active";
      useZustandStore.setState({ state });
    }
  };

  ...
};

export default App;

 

 

참고 사이트

https://www.nextree.io/zustand/

 

상태 관리 라이브러리 Zustand

Zustand는 상태 관리 라이브러리 중 하나로, 작은 패키지 크기와 직관적인 사용법 덕분에 Redux와 Mobx와 더불어 많은 개발자들로부터 선택받고 있습니다. Zustand는 일반적으로 위의 예시 코드처럼 사

www.nextree.io

 

 

 

 

 

 

 

 

 

 

728x90

'🖥️Frontend > React' 카테고리의 다른 글

[React] canvas & x, y좌표 값으로 길 그리기  (0) 2023.11.28
[React] RTK & TypeScript  (1) 2023.11.20
[React] Redux & RTK  (0) 2023.11.17
[React] xlsx & file-saver & csv  (0) 2023.09.14
[React] React 배포 시 CORS 이슈  (0) 2023.09.13

댓글