Created
January 17, 2025 14:03
-
-
Save Smnthjm08/682ebd4360cb8acc131a0ea893cce071 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//store/atom/counter.js | |
import { atom, selector } from "recoil"; | |
export const counterAtom = atom({ | |
key: "counter", | |
default: 0, | |
}); | |
export const evenSelector = selector({ | |
key: "isEvenSelector", | |
get: function ({ get }) { | |
const currentCount = get(counterAtom); | |
const isEven = currentCount % 2 == 0; | |
return isEven; | |
}, | |
}); | |
//App.jsx | |
import { RecoilRoot, useRecoilValue, useSetRecoilState } from "recoil"; | |
import { counterAtom, evenSelector } from "./store/atoms/counter"; | |
function App() { | |
return ( | |
<RecoilRoot> | |
<Buttons /> | |
<Counter /> | |
<IsEven /> | |
</RecoilRoot> | |
); | |
} | |
export default App; | |
function Buttons() { | |
const setCount = useSetRecoilState(counterAtom); | |
return ( | |
<div> | |
<button onClick={() => setCount((c) => c + 2)}>Increase</button> | |
<button onClick={() => setCount((c) => c - 1)}>Decrease</button> | |
</div> | |
); | |
} | |
function Counter() { | |
const count = useRecoilValue(counterAtom); | |
return <div>{count}</div>; | |
} | |
function IsEven() { | |
const even = useRecoilValue(evenSelector); | |
return <div>{even ? "Even" : "Odd"}</div>; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment