모달을 열고 닫는 상태관리를 쉽게하기위해 Zustand로 상태관리를 진행하였다.
코드가 복잡한 Redux보다 쉽고 간단한 Zustand를 선택하였다.
yarn add zustand
// store.ts
import { create } from 'zustand';
type Store = {
show: boolean;
toggleModal: () => void;
};
const useModalStore = create<Store>()((set) => ({
show: false,
toggleModal: () => set((state) => ({ show: !state.show })),
}));
export default useModalStore;
Redux와 마찬가지로 store를 만들어준다.
zustand 의 create를 통해 store를 만든다.
create 안에는 기본값을 갖는 state를 설정하고, 함수명 형식으로 변경할 state에 대해 작성한다.
set은 상태를 변경하는 메서드이다.
// modal.tsx
import useModalStore from '@/store/modal';
import styles from '../styles/Modal.module.css';
interface Props {
children: React.ReactNode;
}
const Modal = ({ children }: Props) => {
const { toggleModal } = useModalStore();
return (
<div>
<div className={styles['modal-overlay']} onClick={toggleModal}></div>
<div className={styles['modal-content-container']}>
<div className={styles['modal-content']}>
<h1>모달테스트</h1>
{children}
<button
onClick={toggleModal}
className={styles['modal-close-button']}
type='button'
>
닫기
</button>
</div>
</div>
</div>
);
};
export default Modal;
설정한 store 이름으로 store를 실행하고 함수 혹은 상태를 가져와서 실행하면된다.