DEV Community

madhu
madhu

Posted on

React, when to use propTypes what are the best practices?

Oldest comments (3)

Collapse
 
stefandorresteijn profile image
Stefan Dorresteijn

It's a bit of a broad question but I have some input on using props in general. Here are the rules we've set for props when building React Components.

1. Any is wrong, unless it's not.
If a PropType is set to any, you're probably doing it wrong. Check if you can specify what the type really is. If not, add a comment specifying why that's not possible. In the code, always assume the type you're getting is the one you don't need. (Parse floats, check types, etc.)

2. Don't overshare.
Try to only pass the least amount of data you can. Instead of passing an entire object to a card, only pass the content you'll actually be using.

3. If a prop isn't required, set a default.
I think everyone does this because it's a pretty obvious one but we use the react/require-default-props eslint rule.

Besides requiring 100% coverage, we really don't have more rules than that. Hope it helps!

Collapse
 
floede profile image
Janus Hasseriis

Hi Stefan!

Sorry to necro this old reply :-)

I have a question about using isRequired.
If you have a prop that is required, do you leave it at that, or do you have any other fallbacks?

I'm thinking about:
1) Making sure the code doesn't break even if a required prop is not provided.
and / or
2) Having a part of or the whole component not render at all if the required prop is not provided.

I feel like you can argue that "isRequired" is the fallback.
But on the other hand, it's often nice to avoid breaking the application or having it render weird stuff.

A simple example would be a menu element where you'd probably set a text as required.

Collapse
 
stefandorresteijn profile image
Stefan Dorresteijn

I think it's nice not to break an app, but when a developer is misusing a component, the app should break. Otherwise it can be difficult to debug why the app doesn't work as expected. Check your values before rendering the component, then the component should be very dumb and just require certain props.