Atoms are units of state that can be read from and written to from any component. When an atom’s state changes, all components that subscribe to that atom will re-render.
npm create vite@latest
npm install recoil
import { RecoilRoot } from "recoil";
function App() {
return (
<RecoilRoot>
<Counter />
</RecoilRoot>
)
}
const counter = atom({
key: "counter",
default: 0
})
function Buttons() {
const setCount = useSetRecoilState(counter);
function increase() {
setCount(c => c + 1)
}
function decrease() {
setCount(c => c - 1)
}
return <div>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
</div>
}
function Counter() {
const count = useRecoilValue(counter);
return <div>
{count}
<Buttons />
</div>
}
Gist from class - https://gist.github.com/hkirat/36948713f8759a32a2a42446002d2b8d