Skip to content

Instantly share code, notes, and snippets.

@timbuckley
Created December 21, 2020 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timbuckley/fd473884f83f127f7e92e5d64dbdd7cf to your computer and use it in GitHub Desktop.
Save timbuckley/fd473884f83f127f7e92e5d64dbdd7cf to your computer and use it in GitHub Desktop.
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