Skip to content

Instantly share code, notes, and snippets.

@Smnthjm08
Created January 17, 2025 14:03
Show Gist options
  • Save Smnthjm08/682ebd4360cb8acc131a0ea893cce071 to your computer and use it in GitHub Desktop.
Save Smnthjm08/682ebd4360cb8acc131a0ea893cce071 to your computer and use it in GitHub Desktop.
//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