Last active
June 14, 2020 19:42
-
-
Save rphansen91/134821ff418e838921cd10b513c6e78d to your computer and use it in GitHub Desktop.
react-hawk vs context vs recoil examples
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
import React, { | |
createContext, | |
useContext, | |
useState, | |
FC, | |
Dispatch, | |
SetStateAction, | |
} from "react"; | |
import Counter from "../Components/Counter"; | |
const CounterContext = createContext<{ | |
value: number; | |
setValue: Dispatch<SetStateAction<number>>; | |
}>({ | |
value: 0, | |
setValue: (n = 1) => console.warn("CounterProvider not supplied"), | |
}); | |
const useCounterValue = () => { | |
const { value } = useContext(CounterContext); | |
return value; | |
}; | |
const useCounterIsEven = () => { | |
const { value } = useContext(CounterContext); | |
return value % 2 ? "odd" : "even"; | |
}; | |
const useDecrease = () => { | |
const { setValue } = useContext(CounterContext); | |
const decrease = (n = 1) => { | |
setValue((v) => v - n); | |
}; | |
return decrease; | |
}; | |
const useIncrease = () => { | |
const { setValue } = useContext(CounterContext); | |
const increase = (n = 1) => { | |
setValue((v) => v + n); | |
}; | |
return increase; | |
}; | |
export const CounterProvider: FC = ({ children }) => { | |
const [value, setValue] = useState(0); | |
return ( | |
<CounterContext.Provider value={{ value, setValue }}> | |
{children} | |
</CounterContext.Provider> | |
); | |
}; | |
export const ContextCounter = () => { | |
const count = useCounterValue(); | |
const even = useCounterIsEven(); | |
const decrease = useDecrease(); | |
const increase = useIncrease(); | |
return ( | |
<Counter | |
title="Context Counter" | |
value={count} | |
helperText={`${count} is ${even}`} | |
onIncrease={() => increase(1)} | |
onDecrease={() => decrease(1)} | |
/> | |
); | |
}; | |
export default ContextCounter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment