r/learnreactjs • u/corner_guy0 • Jul 05 '24
Question can someone help me understand useCallBack?
so i am in total confusion right now
i was having hard time understanding useCallBack Hook so i went to chatgpt to learn it and i got more confused when it spit out below code as a example
so what i understand the incrementCallback function will be created everytime count variable changes but the IncrementCallback will change the count variable which will cause again the creation of incrementCallBack function which doesnt make sense to me
from what i understand till now about callBack is that it is used for memoization of function defination
but i dont understand how it can be useful?
import React, { useCallback, useState } from 'react';
const MyComponent = () => {
const [count, setCount] = useState(0);
// Without useCallback: this function would be recreated on every render
const increment = () => {
setCount(count + 1);
};
// With useCallback: function is only recreated if count changes
const incrementCallback = useCallback(() => {
setCount(count + 1);
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment (No useCallback)</button>
<button onClick={incrementCallback}>Increment (With useCallback)</button>
</div>
);
};
export default MyComponent;
View all comments
Show parent comment
1
u/corner_guy0 Jul 06 '24
thanks man! this is most simple and detailed explanation i got!