Use react context or packages that use context outside of React
npm install react-outside-callUse react hooks/context outside of React. Useful if you're using react packages that don't have this functionality, or you want access context hooks useContext outside of React.
```
npm install react-outside-call
Create outside caller object with the hooks you want to use like this...
`jsx
import OutsideCallConsumer, { createCaller } from 'react-outside-call';
const callConfig = createCaller({
myUserContext: () => useContext(myUserContext),
useToasts: () => useToasts(),
apolloClient: () => useApolloClient(),
});
`
Add the component just after all the Provider components.
Note:
- Always put after all the Provider components
- This will not rerender if any context's get updated, so you don't need to worry about unnecessary rerenders!
Example:
`jsx
import React, { useContext } from 'react';
import ReactDOM from 'react-dom';
import App from './app';
import { ToastProvider } from 'react-toast-notifications';
import myUserContext, MyUserContextProvider from './myUserContext';
import OutsideCallConsumer, { createCaller } from 'react-outside-call';
import apolloClient from './apolloClient';
export const callConfig = createCaller({
myUserContext: () => useContext(myUserContext),
useToasts: () => useToasts(),
apolloClient: () => useApolloClient(),
});
ReactDOM.render(
document.getElementById('root')
);
`
using the call object wherever you like in your project - like inside a normal javascript function, redux sagas, etc..
`jsx
import { callConfig } from './index';export const logHttpFailure = () => {
callConfig.call.useToasts.addToast({ message: 'Network error' });
console.log(
User failure ${callConfig.call.myContext}.);
};
``