We use event handlers to respond when users click buttons or do other actions. Inline handlers are written directly inside the element, while function handlers are separate functions. Choosing between them helps keep code clear and efficient.
0
0
Inline vs function handlers in React
Introduction
When you want a quick action directly inside a button or element.
When the same action is used in many places and you want to reuse code.
When you want to keep your code clean and easy to read.
When you want to avoid creating a new function every time the component renders.
When you need to pass parameters to the event handler.
Syntax
React
/* Inline handler example */ <button onClick={() => alert('Clicked!')}>Click me</button> /* Function handler example */ function handleClick() { alert('Clicked!'); } <button onClick={handleClick}>Click me</button>
Inline handlers use arrow functions directly inside JSX.
Function handlers are defined separately and passed by name.
Examples
This uses an inline arrow function to show an alert when clicked.
React
<button onClick={() => alert('Hello!')}>Say Hello</button>This defines a separate function and uses it as the click handler.
React
function greet() { alert('Hello!'); } <button onClick={greet}>Say Hello</button>
Inline handler calls a function with a parameter.
React
function greet(name) { alert(`Hello, ${name}!`); } <button onClick={() => greet('Alice')}>Greet Alice</button>
Function handler defined as an arrow function outside JSX.
React
const handleClick = () => { console.log('Button clicked'); }; <button onClick={handleClick}>Log Click</button>
Sample Program
This React component shows two buttons that both add 1 to a counter. One uses an inline arrow function, the other uses a separate function. Both update the count state and show the new value.
React
import React, { useState } from 'react'; export default function InlineVsFunction() { const [count, setCount] = useState(0); // Function handler increments count function increment() { setCount(prevCount => prevCount + 1); } return ( <main> <h1>Count: {count}</h1> {/* Inline handler increments count by 1 */} <button onClick={() => setCount(prevCount => prevCount + 1)}>Inline +1</button> {/* Function handler increments count by 1 */} <button onClick={increment}>Function +1</button> </main> ); }
OutputSuccess
Important Notes
Inline handlers create a new function every render, which can affect performance if overused.
Function handlers help keep code organized and can be reused easily.
Use inline handlers for simple, quick actions; use function handlers for complex or repeated logic.
Summary
Inline handlers are quick and written inside JSX.
Function handlers are separate functions passed by name.
Choosing the right one helps keep your React code clean and efficient.