React
Storybook Decorator 로 전역 상태 사용하기
bkdragon
2024. 11. 7. 21:28
공식문서에서는 Decorator 는 Story 을 감싸는 것이라고 설명한다.
Decorator 를 사용하면 레이아웃을 잡거나 Story 에서 특정 컨텍스트를 공유하게 하는 것이 가능하다.
zustand 전역 상태가 불필요하게 모든 Story가 아닌 특정 story 내에서만 유지되게 해보자.
export const Default: Story = {
name: "Default",
parameters: {
withZustand : true
},
};
parameters 에 withZustand 라는 임의의 키를 추가하고 true 값을 설정해줬다.
import { useEffect } from "react";
import { useStore } from "@/hooks/useStore";
import { Decorator } from "@storybook/react";
export const withZustand: Decorator = (Story, context) => {
const resetStore = useSystemTabStore((state) => state.reset);
useEffect(() => {
if (context.parameters?.withZustand) {
resetStore();
} else {
localStorage.removeItem("zustand-store");
}
}, [context.parameters.withTabStore, resetStore]);
return <Story {...context} />;
};
withZustand 가 true 인 스토리 일 때 초기값을 설정해주고, 아닐 때는 삭제한다.
Decorator 적용은 전역적으로도 가능하고 특정 스토리에도 가능하다.
.storybook/preview.ts 에서 전역적으로 설정할 수 있다.
import type { Preview } from "@storybook/react";
import "@/main.css";
import { withZustand } from "../src/stories/decorators/withZustand";
const preview: Preview = {
decorators: [withZustand],
parameters: {
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/i,
},
},
},
};
export default preview;