doggie
doggie

Reputation: 99

How to use react hooks in events

I have a custom hook that takes an item from my Redux store and dispatches it to another part of the of the store. The hook should fire whenever an item is dropped on an element.

Sample code:

const useDragged = () => {
    const draggedItem = useSelector((state) => state.draggedItem);
    const dispatch = useDispatch(); 
    dispatch(addItem(draggedItem));
}
//calling useDragged() here works

<MyComponent>
    <div ... onDrop={useDragged}> ... </div> //calling here crashes because I'm calling it from a function
</MyComponent>

I get that this Violate the rules of hooks because onDrop is a function call and hooks shouldn't be called inside functions - I just don't know the "right" way to implement a solution.

I also get that I could solve the specific issue by setting the value with event.dataTransfer.setData but I'm more interested in how I solve my general problem of hooks in event calls rather than the actual case here.

Upvotes: 0

Views: 640

Answers (1)

Sinan Yaman
Sinan Yaman

Reputation: 5946

You can't use hooks inside a function. You can only use them inside the body of the functional component. You can get the variables from the state, wherever. So you need to do:

function ComponentExample(props){
  const draggedItem = useSelector((state) => state.draggedItem);
  const dispatch = useDispatch(); 

  const useDragged = () => {
    dispatch(addItem(draggedItem));
  }
}

Upvotes: 1

Related Questions