13

On a react class I would write something like this

class Myclass extends React.Component {
  handleUpdate = info => {
    //do the update
  }

  render() {
    return (
      <SomeMarkup>
        <SomeComponent onUpdate={this.handleUpdate} />
      </SomeMarkup>
    )
  }
}

If using a function I could just write the following

function MyFunction() {
  function handleUpdate(info) {
    // do the update
  }
  return (
    <SomeMarkup>
      <SomeComponent onUpdate={handleUpdate} />
    </SomeMarkup>
  )
}

...but with that I'd be redeclaring a function on every render. Is there any sort of trick that would memoize the handler function between renders? Or should I just move the handler out of the render scope? (Moving it out of the render scope requires me that I explicitly pass more parameters since I wont directly have access to the function scope.)

wkrueger
  • 1,281
  • 11
  • 21
  • Use a arrow function i heard its better for the memory – o elhajoui Feb 28 '19 at 22:06
  • arrow function only changes the scope of `this`, which is irrelevant for "non-classes" – wkrueger Feb 28 '19 at 22:12
  • 4
    You are right, arrow functions are good for not binding every time. Back to your question, the only way to not recreate it every time is to pass it as a prop. It will use the function but not recreate it. That is the only way. – o elhajoui Feb 28 '19 at 22:15
  • is there a strong need here to avoid redeclaring the functions? any performance issue that's cropping up? – worc Mar 05 '19 at 23:20
  • performance issues related to big renders can easily show up when dealing with things like big controlled forms, where every keystroke may trigger 1 (or more) rerenders. – wkrueger Mar 07 '19 at 20:29

1 Answers1

8

This is exactly the scenario that useCallback is for. The function still gets declared every time with useCallback, but the function returned is memoized so that if it is passed as a property to children, the children will receive a consistent function unless it has to change due to dependencies changing.

Please see my recent related answer here that demonstrates in detail how useCallback works: Trouble with simple example of React Hooks useCallback

Here's another related answer: React Hooks useCallback causes child to re-render

Ryan Cogswell
  • 75,046
  • 9
  • 218
  • 198