Posts

Showing posts from November, 2024

Passing array from child to parent component

 To pass the assigned_users array from a child component to its parent component, you need to follow these steps: Create a callback function in the parent component : This function will be responsible for receiving the assigned_users array. Pass the callback function to the child component as a prop : The child component can then call this function when it wants to send the assigned_users array to the parent. Call the callback function from the child component : Inside the child component, when you want to send the data to the parent (e.g., after updating assigned_users ), you call the callback function with the updated array. Parent Component jsx Copy code import React , { useState } from 'react' ; import ChildComponent from './ChildComponent' ; const ParentComponent = ( ) => { const [assignedUsers, setAssignedUsers] = useState ([]); // Callback function to update the parent state const handleAssignedUsersChange = ( users ) => { setAssig

useCallback hook in React

`useCallback` is a useful hook for optimizing performance in React applications by preventing unnecessary re-creations of functions. However, you should use it wisely, as it can add complexity and may not always offer a performance improvement in every case. ### 1. **What does `useCallback` do?** `useCallback` returns a memoized version of the callback function that only changes if one of the dependencies has changed. It’s primarily used when passing a function as a prop to child components or using it in an effect (like `useEffect`), where unnecessary re-creations of the function can lead to performance problems. ### 2. **Syntax:** ```javascript const memoizedCallback = useCallback(() => {   // Your callback code }, [dependencies]); ``` - The first argument is the function you want to memoize. - The second argument is an array of dependencies (like `useEffect`). The function will only be re-created if any of these dependencies change. ### 3. **When to use `useCallback`?** You shoul