The useCallback Hook
useCallback hook helps to return a memoized callback that only changes if one of the dependencies has changed. This can help optimize performance by preventing unnecessary re-renders of child components.
Syntax:
const memoizedCallback = useCallback(
() => {
// Function logic
},
[dependencies]
);
- Here ‘dependencies‘ are an optional array of dependencies. The memoized callback will only be recalculated if one of these dependencies changes.
Example: Below is an example of useCallback hook.
import React, {
useState,
useCallback
} from 'react';
function Gfgarticle() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount((prevCount) => prevCount + 1);
}, []);
return (
<>
<p>Count: {count}</p>
<button onClick={increment}>
Incement
</button>
</>
)
}
export default Gfgarticle;
Output:
Additional Built-in Hooks in React
Hooks are functions that allow you to “hook” into the state of a component and provide additional features to ensure the lifespan of functional components. These are available in React versions 16.8.0 and higher. however, we previously used to describe them using classes.
We will discuss the various Additional Built-in Hooks:
Table of Content
- The useReducer hook
- The useRef hook
- The useCallback Hook
- The useMemo Hook
- The useLayoutEffect Hook
- The useImperativeHandle Hook
- The useDebugValue Hook
- Conclusion