
Usecallback in ReactJS
✅ useCallback in ReactJS
useCallback
is a React Hook used to memoize functions. It prevents functions from being recreated on every render, optimizing performance in certain scenarios.
📌 Why Use useCallback
?
Prevents Unnecessary Re-Renders → Useful when passing functions as props to child components.
Performance Optimization → Functions are memoized (stored in memory) and only recreated if dependencies change.
Avoids Component Re-Mounting → Prevents unnecessary operations in components like lists or forms.
📌 Syntax
import React, { useState, useCallback } from 'react';const Counter = () => { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount((prevCount) => prevCount + <div> import React, { useState, useCallback } from 'react';const Counter = () => { const [count, setCount] = useState(0); const [step, setStep] = useState(1); const increment = useCallback(() => { setCount((prevCount) => prevCount + step); }, [step]); <div> import React, { useState, useCallback } from 'react';import Child from './Child';const Parent = () => { const [count, setCount] = useState(0); const increment = useCallback(() => { setCount((prevCount) => prevCount + <div> import React from 'react';const Child = React.memo(({ increment }) => { <button onClick={increment}>Increment from Child</button>;});export default Child;
🛠 Explanation:
React.memo → Prevents unnecessary re-renders of the child.
useCallback
→ Ensures theincrement
function remains stable.Result: Child only re-renders when needed.
📌 4. When Not to Use useCallback
For Simple Functions: If the function doesn't affect performance,
useCallback
may add complexity without benefit.No Props Passing: If functions aren't passed to children, you don't need
useCallback
.Function with No Dependencies: If there are no dependencies, a regular function works fine.
📌 5. Conclusion
Use
useCallback
→ When functions are passed as props or used in performance-critical components.Avoid Unnecessary Use → For static functions or those without performance issues.
Combine with
React.memo
→ For maximum optimization in child components.