EventsInteractivity
useCounter
The useCounter hook is useful for managing a counter value with additional options for minimum and maximum limits. The hook takes a starting value and options object as parameters, which can specify minimum and maximum limits for the counter. If the starting value falls outside the specified limits, an error is thrown. The hook returns the current count value and an object containing functions to increment, decrement, set a specific count, and reset the counter.
Parameters
Name | Type | Description |
---|---|---|
initialValue | number | The value you'd like the counter to start at. |
Return Values
Name | Type | Description |
---|---|---|
counter.count | number | Returns the current count value. |
counter.doubled | number | Stored the doubled count value, equivilant of using |
counter.increment | function | A function that increments the count value by |
counter.reset | function | A function that will reset the count back to the |
Source Code
const useCounter = (initialValue = 0) => { let count = $state(initialValue); const increment = () => { count++; }; const reset = () => { count = 0; }; return { get count() { return count; }, get doubled() { return count * 2; }, increment, reset, }; }; export default useCounter;
Value 0
Doubled 0
<script> import useCounter from "./useCounter.svelte"; let counter = useCounter(); </script> <div class="container"> <div class="box-list"> <div class="box"> <span class="label">Value</span> <span class="num">{counter.count}</span> </div> <div class="box"> <span class="label">Doubled</span> <span class="num">{counter.doubled}</span> </div> </div> <div class="button-list"> <button on:click={counter.increment}>Increment</button> <button disabled={counter.count === 0} on:click={counter.reset}>Reset</button> </div> </div> <style> .container { display:flex; flex-direction:column; align-items:center; gap:20px; } .box-list { display:flex; gap:20px; } .box { display:flex; flex-direction:column; gap:10px; } .box .label { text-transform:uppercase; font-size:12px; font-weight:600; letter-spacing:1px; text-align:center; color:rgba(255,255,255,.7); } .box .num { padding:10px 20px; background-color:rgba(255,255,255,.07); border-radius:5px; width:70px; text-align:center; } .button-list { display:flex; gap:20px; } .button-list button { width:110px; } .button-list button:disabled { opacity:.5; cursor:not-allowed; } </style>