Recoil 설치
npm install recoil
Recoil 속성 (selector, useRecoilValue, useRecoilState)
// _app.tsx
import type { AppProps } from "next/app";
import { RecoilRoot } from "recoil";
export default function App({ Component, pageProps }: AppProps) {
return (
<RecoilRoot>
<Component {...pageProps} />
</RecoilRoot>
);
}
// atom.tsx
import { atom } from "recoil";
import { v4 as uuidv4 } from "uuid";
export const usernameState = atom({
key: `userName${uuidv4()}`,
default: "",
});
export const filpState = atom({
key: `flipData${uuidv4()}`,
default: false,
});
// pages/index.tsx
import React from "react";
import { useRecoilState, useRecoilValue } from "recoil";
import Profile from "@/components/test/Profile";
import CountUser from "@/components/test/CountingChar";
import { usernameState } from "@/atom";
const Index = () => {
const user = useRecoilValue(usernameState);
const [user2, setUser2] = useRecoilState(usernameState);
return (
<>
<Profile />
<CountUser />
user: {user}
<br />
user2: {user2}
</>
);
};
export default Index;
// components/Profile.tsx
import { usernameState } from "@/atom";
import React from "react";
import { useRecoilState } from "recoil";
const Profile = () => {
const [userName, setUsername] = useRecoilState(usernameState); // useState랑 판박이
return (
<>
<h2>Profile</h2>
<div>userName: {userName}</div>
<input
type="text"
value={userName}
placeholder="userName"
onChange={(e) => setUsername(e.target.value)}
/>
</>
);
};
export default Profile;
// components/CountUser
import { usernameState } from "@/atom";
import React from "react";
import { selector, useRecoilValue } from "recoil";
import { v4 as uuidv4 } from "uuid";
const CountUser = () => {
const countState = selector({
key: `countUser${uuidv4()}`,
get: ({ get }) => {
const userName = get(usernameState);
return userName;
},
});
const count = useRecoilValue(countState);
return (
<div>
<div>count.length: {count.length}</div>
<div/>
);
};
export default CountUser;
위의 예시처럼 사용할 수 있다.