1

I noticed, preventDefault() doesn't work if called inside of reducer. As you can see in this sample. The target element, doesn't allow drop(pointer shows invalid icon), when a dragged element is enter or hovering it, even though preventDefault() is being called.

But when when I move the calling of preventDefault() at the handler(the function that receives the event), as you can see in this sample. The target element now allows drop operations.

In one of the projects that I been working on, I needed or I want to be sure that the state that I'm reading is the most recent, when deciding to called or not the preventDefault(), that's when I encounter this behavior.

Paulo
  • 63
  • 6

1 Answers1

1

The reducer is meant to update the state, not to handle browser events directly. React's synthetic events (like the evt parameter in your reducer) have limited scope and behaviour outside of the event handler they are associated with.
When an event like dragging occurs in a web page, it goes through a series of stages called event propagation. This process starts from the root of the page and moves towards the target element. During this journey, event handlers get a chance to respond. However, if you attempt to prevent the default behaviour of the event, like the default drag-and-drop behaviour, inside a reducer, the event has typically already progressed through this propagation process. So, even if you call preventDefault() within the reducer, it won't rewind the event to its earlier stages where the default behavior could be effectively stopped. This is why it's important to apply preventDefault() within the actual event handler, where it can intercept the event before its default behavior is triggered. This ensures that you're affecting the event behavior as it happens in real-time during the event propagation phase.
Regarding your concern about reading the most recent state, React's state updates and event handling mechanisms ensure that you are always working with the latest state when event handlers are triggered. The state will be updated and the component will re-render before any subsequent event handlers are executed. Therefore, you don't need to worry about the state not being up-to-date when calling preventDefault() within your event handlers.

Nazrul Chowdhury
  • 1,483
  • 1
  • 5
  • 11
  • thanks, though would it be possible that you can provide a link or atleast a quote from a doc or similar resources, that says the state are guarantee to be updated before subsequent events are trigger. I only found [this](https://stackoverflow.com/a/58130205/11523658), though the link it provide for the doc doesn't exist – Paulo Aug 25 '23 at 08:25
  • nevermind, i found it [here](https://react.dev/learn/queueing-a-series-of-state-updates#react-batches-state-updates) – Paulo Aug 25 '23 at 08:42