Search code examples
reactjsfunctioncomponents

Difference between () => someFunc and someFunc


I have a react component

import React from 'react';

function App() {

  const someFunc = () => {
    console.log('clicked');
  }

  return (
    <div >
      <button onClick = {() => someFunc}>Button 1</button>
      <button onClick = {someFunc}>Button 2</button>
    </div>
  );
}

export default App;

What is the difference between callings onClick = {() => someFunc} and onClick = {someFunc} . Thanks in advance for helping.


Solution

  • onClick = {() => someFunc}
    

    This is just returning the reference to someFunc when the onClick handler will run. This will not do anything (will not work how you expect).

    onClick = {someFunc}
    

    This is passing a direct reference to someFunction which will get called when the onClick handler is called. You can think of putting someFnnction's body here as it is like this

    onClick = {() => {
        console.log('clicked');
      }}