In React, a callback hook is a function that allows you to pass a function as a prop to a child component, which can then be used to update the state of the parent component.
useCallback
is a hook that allows you to memoize a function so that it is only recreated when its dependencies change. This can be useful when you have a function that you want to pass down to a child component, but you don't want to recreate the function every time the parent component renders. By wrapping the function in useCallback
, React can reuse the same function reference between renders, which can help improve performance.
Here's an example of useCallback
:
import React, { useCallback } from 'react';
function Parent() {
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <Child onClick={handleClick} />;
}
function Child(props) {
return <button onClick={props.onClick}>Click me</button>;
}
In this example, we define a handleClick
function using useCallback
, and then pass it down to the Child
component as a prop. Because handleClick
doesn't depend on any props or state variables, we pass an empty array as the second argument to useCallback
.