Recoil과 Zustand는 둘 다 React 애플리케이션에서 상태 관리를 위한 라이브러리이다.
공통점:
차이점:
1. API 디자인:
import { atom, selector } from 'recoil';
// Atom 정의
export const countState = atom({
key: 'countState',
default: 0,
});
// Selector 정의
export const doubledCountState = selector({
key: 'doubledCountState',
get: ({ get }) => {
const count = get(countState);
return count * 2;
},
});
import React from 'react';
import { useRecoilState, useRecoilValue } from 'recoil';
import { countState, doubledCountState } from './state';
const Counter = () => {
const [count, setCount] = useRecoilState(countState);
const doubledCount = useRecoilValue(doubledCountState);
return (
<div>
<h1>Count: {count}</h1>
<h2>Doubled: {doubledCount}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={() => setCount(count - 1)}>Decrement</button>
</div>
);
};
export default Counter;
import create from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
export default useStore;
import React from 'react';
import useStore from './store';
const Counter = () => {
const { count, increment, decrement } = useStore();
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;
Recoil 상태는 RecoilRoot 컴포넌트 내에서 작동하기 한다. 이 컴포넌트는 상태의 최상위 컨테이너 역할을 하며, Recoil의 모든 상태는 이 컨테이너 내에서 관리된다.
Recoil의 상태와 상호작용하기 위해 useRecoilState, useRecoilValue, useSetRecoilState리액트 라이프사이클에서 상태 접근, 변경이 가능하다.
Zustand는 리액트 라이프사이클 밖에서도 상태에 접근, 변경할 수 있다.