Reputation: 175
When setting default props for values such as objects or functions, is there a reason why we would ever want to use null as a default prop instead of lets say, an empty function or empty object? Are there any pros and cons.
For example, instead of doing something like
static defaultProps = {
onClick: null,
person: null
};
vs
static defaultProps = {
onClick: () => {},
person: {},
};
What's the reasoning behind setting null as a default or is that a bad practice?
Upvotes: 2
Views: 4714
Reputation: 6253
Setting null or an empty object for a required prop can be considered a bit of a bad practice. If the prop is required, but has a default value, there is nothing actually enforcing it to be required at this point. See this tweet from Cory House for more about this.
Now if the prop is not required, and you want to add a default prop, I can make the argument that null is easier to work with than empty object because an empty object is still truthy which makes for slightly more verbose if checks, whereas null is falsey, making for for more concise if checks.
UPDATE BASED ON COMMENT:
better than having an empty object or null, might be to actually have data that represents the real thing. For example if I have a prop that looks like this.
const person = {
cars: []
}
I would not want to set person as an empty object or null by default, since indexing in to person.cars
will cause me to blow up, but if the shape is there, I can be sure I wont blow up even when the data isn't there yet.
Upvotes: 1
Reputation: 167
suppose you have a logic that some view will be visible if you get props from parent. If you don't receive any props then props value will be default. so your logic might not work properly in that situation.
Upvotes: 0