Created
July 3, 2024 15:42
-
-
Save BinodNagarkoti/170dde07bdb421004a9de35db08bb44e to your computer and use it in GitHub Desktop.
This file contains 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
//useCounter.tsx | |
import { useState } from 'react'; | |
function useCounter(initialValue = 0) { | |
const [count, setCount] = useState(initialValue); | |
const increment = () => setCount((prevCount) => prevCount + 1); | |
const decrement = () => setCount((prevCount) => prevCount - 1); | |
const reset = () => setCount(initialValue); | |
return { count, increment, decrement, reset }; | |
} | |
export default useCounter; | |
//CounterComponent.tsx | |
import React from 'react'; | |
import useCounter from './useCounter'; | |
function CounterComponent() { | |
const { count, increment, decrement, reset } = useCounter(0); | |
return ( | |
<div> | |
<p>Count: {count}</p> | |
<button onClick={increment}>Increment</button> | |
<button onClick={decrement}>Decrement</button> | |
<button onClick={reset}>Reset</button> | |
</div> | |
); | |
} | |
export default CounterComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment