I was working on a react project and came accross this situation.
Is it okay to set an empty arrow function to a variable while destructuring in javascript.
Are there any cons if done like this ?
const { onClick = () => {} } = props;
I was working on a react project and came accross this situation.
Is it okay to set an empty arrow function to a variable while destructuring in javascript.
Are there any cons if done like this ?
const { onClick = () => {} } = props;
2
Answers
Doing this will assign the empty function to onClick if there if props does not have an onClick key. So while this is a legal method to have a default value for a prop key which might not be guaranteed to exist, the cons of doing this will have to be evaluated by you in the context of your app.
In general that’s okay, if you really want
onClick
to be a do-nothing function when it either doesn’t exist onprops
or it has the valueundefined
. Specifically in the context of a React component, though:onClick
to afterward will expect that it may getundefined
for the function prop, so there’s not much point in defaulting it.onClick
to will see it as a new value and have to re-render, even if it’s memoized and could avoid re-rendering ifonClick
hadn’t changed. In that case, again,undefined
would be the better choice, since it would avoid unnecessary re-renders.Here’s a simple example showing the effect of the unstable function reference on a memoized component:
Notice how "Button 2" renders every time you click
+
, but "Button 1" doesn’t. That’s because "Button 2" getsonClick2
which we’re defaulting to() => {}
, but "Button 1" getsonClick1
which we’re leaving asundefined
.My other answer here has more about how/why unstable function references cause unnecessary re-rendering of memoized components.