๊ฐํธํ๊ณ ์ ์ฐํ ์ํ ๊ด๋ฆฌ๋ฅผ ๋์์ฃผ๋ Recoil์
atom๊ณผ selector, ๋ ๊ฐ์ง ์ ํ์ ์ํ๋ฅผ ์ ์ํ ์ ์๋ค.
atom
: ๋ณ๊ฒฝ ๊ฐ๋ฅํ ์ํ๋ฅผ ์ ์
selector
: ๋ค๋ฅธ ์ํ์ ํ์ ๊ฐ์ด๋ ๋ณํ๋ ๊ฐ์ ๊ณ์ฐํ๊ธฐ ์ํด ์ฌ์ฉ
npm install recoil
index.js
// RecoilRoot ๊ฐ์ ธ์ค๊ธฐ
import { RecoilRoot } from "recoil";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<RecoilRoot> // ์ถ๊ฐ
<App />
</RecoilRoot> // ์ถ๊ฐ
</React.StrictMode>
);
atom/usernameState.js
// atom ๊ฐ์ ธ์ค๊ธฐ
import { atom } from "recoil";
const usernameState = atom({
key: "usernameState",
default: "tata",
});
export default usernameState;
get ํจ์๋ฅผ ์ ์ํ์ฌ ํด๋น ์ํ๋ฅผ ๊ณ์ฐํ ์ ์๋ค.
selector/nameLengthState.js
// selector ๊ฐ์ ธ์ค๊ธฐ
import { selector } from "recoil";
import usernameState from "../atom/usernameState";
const nameLengthState = selector({
key: "nameLengthState",
get: ({ get }) => {
const username = get(usernameState);
return username.length;
},
});
export default nameLengthState;
useRecoilState
: useState์ฒ๋ผ ์ํ ๊ฐ ๋ณ๊ฒฝ๋ ๊ฐ๋ฅ
useRecoilValue
: ์ํ ๊ฐ๋ง ๊ฐ์ ธ์ค๊ธฐ
import { useRecoilState, useRecoilValue } from "recoil";
import nameState from "../atom/usernameState";
import nameLengthState from "../selector/nameLengthState";
const Main = () => {
const [username, setUsername] = useRecoilState(nameState);
const name = useRecoilValue(nameState);
const nameLength = useRecoilValue(nameLengthState);
const changeName = () => {
setUsername("chimmy");
};
const resetName = () => {
setUsername("tata");
};
return (
<>
<span>{username}</span>
<button onClick={changeName}>Change Name</button>
<button onClick={resetName}>Reset</button>
<p>{name}</p>
<p>{nameLength}</p>
</>
);
};
export default Main;
useSetRecoilState
: ์ํ ๊ฐ ๋ณ๊ฒฝ ๊ฐ๋ฅ
useResetRecoilState
: ๋ํดํธ ์ํ ๊ฐ์ผ๋ก ๋ณ๊ฒฝ
import { useSetRecoilState, useResetRecoilState, useRecoilValue } from "recoil";
import nameState from "../atom/usernameState";
const Main = () => {
const username = useRecoilValue(nameState);
const resetName = useResetRecoilState(nameState); // ์ํ ๊ฐ ๋ณ๊ฒฝ ๊ฐ๋ฅ
const change = useSetRecoilState(nameState); // ๋ํดํธ ์ํ ๊ฐ์ผ๋ก ๋ณ๊ฒฝ
const changeName = () => {
change("chimmy");
};
return (
<>
<span>{username}</span>
<button onClick={changeName}>Change Name</button>
<button onClick={resetName}>Reset</button>
</>
);
};
export default Main;
useSetRecoilState๋ก๋ง ์ํ ๊ฐ ๋ณ๊ฒฝํ ๋
/* atom/infoState.js */
import { atom } from 'recoil';
const defaultValue = {
info2: '',
info4: '',
date: '',
info5: '',
info6: [],
};
const infoState = atom({
key: 'infoState',
default: defaultValue,
});
export default infoState;
/* Title.jsx */
import { useSetRecoilState } from 'recoil';
function Title() {
const setInfoState = useSetRecoilState(infoState);
const handleInputChange = (e) => {
const value = e.target.value;
setInfoState((data) => ({ ...data, info2: value }));
};
...