DEV Community

HidetoshiYanagisawa
HidetoshiYanagisawa

Posted on

Understanding and Proper Usage of 'on' and 'handle' Prefixes in React Function Naming

React developers often come across functions with prefixes 'on' and 'handle'. However, it may be a little confusing as to why these prefixes are used and how to properly use them. In this article, I'll explain what these prefixes mean and how you should use them.

Understanding 'on' and 'handle'

Firstly, let's start with the basics. Generally, function names starting with 'on' indicate that they fire when an event occurs. On the other hand, function names starting with 'handle' indicate that they perform a specific action.

For instance, React's onClick event handler is a function that fires when a click event occurs. Look at the example below.

<button onClick={handleClick}>Click me</button>
Enter fullscreen mode Exit fullscreen mode

In this example, when the button is clicked, the 'handleClick' function fires.

Creating an Event Handler

So, how do we create a 'handle' prefixed function, i.e., an event handler? Let's look at it below.

function ExampleComponent() {
  const handleClick = () => {
    console.log("Button clicked");
  };

  return (
    <button onClick={handleClick}>Click me</button>
  );
}
Enter fullscreen mode Exit fullscreen mode

Here, we define a function 'handleClick', and we assign this function to the button's onClick event handler. The 'handleClick' function fires when the button is clicked.

Proper Usage of 'on' and 'handle'

Finally, let's talk about when to use 'on' and 'handle'.

  • 'on' is used for functions that trigger some action when a specific event occurs.
  • 'handle' is used for functions that describe what exactly to do when an event occurs.

Let's see a concrete example.

class ExampleComponent extends React.Component {
  handleClick = () => {
    console.log("Button clicked");
  };

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

Here, the 'handleClick' function defines the specific action for the button's click event. It's passed to the button as 'onClick' and is called when the click event occurs.

That's the basic and proper usage of 'on' and 'handle' in React function naming. Using them properly improves the readability of your code and makes it easier for other developers to understand.

Happy coding!

Top comments (0)