Popular Searches
Popular Course Categories
Popular Courses

Passing Functions Through Props

Passing Functions Through Props

Props in React

Passing Functions Through Props in React

Course: React JS Training

Topic: Passing Functions Through Props

Learning Objective: Understand how to pass functions from parent components to child components, execute callback functions through user interactions, pass arguments to functions, update parent component state, and build reusable interactive React components.


1. Introduction to Passing Functions Through Props

React uses props to pass data from a parent component to a child component. Props can contain strings, numbers, arrays, objects, and functions. Passing functions through props allows child components to trigger actions defined by their parent components.

For example, a parent component can define a function that displays a message and pass it to a child component. The child component can execute that function when a user clicks a button.

This technique is commonly used for button clicks, form submissions, deleting items, updating information, handling selections, and communicating user actions from child components to parent components.

Basic example

function Child({ onGreet }) {
  return (
    <button onClick={onGreet}>
      Say Hello
    </button>
  );
}
function App() {
  function greetUser() {
    alert("Hello from the parent component!");
  }
  return <Child onGreet={greetUser} />;
}
export default App;

How it works:

  • The parent component defines the greetUser function.
  • The parent passes the function to the child through the onGreet prop.
  • The child receives the function using {onGreet} destructuring.
  • When the user clicks the button, the child executes the received function.
  • The alert displays the message defined in the parent.

2. What Is a Function in JavaScript?

A function is a reusable block of code that performs a particular task. A function can accept parameters, execute instructions, and optionally return a value.

Functions help developers organize code, avoid repetition, and separate application logic into manageable parts.

Example of a regular function

function greet() {
  console.log("Hello, React!");
}
greet();

Output: Hello, React!

Example of a function with parameters

function greetUser(name) {
  console.log("Welcome, " + name);
}
greetUser("Amit");

Output: Welcome, Amit

Example of an arrow function

const greet = () => {
  console.log("Hello from an arrow function!");
};
greet();

In React, both regular functions and arrow functions can be passed through props. The appropriate choice depends on the code structure and requirements.


3. What Does Passing a Function Through Props Mean?

Passing a function through props means sending a function reference from one component to another component as a prop. The receiving component can call that function when necessary.

Unlike passing a string or number, a function prop allows the child component to trigger behavior that is defined elsewhere.

Example

function Button({ onClick }) {
  return (
    <button onClick={onClick}>
      Click Me
    </button>
  );
}
function App() {
  const handleClick = () => {
    alert("Button clicked!");
  };
  return <Button onClick={handleClick} />;
}
export default App;

Here, onClick is a prop that contains a function. The child component uses that function as the event handler for its button.

Important: The function is passed as a reference. It is not executed when the parent renders.


4. Understanding Parent and Child Components

In React, a parent component renders another component inside its JSX. The rendered component is called a child component.

Props generally flow from parent to child. A function defined in the parent can be passed to the child so that the child can request an action from the parent.

Example

function Child({ showMessage }) {
  return (
    <button onClick={showMessage}>
      Show Message
    </button>
  );
}
function Parent() {
  function displayMessage() {
    alert("This function belongs to Parent.");
  }
  return <Child showMessage={displayMessage} />;
}
export default Parent;

Parent component: Defines the displayMessage function and passes it to the child.

Child component: Receives the function through the showMessage prop and executes it when the button is clicked.

This pattern keeps the child component reusable because it does not need to know the exact implementation of the function it receives.


5. Passing a Function as a Prop

To pass a function through props, define the function and provide its name as a JSX expression using curly braces.

Syntax

<ChildComponent onAction={handleAction} />

In this syntax:

  • ChildComponent is the child component.
  • onAction is the name of the prop.
  • handleAction is the function defined by the parent.
  • The curly braces allow JSX to evaluate the JavaScript expression.

Complete example

