8

What is the best practice defining a function defaultProps that is empty in ReactJS?

My solution so far is either an empty arrow function or a null value. Which way would be better?

MyComponent.defaultProps = {
  onClick: () => {},
  onClickNull: null,
};
3
  • 1
    I think this depends on the situation whether "null" could mean something in your code. "null" means having no data, so if your code has a logic that handles differently whether onClick is defined or not, then null else use the null object pattern by declaring () => {}. Commented Jan 3, 2019 at 16:09
  • 2
    It's entirely up to you. If you want your code to know whether the function was provided, use null or undefined or leave the property off the defaults. If you don't need your code to know and want to be able to use it without any checks, use the no-op function. (I usually create a single no-op function I reuse, although with modern engines I guess there's really no good reason for that...) Commented Jan 3, 2019 at 16:10
  • The "no-op" term seems new to me. Thank you for your answer and the new dev term I gained @T.J.Crowder :p Commented Jan 3, 2019 at 16:54

2 Answers 2

6

I don't think there is a right answer for this.

If you want to be more explicit in your code, go with the null and check if the function is null before calling it.

If you want to have less code, go with empty function.

The more important thing I would say, is to be consistent in the entire project.

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

2 Comments

My main concern was the possibility of performance issues using an empty function. However, your point of view helped me clarify it, thanks @Anas !!
How is having an empty function a performance issue?
5

Important thing to keep in mind is that an empty function ()=>{} is an object hence its truthy whereas null and undefined are falsy.

So if you want to check whether that event handler prop is passed on implementation and handle both cases (supplied and not supplied) differently, it makes more sense to go with null or undefined.

1 Comment

I faced this issue the other day, thanks for bringing it up!

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.