Today I Learned

React code-smells: Passing unnecessary props

Component receiving many props might suggest something is wrong.

In this case MyComponent receives many props used only to calculate another values.

function MyComponent({ value, format, isVisible, color, height, width }) {
  const displayValue = useMemo(() => {
    if (!isVisible) return "";
    if (!value) return "";

    value.transform(format);
  }, [isVisible, value, format]);

  return (
    <div style={{ color, height, width }}>Some content and {displayValue}</div>
  );
}

function MyParentComponent() {
  // value, format, isVisible, color, height, width come from state or somewhere else

  return (
    <div>
      <h2>Here will be my component</h2>
      <MyComponent
        value={value}
        format={format}
        isVisible={isVisible}
        color={color}
        height={height}
        width={width}
      />
    </div>
  );
}

In such cases we could simplify the component by calculating the values in parent or additional wrapper component and pass only that.

function MyComponent({ style, displayValue }) {
  return <div style={style}>Some content and {displayValue}</div>;
}

function MyParentComponent() {
  // value, format, isVisible, color, height, width come from state or somewhere else

  const style = useMemo(
    () => ({ color, height, width }), 
    [color, height, width]
  );

  const displayValue = useMemo(() => {
    if (!isVisible) return "";
    if (!value) return "";

    value.transform(format);
  }, [isVisible, value, format]);

  return (
    <div>
      Here will be my component
      <MyComponent style={style} displayValue={displayValue} />
    </div>
  );
}