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

React Context – dispatch from a function

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:

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

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>

>Solution :

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