function MessageButton({ onMessage }) {
  return (
    <button onClick={onMessage}>
      Display Message
    </button>
  );
}
function App() {
  function handleMessage() {
    alert("Welcome to React JS!");
  }
  return <MessageButton onMessage={handleMessage} />;
}
export default App;

When the button is clicked, React invokes the function passed through the onMessage prop.


6. Difference Between Passing and Calling a Function

One of the most important concepts in React is understanding the difference between passing a function reference and calling a function immediately.

Syntax Meaning Result
onClick={handleClick} Passes the function reference. The function runs when the event occurs.
onClick={handleClick()} Calls the function during rendering. The function executes immediately.
onClick={() => handleClick()} Passes a new function that calls the handler later. The handler runs when the event occurs.

Correct example

function App() {
  function handleClick() {
    alert("Button clicked!");
  }
  return <button onClick={handleClick}>Click Me</button>;
}

Incorrect example

function App() {
  function handleClick() {
    alert("This runs during rendering!");
  }
  return <button onClick={handleClick()}>Click Me</button>;
}

In the incorrect example, handleClick() is executed while React renders the component. Its return value is then passed to onClick, rather than the function itself.

Best practice: Use onClick={handleClick} when no additional arguments are required. Use an arrow function when you need to supply arguments or perform additional work at event time.


7. Passing Functions Using Arrow Functions

Arrow functions provide a concise way to define functions in JavaScript. They are frequently used in React to pass callback functions through props or define inline event handlers.

Example

function Button({ onClick }) {
  return <button onClick={onClick}>Click Here</button>;
}
function App() {
  const handleClick = () => {
    alert("Arrow function executed!");
  };
  return <Button onClick={() => handleClick()} />;
}
export default App;

The parent passes an arrow function to the child. When the button is clicked, the arrow function calls handleClick.

If no additional logic or arguments are needed, passing onClick={handleClick} directly is simpler and avoids creating an unnecessary wrapper function.

Inline arrow function example

function App() {
  return (
    <button onClick={() => alert("Hello!")}>
      Click Me
    </button>
  );
}
export default App;

This approach is convenient for short event handlers. For more complex behavior, defining a named handler can improve readability.


8. Passing Arguments to Functions Through Props

Sometimes a function needs additional information, such as a product ID, user name, item index, or message. An arrow function can pass these arguments when the user triggers an event.

Example: Passing a name

function GreetingButton({ onGreet }) {
  return (
    <button onClick={() => onGreet("Rahul")}>
      Greet Rahul
    </button>
  );
}
function App() {
  function greetUser(name) {
    alert("Hello, " + name + "!");
  }
  return <GreetingButton onGreet={greetUser} />;
}
export default App;

Output after clicking: Hello, Rahul!

The child invokes the callback with the argument "Rahul". The parent function receives that value through its name parameter.

Example: Passing a product ID

function Product({ id, name, onSelect }) {
  return (
    <button onClick={() => onSelect(id)}>
      Select {name}
    </button>
  );
}
function App() {
  function handleSelect(productId) {
    alert("Selected product ID: " + productId);
  }
  return (
    <Product
      id={101}
      name="Laptop"
      onSelect={handleSelect}
    />
  );
}
export default App;

When the button is clicked, the child passes the product ID to the parent function. The parent can use that ID to select a product, display its details, or perform another action.


9. Using Callback Functions to Communicate from Child to Parent

React's normal data flow sends props from parent to child. A callback function passed through props allows a child to notify the parent that an event occurred or provide information about that event.

This is sometimes described as child-to-parent communication, but the function itself is still passed from the parent to the child.

Example: Sending a message to the parent

function Child({ onSendMessage }) {
  function sendMessage() {
    onSendMessage("Hello from Child!");
  }
  return <button onClick={sendMessage}>Send Message</button>;
}
function App() {
  function handleMessage(message) {
    alert(message);
  }
  return <Child onSendMessage={handleMessage} />;
}
export default App;

The child calls the callback with a message. The parent receives the message as an argument and decides what to do with it.

Why is this useful?

  • It allows children to notify parents about user actions.
  • It keeps business logic in the component responsible for that logic.
  • It helps create reusable buttons, forms, lists, and modal components.
  • It avoids unnecessary duplication of event-handling code.

10. Passing Functions to Update Parent State

React state stores information that can change over time. A common use of function props is to allow a child component to trigger a state update managed by its parent.

The parent can define a callback that updates state and pass that callback to the child. When the child invokes it, the parent updates its state and React renders the updated UI.

Example: Counter component

import { useState } from "react";

function CounterButtons({ onIncrease, onDecrease }) {
  return (
    <div>
      <button onClick={onDecrease}>-</button>
      <button onClick={onIncrease}>+</button>
    </div>
  );
}
function App() {
  const [count, setCount] = useState(0);

  function increaseCount() {
    setCount(previousCount => previousCount + 1);
  }

  function decreaseCount() {
    setCount(previousCount => previousCount - 1);
  }

  return (
    <div>
      <h2>Count: {count}</h2>
      <CounterButtons
        onIncrease={increaseCount}
        onDecrease={decreaseCount}
      />
    </div>
  );
}
export default App;

How it works:

  1. The parent component creates a state variable called count.
  2. The parent defines functions to increase and decrease the count.
  3. Both functions are passed to CounterButtons.
  4. The child calls the appropriate function when a button is clicked.
  5. The parent updates its state and React renders the new count.

The functional state updater previousCount => previousCount + 1 calculates the next value from the previous state. This is useful when the next state depends on the current state.


11. Passing Multiple Functions Through Props

A child component can receive more than one function prop. This is useful when a component supports several actions, such as saving, cancelling, deleting, or editing an item.

Example: User action buttons

function UserActions({ onEdit, onDelete, onView }) {
  return (
    <div>
      <button onClick={onView}>View</button>
      <button onClick={onEdit}>Edit</button>
      <button onClick={onDelete}>Delete</button>
    </div>
  );
}
function App() {
  function handleView() {
    alert("Viewing user details");
  }
  function handleEdit() {
    alert("Editing user details");
  }
  function handleDelete() {
    alert("Deleting user");
  }
  return (
    <UserActions
      onView={handleView}
      onEdit={handleEdit}
      onDelete={handleDelete}
    />
  );
}
export default App;

Each callback performs a different task. The child component provides the user interface, while the parent determines the behavior associated with each action.


12. Naming Function Props

Function props can have any valid prop name. However, React developers commonly use names beginning with on followed by a capital letter to describe an event or interaction.

Prop name Typical purpose
onClick Handle a click interaction.
onSubmit Handle form submission.
onChange Handle a change in input or selection.
onDelete Request deletion of an item.
onSave Request saving data.
onSelect Handle selection of an item.
onAddToCart Request adding a product to a cart.

These names make the purpose of each callback clear. A custom prop such as onDelete is not automatically a browser event; it is an ordinary function prop that the child can call when appropriate.


13. Passing Functions to Reusable Components

One of the main advantages of function props is that they allow a component to be reused with different behavior. A reusable button can handle saving in one place and cancelling in another without needing separate button implementations.

Example: Reusable button

function ActionButton({ label, onAction }) {
  return (
    <button onClick={onAction}>
      {label}
    </button>
  );
}
function App() {
  function handleSave() {
    alert("Changes saved!");
  }
  function handleCancel() {
    alert("Action cancelled!");
  }
  return (
    <div>
      <ActionButton label="Save" onAction={handleSave} />
      <ActionButton label="Cancel" onAction={handleCancel} />
    </div>
  );
}
export default App;

The same ActionButton component is used twice. The label and callback determine the behavior for each instance.


14. Passing Functions with Array Items

When rendering a list of items, each item can receive a callback that identifies which item the user selected, edited, or deleted.

Example: Delete a task

function TaskItem({ task, onDelete }) {
  return (
    <li>
      {task.title}
      <button onClick={() => onDelete(task.id)}>
        Delete
      </button>
    </li>
  );
}
function TaskList({ tasks, onDeleteTask }) {
  return (
    <ul>
      {tasks.map(task => (
        <TaskItem
          key={task.id}
          task={task}
          onDelete={onDeleteTask}
        />
      ))}
    </ul>
  );
}
export default TaskList;

The TaskItem calls the function with the task ID. The parent component that owns the task data can use that ID to remove the corresponding task from state.

This pattern is widely used in todo applications, shopping carts, dashboards, and administrative interfaces.


15. Passing Functions to Handle Form Submission

Forms often use function props so a child form component can notify the parent when the user submits information.

Example: Reusable contact form

function ContactForm({ onSubmitContact }) {
  function handleSubmit(event) {
    event.preventDefault();
    onSubmitContact("[email protected]");
  }
  return (
    <form onSubmit={handleSubmit}>
      <button type="submit">Submit Form</button>
    </form>
  );
}
function App() {
  function handleContactSubmit(email) {
    alert("Submitted email: " + email);
  }
  return <ContactForm onSubmitContact={handleContactSubmit} />;
}
export default App;

In this example, preventDefault() stops the browser's default form submission behavior. The child then calls the parent callback with a value.

This is a simplified demonstration. In a real form, the email would usually come from the user's input, and the application would validate it before processing the submission.


16. Understanding the Event Object in Callback Functions

When a function is assigned directly to a React event handler, React passes an event object to that function when the event occurs. The object provides information about the interaction, such as the input value or the element involved.

Example: Passing the event to a parent callback

function TextInput({ onValueChange }) {
  return (
    <input
      type="text"
      onChange={onValueChange}
      placeholder="Enter your name"
    />
  );
}
function App() {
  function handleValueChange(event) {
    console.log(event.target.value);
  }
  return <TextInput onValueChange={handleValueChange} />;
}
export default App;

When the user types into the input, the child invokes the supplied function through the input's onChange event. The parent function reads the input value from the event object.

Example: Passing a specific value instead of the event

function SelectButton({ item, onSelect }) {
  return (
    <button onClick={() => onSelect(item)}>
      Select {item}
    </button>
  );
}
function App() {
  function handleSelect(selectedItem) {
    console.log("Selected:", selectedItem);
  }
  return (
    <SelectButton item="React JS" onSelect={handleSelect} />
  );
}
export default App;

In this version, the callback receives the specific item rather than the browser event. Choose the approach that matches what the parent needs to know.


17. Using Functions to Update Arrays in Parent State

A common use of function props is allowing a child component to request an update to an array stored in the parent's state.

Example: Adding a task

import { useState } from "react";

