Created
December 21, 2020 19:38
-
-
Save timbuckley/fd473884f83f127f7e92e5d64dbdd7cf 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
import React, {useState} from 'react' | |
// Custom hook that manages local state for a counter. | |
export function useCounter(initialValue) { | |
const [count, setCount] = useState(initialValue) | |
const increment = () => setCount(count => count + 1) | |
const decrement = () => setCount(count => count - 1) | |
const reset = () => setCount(initialValue) | |
return { | |
reset, | |
count, | |
increment, | |
decrement | |
} | |
} | |
function Counter() { | |
// All the business logic around handling the count is contained in this custom hook. | |
// The component then can just care about how to render that data. | |
const { reset, count, increment, decrement } = useCounter() | |
return ( | |
<div> | |
<h1>{count}</h1> | |
<span onClick={increment}>+</span> | |
<span onClick={decrement}>Reset!</span> | |
<span onClick={reset}>Reset!</span> | |
</div> | |
) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment