Home > Enterprise >  React Context - dispatch from a function
React Context - dispatch from a function

Time:05-01

I have to call dispatch (Context, not Redux) in a function, but I am not able to do this. (Error: Invalid hook call. Hooks can only be called inside of the body of a function component.)

Is there a way to run hooks (or only dispatch) inside a function called from a component? I can do this using Redux (store.dispatch(...)), but I have no idea how to do this with React Context.

Example function:

function someAction() {
  const { dispatch } = React.useContext(SomeContext);
  dispatch({
    type: "ACTION_NAME",
  });
}

I am trying to call that function directly from a component:

<button onClick={() => someAction()}>Click me</button>

Sure, I can pass dispatch, but I want to avoid this because the function will be shared and it should be simple.

<button onClick={() => someAction(dispatch)}>Click me</button>

CodePudding user response:

You can only use hooks in components or other hooks, but you can use the return value of hooks inside other functions. Extract the useContext from the function, and use the returned dispatch:

const Component = () => {
  const { dispatch } = React.useContext(SomeContext);

  function someAction() {
    dispatch({
      type: "ACTION_NAME",
    });
  }

  return (
    <button onClick={someAction}>Click me</button>
  );
};

I would create a custom hook that returns the action function, and use it in the component, to make it less clunky and more reusable:

const useAction = () => {
  const { dispatch } = React.useContext(SomeContext);
  
  return () => dispatch({
    type: "ACTION_NAME",
  });
};

Usage:

const Component = () => {
  const someAction = useAction();
  
  return (
    <button onClick={someAction}>Click me</button>
  );
};
  • Related