Home > Software engineering >  Need to understand inline function call with react FC
Need to understand inline function call with react FC

Time:03-02

Im quite new to React and have created a new view at my company. I use inline functions because many guides do the same. Everything is written as function components.

I write onClick like this:

onClick: () => onBackClick()

My co-workes says this is a usless arrow function.

Will try to give you the whole picture. Parent component has the onBackClick function declared

const Parent = () => {
     const onBackClick = () => {backOff}
    
          <Child {...{onBackClick}}/>

}

const Child = ({onBackClick}) => {
 return (
   <MyButton {...{onClick: () => onBackClick() }}/>
)

}

My co-workers want me to write it like this:

onClick: onBackClick

I dont get a good explanation on why and really would like to learn. Can someone be kind to explain why this is a better way to write it.

Regards.

CodePudding user response:

Compare:

const onBackClick = () => { console.log("This does something useful"); };

const onClick = onBackClick;

onClick();

const onBackClick = () => { console.log("This does something useful"); };

const onClick = () => onBackClick();

onClick();

In the first example (your co-worker's way) there is one function and it is passed around.

In the second example (your way) you create a whole new function that does nothing except call the first function.


Aside from being redundant, this creates an extra inefficiency in React.

When the component is re-rendered, the output is checked for changes.

onBackClick might not have changed, but (when using your way) onClick has, so React will delete the old event handler from the DOM and assign a new one with the new (but identical) onClick function you created.

  • Related