In this article, we will discuss the correct use of arrow functions in reactJS.

Arrow functions have become a popular way of defining functions in JavaScript and these functions can be used in various ways to define component methods and callbacks.

In class components, component methods are defined as instance methods, whereas in function components, they are defined as regular functions.

Arrow functions in react class based component:

class MyComponent extends React.Component {
  handleClick = () => {
    console.log(this.props);
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}

In the above example, handleClick is defined as an arrow function. Here, this is bound to the instance of MyComponent when the function is called.

It it is a regular function, this would be undefined when handleClick is called response to a click event.

Arrow functions in react functional based components

In functional components, arrow functions are used to define the component methods.In functional components we don’t need to worry about binding this because functional components doesn’t have instances.

function MyComponent(props) {
  const handleClick = () => {
    console.log(props);
  };

  return (
    <button onClick={handleClick}>Click me</button>
  );
}

In the above example, handleClick is defined as an arrow function which is called when the button is clicked. As the MyComponent is a function component, we don’t need to worry about binding this.

Arrow functions in React callbacks

In React, it’s common to define callbacks as arrow functions to ensure that they are re-rendered only when their dependencies change. Callbacks are functions that are passed as props to child components, and are called when certain events occur. These are often used to update state, trigger side effects, or pass data between components.

function ParentComponent() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <ChildComponent onClick={handleClick} />
  );
}

function ChildComponent({ onClick }) {
  return (
    <button onClick={onClick}>Click me</button>
  );
}

Explanation:

In the above example, handleClick is defined as an arrow function, which is passed as a prop to ChildComponent. handleClick references count, which is a state variable defined in ParentComponent, handleClick needs to be re-rendered when count changes.

By using an arrow function, we make sure that every time ParentComponent is re-rendered, a new function is created. This makes sure that handleClick has access to the most recent value of count..

Categorized in:

Tagged in: