Skip to content
Advertisement

Using .bind() in functional React component, is it recommended?

I saw this syntax below during our code review, it’s my first time seeing it, I couldn’t find any article online of it being used/recommended – usually I would opt for arrow function or useCallback in this use case. Just curious if anyone else here used this, and if yes, would you be able to provide some references or an article saying it’s safe or recommended to use it.

function DummyComponent({ onBtnClick }) {
  const [data, setData] = useState('some-data-that-only-exists-here');

  return (
    <div>
      <button onClick={onBtnClick.bind(null, dummyData)} />
    </div>
  )
}

I was told that this prevents the function from being recreated on rerenders. Also, during writing of tests, it passes a class which seems to be the class of the HTML button as the 2nd argument when onBtnClick is triggered which is one of the reason why I didn’t approve of this and needed some references.

enter image description here

Advertisement

Answer

While it’s technically possible, the use of .bind or .call or .apply instead of an anonymous function is usually done to change the this inside the function. Here, you don’t care about this, so it’d probably make a bit more intuitive sense to read and write if you used an anonymous function instead.

<button onClick={() => onBtnClick(dummyData)} />

Or make a higher-order function outside, before returning the JSX:

const makeOnBtnClick = arg => () => onBtnClick(arg);
<button onClick={makeOnBtnClick(dummyData)} />

I was told that this prevents the function from being recreated on rerenders.

No, a new function is created every time the render part (with the .bind runs), so a new function gets attached as the click handler every time. If this is something you’re really worried about (which you probably shouldn’t be), useCallback would be one way to have a more persistent function that doesn’t have to be removed/recreated when rendering – just like you mentioned.

Advertisement