Search code examples
reactjstypescriptreact-nativecomponents

How can I make this React Component written better to be more efficient?


How can I make this React Component written better to be more efficient? I feel like I'm repeating code in onIncrement and it could be refactored much better. The maxValue prop is optional

ButtonStepper.tsx:

// TypeScript Type: Props
interface 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);
      }
    }
  };

Solution

  • Make sure to add the default values in your props destructuring.

    // Component: Button (Stepper)
    const ButtonStepper = ({ onChange, minValue, maxValue = Number.MAX_VALUE, stepValue = 1 }: 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 > value + stepValue) {
           setValue(value + stepValue);
        }
      };