Created
April 15, 2021 19:47
-
-
Save Mvrs/b0536982b355e27fdce1d8be7b86bc00 to your computer and use it in GitHub Desktop.
Simple counter example utilizing a custom hook
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"; | |
import "./styles.css"; | |
// Author: Marlon Johnson | |
// Date: 4/15/2021 | |
// Time: 00:08 | |
// another to way for a user to control the state of our app | |
// a way to avoid prop-drilling | |
// which can cause collision issues when your logic becomes difficult to maintain | |
// this solution solves the `duplicate render` issue in your component | |
// we can import these as modules as well | |
const STEP = 2; | |
const STEP_DOWN = 1; | |
function useCount({ initialCount = 0, step, stepDown }) { | |
const [count, setCount] = useState(initialCount); | |
const increment = () => setCount(count + step); | |
const decrement = () => setCount(count - stepDown); | |
return { increment, decrement, count }; | |
} | |
export default function App() { | |
// destruct what we need | |
const { increment, decrement, count } = useCount({ | |
step: STEP, | |
stepDown: STEP_DOWN | |
}); | |
return ( | |
<div className="App"> | |
<span>The current count is: {count}</span> | |
<br /> | |
<button onClick={increment}>increment</button> | |
<button onClick={decrement}>decrement</button> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment