Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a function with arguments as prop in React without creating an arrow function

I have a function

doSomething = (id) => {
  console.log(id) 
}

I want to call this function inside onPress. I know one way to do this is by using another arrow function inside onPress like this:

<Text onPress={() => this.doSomething(id)}>Do Some Work</Text>

But then a new function is created in every re-render and decreases peformance which can be avoided by calling functions like this onPress={this.doSomething} only when there is no argument to be passed. Is a similar thing possible with arguments so that I can improve the performance of my app

like image 711
Sounak Biswas Avatar asked Sep 11 '25 15:09

Sounak Biswas


1 Answers

You are absolutely right, arrow function creates a new function every time, that's why React's shallow equal props comparison returns false.

You could use useCallback hook to create a momoized callback. So, I believe you have the id variable in your render function.

const doSomething = useCallback((e) => {
  console.log(id)
}, [id])


<Text onPress={doSomething} />

Memoized doSomething function will be changed every time when the id variable is changed.

However, by default if the parent component updates then every child will be updated as well. Unless it has memo wrapper, or shouldComponentUpdate life-cycle hook defined.

You can read a bit more about memoization in context of React components in a great article written by Dan Abramov.

UPD

If you are using a class component then you could return a momized function from the class method.

class Component extends React.Component {
 
  // I used Lodash memoize for example

  doSomething = _.memoize((id) => {
    return function (e) {
      console.log(id)
    }
  })

  render () {
    return (
      <Text onPress={doSomething(id)} />
    )
  }
}

like image 136
Ivan Burnaev Avatar answered Sep 14 '25 05:09

Ivan Burnaev