Search code examples
reactjsreduxreact-redux

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

  • 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