Newbie to react here, what is the right way to manage state from synthetic events using hooks and update the state from event handlers, i have gone through the official react documentation and could not find the specific information.
This is what i have tried so far.
Step 1: Declare the hook variable using which we will update state
const [state, setState] = React.useState(0);
Step 2: Declare the function to handle synthetic event & update the state
const handleCopy = (e) => {
setState(state+1);
e.preventDefault();
};
Step 3: Add event listener and pass event to the function
document.addEventListener('copy', (e) => handleCopy(e));
Step 4: Pass the state to the component
<Component value={state}/>
There are few problem i face here though
- The state update is not reflecting in the component. But it does seem to be updating the state since the console.log seems to reflect the state correctly.
- There are too many event-listeners getting registered over time.
To prevent too many event-listeners i wrapped the addEventListener with a condition to register only once
const [syntheticEventRegistered, setSyntheticEventRegistered] = React.useState(false);
if(!syntheticEventRegistered)
{
document.addEventListener('copy', (e) => handleCopy(e));
setSyntheticEventRegistered(true);
}
This did resolve too many event listeners, but the handleCopy function now reflects only default state. i.e state = 0 instead of latest state nor does this update Component value.