Reputation: 3015
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
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