In React, how to memorize an inline function when using functional components?

Viewed 1496

The arrow functions have a performance issues, what should be the best approach to pass event and a parameter to event handler?

For example:

option 1:

 <div
    onClick={setPerson(name)}
 />

 const setPerson = (name) => (e: any): void => {
   setPerson(name)
   e.stopPropagation()
 }

option 2:

<div
  onClick={(e) => setPerson(null, name, e)}
/>

 const setPerson = (name, e): void => {
   setPerson(name)
   e.stopPropagation()
 }
1 Answers

If you want to prevent the child components from rerendering because of a prop that gets a new function, you can memoize it like:

const memoizedSetPerson = React.useCallback(() => { // add the parameters
 // do what you want here
}, [setPerson])

usage:

<div onClick={memoizedSetPerson} />


const memoizedSetPerson = React.useCallback((e) => {
     // e will be the event
}, [setPerson])

useCallback will return a memoized function so just use it like you would use any other function.

Related