An open API service indexing awesome lists of open source software.

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.

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