In my functional React component, I have a function that is used both on component mount and in some child event:
const [count, setCount] = useState(0);
const myFunction = useCallback(() => {
// do something with count, such as a fetch or console.log for example
}, [])
useEffect(() => {
myFunction()
}, [myFunction])
return (
<button onClick={myFunction}>
myButton
</button>
)
myFunction must be called on mount and when the button is clicked. However, the classic React way of doing this implies to declare count as a dependency in useCallback, which would trigger a call of myFunction each time count is updated by another part of the program, which I do not want. count must be able to be updated without triggering myFunction.
I cannot find a clean solution for doing this. Is there one? Or should I write my code a different way? What's the best way to deal with this situation?