Home > Software engineering >  is it okay to use `useDispatch` inside a function or a class?
is it okay to use `useDispatch` inside a function or a class?

Time:04-01

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))
}

CodePudding user response:

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

CodePudding user response:

The answer above is correct!! Just to add, this syntax might help for beginners if you want to do some async calls or get state.

Requisite - Connect should be wrapped in root component.

store.dispatch(doSomething())

export function doSomething() {
    return async (dispatch, getState, { client }) => { //your code } }
  • Related