4

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

2
  • It is not possible to do something similar with an argument. But unless you have like 10000 of them at each re-render, I don't think the performance difference would be perceived... Commented Aug 20, 2020 at 15:43
  • i don't think so, since the function is called with the event object as a parameter Commented Aug 20, 2020 at 15:44

1 Answer 1

2

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)} />
    )
  }
}

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

2 Comments

I am using a class component not a function component. This id variable is only available in render() scope so it means this function also should be in same scope ?
Updated my answer. The main idea to use memoized wrapper around your function. It could be anything: _.memoize or even custom implementation (it's really simple). Don't forget to use PureComponent for your <Text /> or to define custom logic in shouldComponentUpdate

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.