https://github.com/alnorris/react-outside-call
Use react hooks/context outside of React components.
https://github.com/alnorris/react-outside-call
context context-hooks hooks react
Last synced: about 1 month ago
JSON representation
Use react hooks/context outside of React components.
- Host: GitHub
- URL: https://github.com/alnorris/react-outside-call
- Owner: alnorris
- License: mit
- Created: 2021-05-28T22:54:10.000Z (about 4 years ago)
- Default Branch: main
- Last Pushed: 2023-02-03T12:33:53.000Z (over 2 years ago)
- Last Synced: 2025-04-02T06:51:14.185Z (2 months ago)
- Topics: context, context-hooks, hooks, react
- Language: TypeScript
- Homepage:
- Size: 117 KB
- Stars: 11
- Watchers: 1
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 📞 React Outside Call
Use 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.
## Install
```
npm install react-outside-call
```## Quickstart
### Step 1
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(),
});
```### Step 2
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')
);
```### Step 3
Now call `callConfig` 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}.`);
};
```