What are the scenarios one should use isRequired for PropType vs defaultProps in React Application


I constantly struggle to understand, when exactly should I be using .isRequred vs .defaultProps={...} My thought is that, I think I should never ever really need to use isRequired, because it seems manually creating a bug that can break in the application because create isRequired automatically remove the need to add a corresponding default prop, that makes me feel uncomfortable just because it means I won't be able to expect a fail-safe value.

It definitely sounds an opinion based question, but I look for a better opinion that makes more sense if there is one.

Using prop types is a good way of documenting the API for a component, so that other people know how it works without reading the code.

The way it's usually thought of is the component is guaranteed to render without errors if all the required props are supplied. The props that are not required would only enhance the component with additional functionality.

Consider this example

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      {avatarUrl && <img src={avatarUrl} />}
    </div>
  );
}

UserCard.propTypes = {
  name: string.isRequired,
  avatarUrl: string
};

Now, if you want to render a default profile picture if it's not supplied, you could remove the conditional check inside the component and provide a default value instead.

function UserCard({ name, avatarUrl }) {
  return (
    <div>
      <p>{name}</p>
      <img src={avatarUrl} />
    </div>
  );
}

UserCard.propTypes = {
  name: string.isRequired,
  avatarUrl: string
};

UserCard.defaultProps = {
  avatarUrl: "/assets/generic-picture.png"
};