Atom
Course: Recoil - chapter 4
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.
- Initialise a react project
npm create vite@latest- Add recoil as a dependency
npm install recoil- Wrap the app inside a RecoilRoot
import { RecoilRoot } from "recoil";
function App() {
return ( <RecoilRoot> <Counter /> </RecoilRoot> )}- Create a counter atom
const counter = atom({ key: "counter", default: 0})- Create a Buttons component
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>}- Use the counter atom
function Counter() { const count = useRecoilValue(counter);
return <div> {count} <Buttons /> </div>}Does it fix re-rendering?
Section titled “Does it fix re-rendering?”
Why doesnt it fix re-renders?
Section titled “Why doesnt it fix re-renders?”
Gist from class - ‣