Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/donnikitos/react-useglobal
A React.js hook to share and use global variables between unconnected components.
https://github.com/donnikitos/react-useglobal
Last synced: 8 days ago
JSON representation
A React.js hook to share and use global variables between unconnected components.
- Host: GitHub
- URL: https://github.com/donnikitos/react-useglobal
- Owner: donnikitos
- License: mit
- Created: 2020-12-21T10:05:56.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2021-02-28T12:41:11.000Z (over 3 years ago)
- Last Synced: 2024-10-11T17:42:09.032Z (about 1 month ago)
- Language: JavaScript
- Size: 8.79 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
useGlobal
===========[![NPM version](https://badgen.net/npm/v/react-useglobal)](https://www.npmjs.com/package/@donnikitos/react-useglobal)
[![License](https://badgen.net/npm/license/react-useglobal)](https://www.npmjs.com/package/@donnikitos/react-useglobal)A React.js hook to share and use global variables between unconnected components.
Install with [npm](https://www.npmjs.com/):
```bash
# via npm
npm install --save-dev @donnikitos/react-useglobal
```## Usage
The `useGlobal` function takes a string as the primary argument and may take a second argument - the initial value. The first argument, the supplied string
represents the name of a global variable, that the hook is supposed to interact with. The second argument is optional and represents the initial value, that
will be set to the global variable.
If the global variable is alrady set and has a value, the second argument (initial value) will be ignored.
The hook returns a tuple of a getter variable and a setter function very much like a normal useState hook in React.js.```js
import React from 'react';
import useGlobal from '@donnikitos/react-useglobal';// use in Component
export default function Comp(props) {
const [globalX, setGlobalX] = useGlobal('x'); // Access global variable x
const [globalY, setGlobalY] = useGlobal('y', 'Hello World'); // Access global variable y and set initial value to string 'Hello World'
const [tryY, setTryY] = useGlobal('y', 'test me'); // Access global variable y, second argument will be ignoredReact.useEffect(() => {
setGlobalX('i am global'); // change global variable
}, []);return (
);
{globalX} {/* output: i am global */}
{globalY} {/* output: Hello World */}
{tryY} {/* output: Hello World */}
};
```## License
[MIT](LICENSE) Copyright (c) 2020 Nikita 'donnikitos' Nitichevski.