Skip to content

Instantly share code, notes, and snippets.

@BinodNagarkoti
Created July 3, 2024 15:42
Show Gist options
  • Save BinodNagarkoti/170dde07bdb421004a9de35db08bb44e to your computer and use it in GitHub Desktop.
Save BinodNagarkoti/170dde07bdb421004a9de35db08bb44e to your computer and use it in GitHub Desktop.
//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