useCallback is a React hook that is used to memoize functions in functional components.
It is particularly useful when we want to prevent unnecessary re-creations of functions, especially when passing functions as props to child components.
It prevents a function from creating new references every time a component re-renders.
By preventing unnecessary re-renders, `useCallback` hook can lead to smoother UI transitions and interactions, improving the overall user experience.
The `useCallback` hook function promotes cleaner code and makes the component behaviour more predictable.
The primary use case for "useCallback" is to optimize performance in situations where a function is passed down to child components, and we want to avoid unnecessary re-renders of those child components when the parent component re-renders.
import React, { useCallback } from 'react'; const YourComponent = () => { // Declaring useCallback Function const handleClick = useCallback(() => { // add logic statement }, [dependency value]); return ( <div></div> ); }; export default YourComponent;
import React, { useState, useCallback } from 'react'; import ChildComponent from "./ChildComponent.jsx"; const YourComponent = () => { const [count, setCount] = useState(0); // Without useCallback: Each render creates a new handleClick function // const handleClick = () => { // console.log('Button clicked!'); // }; // With useCallback: Function is memoized, only changes if dependencies (count) change const handleClick = useCallback(() => { // When we click from child component handleClick function will get called, // but it will not update head count value // because we are updating the head count from parent component button console.log('Button clicked! Current count:', count); }, [count]); return ( <div> <p>Count: {count}</p> {/** onClick function will trigger handleClick function, it will update head count, and count is dependency of useCallback function of handleClick */} <button onClick={() => setCount(count + 1)}>Increment</button> <ChildComponent onClick={handleClick} /> </div> ); }; export default YourComponent;
Without "useCallback", the handleClick function would be recreated on every render of `YourComponent`.
This could lead to unnecessary re-renders of `ChildComponent` since it would receive a new function reference every time the parent component re-renders.
import React from 'react'; const ChildComponent = ({ onClick }) => { return ( <div> <p>Child Component</p> <button onClick={onClick}>Click Me</button> </div> ); }; export default ChildComponent;
With useCallback, the `handleClick` function is memoized, and it will only be recreated if the dependencies specified in the second parameter of `useCallback` (in this case, the `count` state) change.
This helps to ensure that the function reference remains stable between re-renders.