Skip to content

refactor(useCounter): Extract validateValue function and optimize performance #259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 15 additions & 19 deletions src/hooks/useCounter/useCounter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ type UseCounterReturn = {
setCount: (value: number | ((prev: number) => number)) => void;
};

const validateValue = (value: number, { min, max }: Omit<UseCounterOptions, 'step'>): number => {
if (min !== undefined && value < min) {
return min;
}

if (max !== undefined && value > max) {
return max;
}

return value;
};

/**
* @description
* `useCounter` is a React hook that manages a numeric counter state with increment, decrement, and reset capabilities.
Expand Down Expand Up @@ -52,33 +64,17 @@ type UseCounterReturn = {
* }
*/
export function useCounter(initialValue = 0, { min, max, step = 1 }: UseCounterOptions = {}): UseCounterReturn {
const validateValue = (value: number): number => {
let validatedValue = value;

if (min !== undefined && validatedValue < min) {
validatedValue = min;
}

if (max !== undefined && validatedValue > max) {
validatedValue = max;
}

return validatedValue;
};

const [count, setCountState] = useState<number>(() => validateValue(initialValue));

const validateValueMemoized = useCallback(validateValue, [min, max]);
const [count, setCountState] = useState<number>(() => validateValue(initialValue, { min, max }));

const setCount = useCallback(
(value: number | ((prev: number) => number)) => {
setCountState(prev => {
const nextValue = typeof value === 'function' ? value(prev) : value;

return validateValueMemoized(nextValue);
return validateValue(nextValue, { min, max });
});
},
[validateValueMemoized]
[min, max]
);

const increment = useCallback(() => {
Expand Down
Loading