global-react-hooks
v1.0.1
Published
Call react hooks from outside of the components
Downloads
1
Maintainers
Readme
Project forked from https://github.com/naycho334/react-hooks-outside#readme
global-react-hooks
Call react hooks from outside of the components
Installation
Using npm:
npm install --save global-react-hooks
Import module
// using ES6 modules
import { ReactHooksWrapper, setHook, getHook } from "global-react-hooks";
API
- setHook( name, hook )
- getHook( name )
Example
Add <ReactHooksWrapper /> component to App.js file and declare some hooks
import { ReactHooksWrapper, setHook } from 'global-react-hooks';
import React from 'react';
//
import { useHistory } from "react-router-dom";
import { useSnackbar } from "notistack";
setHook("history", useHistory)
.setHook("snackbar", useSnackbar)
// .setHook("hook1", useHook1)
// .setHook("hookWithArguments", useHookWithArguments.bind(null, arg1, arg2))
// .setHook("hook3", useHook3);
const App = ()=> {
return (
<div>
...
<ReactHooksWrapper />
</div>
);
}
render(<App />, document.getElementById('root'));
Then you can call the hook from any place you want
import { getHook } from "global-react-hooks";
function goToPage(pathname){
const history = getHook("history");
history.push(pathname);
}