2

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?

1
  • 1
    The con is simple; you now have a null, and you have to check for it before doing anything with it, or things blow up. Are there reasons? Sure, but it all boils down to the null-object holy wars, and what your own point of view is. Commented Jun 19, 2018 at 20:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Based off that tweet, what do you think is a good approach to props that aren't required for functions and objects?
Just curious, so there's no "big" difference in either setting these to empty functions/objects or null unless for maybe checking truthy/falsy. (This also includes ensuring it doesn't blow up the code like in your example of person.cars)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.