Skip to content

Instantly share code, notes, and snippets.

@Mvrs
Created April 15, 2021 19:47
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 Mvrs/b0536982b355e27fdce1d8be7b86bc00 to your computer and use it in GitHub Desktop.
Save Mvrs/b0536982b355e27fdce1d8be7b86bc00 to your computer and use it in GitHub Desktop.
Simple counter example utilizing a custom hook
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