import { useState } from 'react'; // Custom hook to manage a counter function useCounter(initialValue = 0) { const [count, setCount] = useState(initialValue); // Function to increment the count const increment = () => { setCount(count + 1); }; // Function to decrement the count const decrement = () => { setCount(count - 1); }; // Return the count value and functions to update it return { count, increment, decrement }; } // Example usage: function Counter() { // Use the custom hook to manage the counter const { count, increment, decrement } = useCounter(0); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> </div> ); }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter