Created
June 14, 2020 19:42
-
-
Save rphansen91/70300be9f89634719d90082aee55a3e8 to your computer and use it in GitHub Desktop.
RecoilCounter.tsx
This file contains 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
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