@@ -162,61 +162,64 @@ export function useCopyToClipboard() {
162
162
export function useCounter ( startingValue = 0 , options = { } ) {
163
163
const { min, max } = options ;
164
164
165
- if ( min && startingValue < min ) {
165
+ if ( typeof min === "number" && startingValue < min ) {
166
166
throw new Error (
167
167
`Your starting value of ${ startingValue } is less than your min of ${ min } .`
168
168
) ;
169
169
}
170
170
171
- if ( max && startingValue > max ) {
171
+ if ( typeof max === "number" && startingValue > max ) {
172
172
throw new Error (
173
173
`Your starting value of ${ startingValue } is greater than your max of ${ max } .`
174
174
) ;
175
175
}
176
176
177
177
const [ count , setCount ] = React . useState ( startingValue ) ;
178
178
179
- const increment = ( ) => {
180
- const nextCount = count + 1 ;
181
- if ( max && nextCount > max ) {
182
- return ;
183
- }
179
+ const increment = React . useCallback ( ( ) => {
180
+ setCount ( ( c ) => {
181
+ const nextCount = c + 1 ;
184
182
185
- setCount ( nextCount ) ;
186
- } ;
183
+ if ( typeof max === "number" && nextCount > max ) {
184
+ return c ;
185
+ }
187
186
188
- const decrement = ( ) => {
189
- const nextCount = count - 1 ;
190
- if ( min && nextCount < min ) {
191
- return ;
192
- }
187
+ return nextCount ;
188
+ } ) ;
189
+ } , [ max ] ) ;
193
190
194
- setCount ( nextCount ) ;
195
- } ;
191
+ const decrement = React . useCallback ( ( ) => {
192
+ setCount ( ( c ) => {
193
+ const nextCount = c - 1 ;
196
194
197
- const set = ( nextCount ) => {
198
- if ( max && nextCount > max ) {
199
- return ;
200
- }
195
+ if ( typeof min === "number" && nextCount < min ) {
196
+ return c ;
197
+ }
201
198
202
- if ( min && nextCount < min ) {
203
- return ;
204
- }
199
+ return nextCount ;
200
+ } ) ;
201
+ } , [ min ] ) ;
205
202
206
- if ( nextCount === count ) {
207
- return ;
208
- }
203
+ const set = React . useCallback (
204
+ ( nextCount ) => {
205
+ setCount ( ( c ) => {
206
+ if ( typeof max === "number" && nextCount > max ) {
207
+ return c ;
208
+ }
209
209
210
- setCount ( nextCount ) ;
211
- } ;
210
+ if ( typeof min === "number" && nextCount < min ) {
211
+ return c ;
212
+ }
212
213
213
- const reset = ( ) => {
214
- if ( count === startingValue ) {
215
- return ;
216
- }
214
+ return nextCount ;
215
+ } ) ;
216
+ } ,
217
+ [ max , min ]
218
+ ) ;
217
219
220
+ const reset = React . useCallback ( ( ) => {
218
221
setCount ( startingValue ) ;
219
- } ;
222
+ } , [ startingValue ] ) ;
220
223
221
224
return [
222
225
count ,
0 commit comments