I want to track when user click the button, and send the record to server.
and I am thinking where should I put the "send the record to server" logic in my component
to put it inside onClick handler or move it to useEffect
first version:
function Btn() {
return (
<Button onClick={(e) => {
// is doing side effect inside onClick handler a good practice ?
sendRecordToServer({ btnName: 'btn1' });
}}>
click & track me
</Button>
)
}
then I noticed the doc of useEffect
said
Mutations, subscriptions, timers, logging, and other side effects are not allowed inside the main body of a function component (referred to as React’s render phase). Doing so will lead to confusing bugs and inconsistencies in the UI.
so my second version:
function Btn() {
// introduce a new state
const [track, setTrack] = useState()
// doing side effect inside useEffect
useEffect(() => {
if (track) {
sendRecordToServer(track);
}
}, [track])
return (
<Button onClick={(e) => {
// has to be a object to make the effect can re-run, not simple string
setTrack({
btnName: 'btn1'
})
}}>
click & track me
</Button>
)
}
Can someone tell me which version is nicer ?