https://github.com/bhrott/react-create-global-state
Generate a useState, but for global variables.
https://github.com/bhrott/react-create-global-state
global hooks react state usestate
Last synced: 4 months ago
JSON representation
Generate a useState, but for global variables.
- Host: GitHub
- URL: https://github.com/bhrott/react-create-global-state
- Owner: bhrott
- License: mit
- Created: 2019-03-19T01:36:06.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2019-03-19T11:46:02.000Z (over 6 years ago)
- Last Synced: 2025-05-23T11:16:19.981Z (5 months ago)
- Topics: global, hooks, react, state, usestate
- Language: JavaScript
- Size: 146 KB
- Stars: 16
- Watchers: 1
- Forks: 3
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# react-create-global-state
Generate a useState, but for global variables.
## Usage
1 - Create your custom hook
```jsx
/**
* useGlobalCounter.js
*/import createGlobalState from 'react-create-global-state'
// create the global for your hook
const initialState = 0const [useGlobalCounter, Provider] = createGlobalState(initialState)
// export the provider to link in the application
export const GlobalCounterProvider = Provider// export the hook
export default useGlobalCounter
```2 - Link the provider in your application
```jsx
import React, { Component } from 'react';// import the provider from your global var
import { GlobalCounterProvider } from './useGlobalCounter'class App extends Component {
render() {
return (
// add the provider.
{/*...*/}
);
}
}export default App
```
3 - Use the hook
```jsx
/**
* Counter.js
*/
import React from 'react'
import useGlobalCounter from './useGlobalCounter'export default function Counter(props) {
const [state, setState] = useGlobalCounter()return (
State: {state}
setState(state + 1)}>+1
setState(state - 1)}>-1
)
}
``````jsx
/**
* App.js
*/
import React, { Component } from 'react';import { GlobalCounterProvider } from './useGlobalCounter'
import Counter from './Counter'
class App extends Component {
render() {
return (
);
}
}export default App
```Result:

## Sample
You can check the sample code [HERE](https://github.com/benhurott/react-create-global-state-sample)