Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

194
Views
ReactJs - Why does calling onDelete() with parantheses without an arrow function not work?

Currently learning React, and I am confused as to why this acts the way it does. My App.JS:

import logo from './logo.svg';
import './App.css';
import Header from './components/Header'
import Tasks from './components/Tasks'
import {useState} from 'react'


function App() {
  let name = "Max";
  const [tasks, setTasks] = useState([
    {
        id: 1,
        text: 'Doctors Appointment',
        day: "Feb 5th at 2:30 pm",
        reminder: true,
    },
    {
        id: 2,
        text: "Meeting at School",
        day: "Feb 6th at 1:30pm",
        reminder: true,
    },
    {
        id: 3,
        text: "Food Shopping",
        day: "Feb 5th at 2:30pm",
        reminder: false,
    },
  ])
  const deleteTask = (id) => {
    alert("deleted " + id);
  }
  return (
    <div className="container">
      <Header />
      <Tasks tasks={tasks} onDelete = {deleteTask} />
    </div>
  );
}

export default App;

Tasks.JS basically just displays Task.js as h3s Task.js:

import {FaTimes} from 'react-icons/fa'

const Task = ({ task, onDelete }) => {
    return (
        <div className = "task">
            <h3>{task.text} <FaTimes style = {{color:'red', cursor:"pointer"}} onClick = {() => onDelete(task.id)}/></h3>
            <p>{task.day}</p>

        </div>
    )
}

export default Task

So I saw the arrow function for onClick = () => onDelete(task.id) and wondered why I couldn't just do onClick = onDelete(task.id) So I tried that and got some unexpected behavior. Basically, upon the page creation i got the alert that each item had been deleted thrice, and then afterwards nothing happened when I clicked it. Why does this happen? Like how do I explain this behavior? Why is this arrow function needed?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If you just use onClick = onDelete(task.id) it will call onDelete on every render of that component. You're passing the return from that function to onClick. By using the arrow function, you're passing the function itself, so that when a user clicks on your h3, it will then and only then call that function.

Note - not a great idea to put onClicks on elements like h3s for accessibility reasons.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!