Skip to content

Instantly share code, notes, and snippets.

@rphansen91
Created June 14, 2020 19:42
Show Gist options
  • Save rphansen91/70300be9f89634719d90082aee55a3e8 to your computer and use it in GitHub Desktop.
Save rphansen91/70300be9f89634719d90082aee55a3e8 to your computer and use it in GitHub Desktop.
RecoilCounter.tsx
import React from 'react';
import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil';
import Counter from '../Components/Counter'
const counterState = atom({
key: 'counter',
default: 0
});
const isEvenState = selector({
key: 'isEven',
get: ({ get }) => {
const count = get(counterState)
return count % 2 ? 'odd' : 'even'
}
})
const useIncrease = () => {
const setCounter = useSetRecoilState(counterState)
const increase = (n = 1) => {
setCounter(count => count + n)
}
return increase
}
const useDecrease = () => {
const setCounter = useSetRecoilState(counterState)
const decrease = (n = 1) => {
setCounter(count => count - n)
}
return decrease
}
export const RecoilCounter = () => {
const count = useRecoilValue(counterState)
const even = useRecoilValue(isEvenState)
const decrease = useDecrease()
const increase = useIncrease()
return (
<Counter
title="Recoil Counter"
value={count}
helperText={`${count} is ${even}`}
onIncrease={() => increase(1)}
onDecrease={() => decrease(1)}
/>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment