Front-end 개발/JAVASCRIPT

jotai 유틸 atomWithStorage 활용하여 session storage 적용 테스트

별의 노트 2023. 1. 11. 16:15
반응형

jotai 유틸 atomWithStorage 활용하여 session storage 적용 테스트

import { useAtom, atom } from 'jotai';
import { atomWithStorage, createJSONStorage } from 'jotai/utils';

// session storage 적용
const darkModeAtom = atomWithStorage(
   'darkMode',
   false,
   createJSONStorage(() => sessionStorage),
);

const [darkMode, setDarkMode] = useAtom(darkModeAtom);

return (
    <div className={styles.study}>
      <div>
        <h1>Welcome to {darkMode ? 'dark' : 'light'} mode!</h1>
        <button onClick={() => setDarkMode(!darkMode)}>toggle theme</button>
    </div>
);