๐ก ๋ฆฌ์ฝ์ผ ๊ณต์ ๋ฌธ์ ์ฐธ๊ณ ํ์ฌ ์ ๋ฆฌ ๋ฐ ๊ณต๋ถ
๊ณ ์ ํ key๊ฐ๊ณผ ๊ธฐ๋ณธ๊ฐ์ ๊ฐ์ง
const fontSizeState = atom({
key: 'fontSizeState',
default: 14,
});
useRecoilState
hook
function FontButton() {
const [fontSize, setFontSize] = useRecoilState(fontSizeState);
return (
<button onClick={() => setFontSize((size) => size + 1)} style={{fontSize}}>
Click to Enlarge
</button>
);
}
atoms ์ํ๊ฐ์ ๋๊ธฐ ๋๋ ๋น๋๊ธฐ ๋ฐฉ์์ ํตํด ๋ณํ
์์์ atoms ๋๋ selectors๊ฐ ์ ๋ฐ์ดํธ ๋๋ฉด ํ์์ selector ํจ์๋ ๋ค์ ์คํ
atoms์ฒ๋ผ ๊ตฌ๋ ํ ์ ์์ผ๋ฉฐ, selectors๊ฐ ๋ณ๊ฒฝ๋๋ฉด ์ปดํฌ๋ํธ ๋ค์ ๋ฆฌ๋ ๋๋ง
์ํ๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ํ๋ ํ์ ๋ฐ์ดํฐ๋ฅผ ๊ณ์ฐํ๋๋ฐ ์ฌ์ฉ
์ต์ํ์ ์ํ๋ง atoms์ ์ ์ฅํ๊ณ ๋ค๋ฅธ ๋ฐ์ดํฐ๋ค์ selectors ํจ์๋ฅผ ํตํด ํจ์จ์ ์ผ๋ก ๊ณ์ฐํจ์ผ๋ก์จ ์ธ๋ชจ์๋ ์ํ์ ๋ณด์กด์ ๋ฐฉ์ง
const fontSizeLabelState = selector({
key: 'fontSizeLabelState',
// get : ๊ณ์ฐ๋ ํจ์
get: ({get}) => {
const fontSize = get(fontSizeState);
const unit = 'px';
return `${fontSize}${unit}`;
},
});
useRecoilValue()
: ํ๋์ atom์ด๋ selector๋ฅผ ์ธ์๋ก ๋ฐ์ ๋ฐํ
function FontButton() {
const [fontSize, setFontSize] = useRecoilState(fontSizeState);
const fontSizeLabel = useRecoilValue(fontSizeLabelState);
return (
<>
<div>Current font size: ${fontSizeLabel}</div>
<button onClick={setFontSize(fontSize + 1)} style={{fontSize}}>
Click to Enlarge
</button>
</>
);
}
์ ์ ์์ฑํ [TypeScript] ๋ณ์ ์์ฝ ์์คํ ๊ตฌํ์์ ์ฌ์ฉ๋ recoil ์ ๋ฆฌ
import { RecoilRoot } from 'recoil';
function App() {
return (
<ThemeProvider theme={theme}>
<GlobalStyle />
<Layout>
<RecoilRoot>
<Main />
</RecoilRoot>
</Layout>
</ThemeProvider>
);
}
// atom.ts
export const globalState = atom<DefaultType[]>({
key: 'globalState',
default: [],
});
ํด๋น state๊ฐ ํ์ํ ์ปดํฌ๋ํธ์์ ํธ์ถํ์ฌ ์ฌ์ฉ
const Main = () => {
const setGlobalAtom = useSetRecoilState(globalState);
useEffect(() => {
setGlobalAtom(DATA.data);
}, []);
return (
<Wapper>
<Calendar />
</Wapper>
);
};
export default Main;
// DATA ํํ
const DATA = {
data: [
{
id: 220101,
user_name: 'ํ๊ธธ๋',
user_phone: '010-3286-6377',
booking_date: '2022-10-17',
booking_time: '16:00',
categories: '๊ฒ์ง',
},
...
]
}
// Calendar.tsx
const reserved = useRecoilValue(globalState);
const Data = reserved.map(function (item) {
const obj = {
title: `${item.booking_time} ${item.user_name} ${item.categories}`,
start: item.booking_date,
end: item.booking_date,
};
return obj;
});
// Calendar.tsx
<FullCalendar
locale={'ko'}
plugins={[dayGridPlugin, interactionPlugin]}
dayMaxEventRows={true}
events={Data}
eventColor="#EFB33F"
selectable={true}
dateClick={(info: DateClickArg) => {
setSelectDate(info.dateStr);
reserveHandler();
}}
/>