I've heard that declaring a function in a react component to handle clicks should be done inside a useCallback hook to avoid recreating the function every render, specially if the function is somewhat complex, like this:
const handleClick = useCallback(()=>
{
"...do a lot of calculations here that takes time"
},[]);
<button onClick={handleClick}>
Click me!
</button>
But I have a special case where I want the useCallback function to trigger when the button is clicked to set a state, this is what I want :
const [state, setState] = useState();
const handleClick = useCallback(()=>
{
const newState = "...do a lot of calculations here that takes time"
setState( newState )
},[ when button is clicked ]);
The problem is, how do i put the "when button is clicked" on the dependency of useCallback, and, as a matter of fact, any react hook that accepts a dependency list? I could do it with some dumb variable and separating the expensive calculations that take time from the onClick function, like bellow, but I don't think this is a good aproach since I'll be wasting memory:
const [state, setState] = useState();
const [dumb, setDumb] = useState(0);
useEffect(()=>
{
const newState = "...do a lot of calculations here that takes time"
setState( newState )
},[ dumb ]);
<button onClick=()=>setDumb(dumb+1)>
Click me!
</button>