React: How can I make this React Component written better to be more efficient? I feel like I'm repeating code and it could be refactored much better. The maxValue
prop is optional
ButtonStepper.tsx (Updated):
// TypeScript Type: Propsinterface IProps { onChange: (value: number) => void; minValue?: number; maxValue?: number; stepValue?: number;}// Component: Button (Stepper)const ButtonStepper = ({ onChange, minValue, maxValue, stepValue }: IProps): JSX.Element => { // React Hooks: State const [value, setValue] = useState<number>(0); // React Hooks: Lifecycle Methods useEffect(() => { onChange(value); }, [onChange, value]); // On Increment const onIncrement = (): void => { if (maxValue && maxValue <= value) { if (stepValue) { setValue((prevState) => prevState + stepValue); } else { setValue((prevState) => prevState + 1); } } else { if (stepValue) { setValue((prevState) => prevState + stepValue); } else { setValue((prevState) => prevState + 1); } } };
tonStepper.tsx:**
// TypeScript Type: Propsinterface IProps { onChange: (value: number) => void; minValue?: number; maxValue?: number; stepValue?: number;}// Component: Button (Stepper)const ButtonStepper = ({ onChange, minValue, maxValue, stepValue }: IProps): JSX.Element => { // React Hooks: State const [value, setValue] = useState<number>(0); // React Hooks: Lifecycle Methods useEffect(() => { onChange(value); }, [onChange, value]); // On Increment const onIncrement = (): void => { if (maxValue) { if (maxValue <= value) { if (stepValue) { setValue((prevState) => prevState + stepValue); } else { setValue((prevState) => prevState + 1); } } } else { if (stepValue) { setValue((prevState) => prevState + stepValue); } else { setValue((prevState) => prevState + 1); } } };