Consider a React component that uses an inline arrow function as an event handler inside JSX. What is the main behavior difference compared to using a named function handler?
function Button() { const [count, setCount] = React.useState(0); return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>; }
Think about how JavaScript functions behave inside JSX when the component re-renders.
Inline arrow functions inside JSX create a new function every time the component renders. This can cause child components receiving these functions as props to re-render unnecessarily because the prop reference changes.
Given a React class component, which option correctly binds the handleClick method to the component instance?
class MyButton extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; // Binding happens here } handleClick() { this.setState({ count: this.state.count + 1 }); } render() { return <button onClick={this.handleClick}>Clicked {this.state.count} times</button>; } }
Remember how JavaScript class methods lose this context unless bound.
In class components, methods need to be bound to the instance to keep the correct this context. Binding in the constructor with this.handleClick = this.handleClick.bind(this); is the standard approach.
Examine this React functional component. What will be displayed after clicking the button twice?
function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(count + 1)}> Count: {count} </button> ); }
Consider how state updates work with the current state value inside the inline function.
Each click calls setCount(count + 1) with the current count value. After two clicks, the count increments twice, showing 2.
Look at this React functional component. It causes an infinite re-render loop. Why?
function Timer() { const [seconds, setSeconds] = React.useState(0); React.useEffect(() => { const id = setInterval(() => setSeconds(seconds + 1), 1000); return () => clearInterval(id); }, [() => setSeconds(seconds + 1)]); return <div>Seconds: {seconds}</div>; }
Think about how React compares dependencies in useEffect.
Functions are objects in JavaScript and a new inline arrow function is created on every render. This makes the dependency array change every time, causing useEffect to run infinitely.
Which reason best explains why using named function handlers is often better than inline handlers in React?
Think about how React uses props to decide when to re-render components.
Named handlers keep the same function reference between renders, which helps React avoid unnecessary re-renders of child components that receive these handlers as props.