I have the counter component. I encapsulated the business logic with custom hook. Should I optimize functions by means useCallback
? If there is input onchange handler, will the situation be the same?
const increment = () => {
setCount(count + 1);
};
↓
const increment = useCallback(() => {
setCount(count + 1);
}, [count]);
Assuming that count and setCount came from const [count,setCount] = useState(0)
then you should use callback in the following way so increment function stays the same during the component's life cycle:
const increment = useCallback(() => setCount(count => count + 1),[]);
You don't need to re create increment when count changes because you can pass a callback to the state setter function.