function AddTaskButton({ onAddTask }) {
  return (
    <button onClick={() => onAddTask("New Task")}>
      Add Task
    </button>
  );
}
function App() {
  const [tasks, setTasks] = useState(["Learn React"]);

  function addTask(taskTitle) {
    setTasks(previousTasks => [...previousTasks, taskTitle]);
  }

  return (
    <div>
      <AddTaskButton onAddTask={addTask} />
      <ul>
        {tasks.map((task, index) => (
          <li key={`${task}-${index}`}>{task}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

The child calls onAddTask with a task title. The parent creates a new array using the spread operator and updates state. React then renders the updated task list.

For applications where task titles may repeat or items can be reordered or deleted, assign each task a stable unique ID and use that ID as the key.


18. Common Mistakes When Passing Functions Through Props

Mistake 1: Calling the function instead of passing it

// Incorrect for a click handler:
<button onClick={handleClick()}>Click</button>

// Correct:
<button onClick={handleClick}>Click</button>

The incorrect version executes the function during rendering instead of waiting for the click.

Mistake 2: Forgetting to pass the callback prop

function Child({ onSave }) {
  return <button onClick={onSave}>Save</button>;
}

// Parent should provide the callback:
<Child onSave={handleSave} />

If the parent does not provide the callback, the child must account for that possibility if the prop is optional.

Mistake 3: Using an undefined function name

// Incorrect if handleDelete has not been defined:
<Child onDelete={handleDelete} />

Make sure the referenced function exists in the current scope or is imported before passing it to a component.

Mistake 4: Forgetting to pass arguments through a wrapper

// Correct when an argument is required:
<button onClick={() => onDelete(item.id)}>
  Delete
</button>

This ensures the callback receives the item's ID when the button is clicked, rather than calling the function immediately during rendering.

Mistake 5: Assuming a callback automatically updates the UI

A callback only performs the behavior defined by its implementation. To update React's rendered UI, it usually needs to update state or trigger another mechanism that causes a render.

Mistake 6: Mutating state directly inside a callback

// Avoid mutating the existing state array:
tasks.push("New Task");

// Prefer creating a new array:
setTasks(previousTasks => [...previousTasks, "New Task"]);

Immutable updates help React recognize state changes and keep rendering behavior predictable.


19. Best Practices for Passing Functions Through Props

  • Use meaningful callback names such as onSave, onDelete, and onSelect.
  • Pass function references instead of calling functions during rendering.
  • Use arrow functions when arguments need to be supplied at event time.
  • Keep reusable child components focused on their UI and interaction interface.
  • Keep application-specific behavior in the parent when the parent owns the relevant data.
  • Use state updates to change information that affects the rendered UI.
  • Use functional state updates when the next state depends on the previous state.
  • Validate callback arguments when they come from user input or external data.
  • Use real HTML buttons for button actions to support keyboard accessibility.
  • For optional callbacks, check that a function exists before calling it, or define the prop as required by your component's design.
  • Use useCallback only when stable function identity is useful for a specific optimization or dependency requirement; it is not required for every callback.
  • Keep function props and their responsibilities clear so components remain easy to test and maintain.

20. Practical Project: Product Management with Function Props

Project Objective: Create a product list in which a child component can send a product ID to the parent when the user clicks a button. The parent will display the selected product and allow the user to remove products.

App.jsx

import { useState } from "react";

function ProductCard({ product, onSelect, onDelete }) {
  return (
    <article className="product-card">
      <h2>{product.name}</h2>
      <p>Price: ₹{product.price}</p>
      <button onClick={() => onSelect(product.id)}>
        Select
      </button>
      <button onClick={() => onDelete(product.id)}>
        Delete
      </button>
    </article>
  );
}
export default function App() {
  const [products, setProducts] = useState([
    { id: 1, name: "Keyboard", price: 1200 },
    { id: 2, name: "Mouse", price: 650 },
    { id: 3, name: "Monitor", price: 8500 }
  ]);
  const [selectedProduct, setSelectedProduct] = useState(null);

  function handleSelect(productId) {
    const product = products.find(item => item.id === productId);
    setSelectedProduct(product ?? null);
  }

  function handleDelete(productId) {
    setProducts(previousProducts =>
      previousProducts.filter(item => item.id !== productId)
    );
    setSelectedProduct(previousSelected =>
      previousSelected?.id === productId ? null : previousSelected
    );
  }

  return (
    <main>
      <h1>Product Management</h1>
      {selectedProduct && (
        <p>Selected Product: {selectedProduct.name}</p>
      )}
      <div className="product-list">
        {products.map(product => (
          <ProductCard
            key={product.id}
            product={product}
            onSelect={handleSelect}
            onDelete={handleDelete}
          />
        ))}
      </div>
      {products.length === 0 && <p>No products available.</p>}
    </main>
  );
}

App.css

body {
  margin: 0;
  padding: 24px;
  font-family: Arial, sans-serif;
  background: #f4f6f8;
}
.product-list {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}
.product-card {
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background: white;
}
.product-card button {
  margin-right: 8px;
  padding: 8px 12px;
  cursor: pointer;
}

How the project works

  1. The parent stores the product list and selected product in state.
  2. Each product card receives one product object and two callback functions.
  3. Clicking Select calls onSelect with the product ID.
  4. The parent finds the matching product and updates the selected product.
  5. Clicking Delete calls onDelete with the product ID.
  6. The parent filters the product out of its state array.
  7. React updates the product list and selection message.

Project learning outcomes

  • Pass multiple functions through props.
  • Send arguments from child components to parent functions.
  • Use callbacks to update parent state.
  • Update arrays immutably.
  • Build reusable interactive components.
  • Use stable keys when rendering lists.

21. Practice Exercises

  1. Create a child button that receives an onClick function from its parent.
  2. Pass a greeting function through props and display a message when clicked.
  3. Create a reusable button that accepts both a label and a callback.
  4. Pass a user's name as an argument to a parent callback.
  5. Create two buttons that receive different callback functions.
  6. Build a counter with separate increase and decrease callbacks.
  7. Create a form child component that passes submitted information to the parent.
  8. Build a product list with a callback for selecting a product by ID.
  9. Create a todo list that passes a task ID to a delete callback.
  10. Update a parent-owned array when a child button is clicked.

22. Interview Questions and Answers

Q1. What does passing functions through props mean?

Answer: It means passing a function reference from one component to another using props so that the receiving component can call it when needed.

Q2. Why do we pass functions as props in React?

Answer: Function props allow child components to trigger actions defined by a parent, report user interactions, and request changes to data managed by the parent.

Q3. What is a callback function?

Answer: A callback is a function passed to another function or component so that it can be invoked at an appropriate time.

Q4. What is the difference between onClick={handleClick} and onClick={handleClick()}?

Answer: The first passes a function reference to be called when the click occurs. The second calls the function immediately during rendering and passes its return value.

Q5. How can a child component send data to a parent?

Answer: The parent passes a callback function to the child. The child invokes it with the required data as an argument.

Q6. Can a component receive multiple function props?

Answer: Yes. A component can receive callbacks such as onSave, onDelete, and onCancel.

Q7. How do you pass an argument to a function when a button is clicked?

Answer: Wrap the function call in an arrow function, such as onClick={() => handleDelete(item.id)}.

Q8. How do callback functions help update React state?

Answer: A parent can pass a callback that calls a state setter. When the child invokes the callback, the parent updates its state and React renders the updated UI.

Q9. Are custom callback props required to start with on?

Answer: No. Any valid prop name can be used, but names such as onSave and onDelete are common conventions because they clearly describe interactions.

Q10. When should useCallback be used?

Answer: useCallback can preserve a function's identity between renders when that stability is useful for memoized child components or hook dependencies. It is not necessary for every function prop.


23. Quick Revision Checklist

  • Understand how functions can be passed as props.
  • Know the difference between a function reference and a function call.
  • Define callback functions in a parent component.
  • Receive callback props in child components.
  • Execute callbacks in response to user interactions.
  • Pass arguments to callbacks using arrow functions.
  • Use callbacks for parent-child communication.
  • Update parent state through callback functions.
  • Keep array and object state updates immutable.
  • Use clear callback names and accessible HTML controls.

24. Conclusion

Passing functions through props is an essential React concept for building interactive and reusable components. A parent component can define a function and pass it to a child, allowing the child to trigger an action or send information back to the parent through a callback.

This approach is useful for buttons, forms, counters, product lists, task management, and many other application features. By learning to pass function references correctly, supply arguments, and update state through callbacks, you can create React applications with clear data flow and maintainable component structures.


25. React JS Training Resources

Explore the following course and learning resources:

Previous Next
whatsapp