r/reactjs • u/HeavenGin • Jun 10 '26
Discussion onClick and function call convention
Hi there,
With a colleague of mine we were triving to determine wether we should do one of the other of those snippets in our code . Those are voluntarily simplified.
const handleClick = (param: string) => {}
return <button onClick={() => handleClick(param)} />
const handleClick = (param: string) => () => {}
return <button onClick={handleClick(param)} /> I was more used to the first snippet so when I was reviewing his PR, I thought that the function will call itself during the rendering of the button.
Happy to know what's your opinion.
8
Upvotes
2
u/IkuraDon5972 Jun 11 '26
what’s your convention when there is no param?
32
u/DocumentFalse7879 Jun 10 '26
The most common pattern is:
<button onClick={() => handleClick(param)} />
Why confuse future/other engineers, seeing this instantly you know it’s ok. Seeing this: <button onClick={handleClick(param)} /> I instantly think there’s an issue.
More concisely I would probably do (if the func lives in the file w the param variable):
const handleClick = () => {someFunc(param)}
return <button onClick={handleClick} />
26
u/besthelloworld Jun 10 '26
Second one is literally just wrong unless
handleClickdoesn't actually handle the click but instead returns the click handler. If it does return a click handler, then it should be renamed tocreateClickHandler.18
u/Palcikaman Jun 10 '26
The second one is a war crime
5
u/rupesh_dev Jun 10 '26
First pattern is the way to go. The second one works but it trips up almost everyone reading it for the first time, that cognitive overhead is not worth the brevity.
If you want to clean it up further just define the handler inline with the param already in scope and pass it without the arrow wrapper:
const handleClick = () => someFunc(param)
return <button onClick={handleClick} />
Cleaner and no one has to think twice about it.
3
u/92smola Jun 10 '26
First one, no point in having a function returning a function just so you can use the second syntax
3
u/ferrybig Jun 10 '26
From the point of view of the React compiler, both work
From the point of view of code, prefer option 1, as it is more commonly used, so new developers to the project have an easier time learning it
2
u/dalce63 Jun 10 '26
the second one is atrocious. no. just no.
0
u/HeavenGin Jun 10 '26
Very glad to read that my way of doing it seems to mainly be the good one. It boosts my ego as I'm writing React since 6 years and a half. Still, I prefer to question implementation choices when I think I might be learning something 😁
0
u/j2ee-123 Jun 10 '26
Don’t overthink, the simpler - the better.
-6
u/Top_Bumblebee_7762 Jun 10 '26
I tend to use the second one as it looks cleaner but I'm also fine with the first one.