@@ -162,61 +162,64 @@ export function useCopyToClipboard() {
162162export function useCounter ( startingValue = 0 , options = { } ) {
163163 const { min, max } = options ;
164164
165- if ( min && startingValue < min ) {
165+ if ( typeof min === "number" && startingValue < min ) {
166166 throw new Error (
167167 `Your starting value of ${ startingValue } is less than your min of ${ min } .`
168168 ) ;
169169 }
170170
171- if ( max && startingValue > max ) {
171+ if ( typeof max === "number" && startingValue > max ) {
172172 throw new Error (
173173 `Your starting value of ${ startingValue } is greater than your max of ${ max } .`
174174 ) ;
175175 }
176176
177177 const [ count , setCount ] = React . useState ( startingValue ) ;
178178
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 ;
184182
185- setCount ( nextCount ) ;
186- } ;
183+ if ( typeof max === "number" && nextCount > max ) {
184+ return c ;
185+ }
187186
188- const decrement = ( ) => {
189- const nextCount = count - 1 ;
190- if ( min && nextCount < min ) {
191- return ;
192- }
187+ return nextCount ;
188+ } ) ;
189+ } , [ max ] ) ;
193190
194- setCount ( nextCount ) ;
195- } ;
191+ const decrement = React . useCallback ( ( ) => {
192+ setCount ( ( c ) => {
193+ const nextCount = c - 1 ;
196194
197- const set = ( nextCount ) => {
198- if ( max && nextCount > max ) {
199- return ;
200- }
195+ if ( typeof min === "number" && nextCount < min ) {
196+ return c ;
197+ }
201198
202- if ( min && nextCount < min ) {
203- return ;
204- }
199+ return nextCount ;
200+ } ) ;
201+ } , [ min ] ) ;
205202
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+ }
209209
210- setCount ( nextCount ) ;
211- } ;
210+ if ( typeof min === "number" && nextCount < min ) {
211+ return c ;
212+ }
212213
213- const reset = ( ) => {
214- if ( count === startingValue ) {
215- return ;
216- }
214+ return nextCount ;
215+ } ) ;
216+ } ,
217+ [ max , min ]
218+ ) ;
217219
220+ const reset = React . useCallback ( ( ) => {
218221 setCount ( startingValue ) ;
219- } ;
222+ } , [ startingValue ] ) ;
220223
221224 return [
222225 count ,
0 commit comments