Jad S
Jad S

Reputation: 3015

React 16: access context from outside of function component

I'm using React 16 and trying to use a React hook to access context.

const { locale } = React.useContext(LocaleContext);

This hook call is being done inside a Redux middleware. I then get the error Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component.

Is there any way for me to access context from outside of a functional component?

Upvotes: 1

Views: 530

Answers (1)

hiddenuser.2524
hiddenuser.2524

Reputation: 4988

It's not possible to use a hook outside a React component. If you really need to access the locale inside redux you can either keep an outside reference to it somewhere:

let globalLocale;

// inside a component
function MyComponent() {
  const {locale} = React.useContext(LocaleContext);
  globalLocale = locale;
}

Or you can add the locale in redux with an action (inside your LocaleContext e.g., whenever it changes):

// inside LocaleContextProvider somewhere, when locale updates 
dispatch({type: 'SET_LOCALE', payload: locale});

The you'll be able to access it in redux like any other value.

Upvotes: 1

Related Questions