0

What's wrong with the code below?

export default function App() {
  const [count, setCount] = useState(0);

  return (
    <div className="App">
      <h2>{count}</h2>
      <button
        onClick={() => {
          setCount((count) => count + 1);
        }}
      >
        increase
      </button>
    </div>
  );
}

will using the arrow function in the event handler cause rerendering and affect performances?

Someone argued I should do this instead.

const [count, setCount] = useState(0);
  const increment = () => setCount((count) => count + 1);

  return (
    <div className="App">
      <h2>{count}</h2>
      <button onClick={increment}>increase</button>
    </div>
  );

To me it's just a matter of preference, it doesn't improve performance, am I right?

https://codesandbox.io/s/purple-breeze-8xuxnp?file=/src/App.js:393-618

1
  • If you really want to avoid redeclaring the function you could useCallback but no, given a single instance the two are the same — both redeclare a single function on each render. Commented Jan 27, 2023 at 1:13

1 Answer 1

1

React triggers a re-render when state changes, parent (or children) re-renders, context changes, and hooks changes. So in your example above, there's no difference to re-renders whether you extract the function or just simply type it in the html.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.