Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

is it okay to use `useDispatch` inside a function or a class?

is it okay to use useDispatch hook inside a function or a class? I am not talking about functional or class components. I want to dispatch a state change from function/class.

// Example: utils.ts

export function foo(){
  const bar = getBar();
  const dispatch = useDispatch();
  dispatch(addBar(bar))
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

No, things that begin with use are hooks and can only be used in function components.

If you want access to dispatch from a function, do one of

  • write the function as a thunk
  • pass dispatch in as an argument
  • import your store and call store.dispatch
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading