https://github.com/spiderpoul/use-global-state-react
Simple useGlobalState hook for React!
https://github.com/spiderpoul/use-global-state-react
react react-hooks react-state react-state-management usestate
Last synced: 13 days ago
JSON representation
Simple useGlobalState hook for React!
- Host: GitHub
- URL: https://github.com/spiderpoul/use-global-state-react
- Owner: spiderpoul
- Created: 2021-12-24T08:41:54.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2021-12-27T18:57:02.000Z (over 3 years ago)
- Last Synced: 2025-03-27T12:37:21.653Z (about 1 month ago)
- Topics: react, react-hooks, react-state, react-state-management, usestate
- Language: JavaScript
- Homepage:
- Size: 66.4 KB
- Stars: 12
- Watchers: 1
- Forks: 0
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## useGlobalState
**Simple useGlobalState hook for React!**
Do you need your data shared across other components, and you simply don't want to pass props all the way down, create context or use state management tool?
Just use `useGlobalState`, it's really simple and does all the magic for you:
- first argument is a key for your store
- second argument is optional - initial valueTry [Codesandbox example](https://codesandbox.io/s/boring-cerf-j4ub4)
### Example:
```ts
import { useGlobalState } from 'use-global-state-react';const TASK_STORE_KEY = 'tasks';
const Tasks = () => {
const [tasks, setTasks] = useGlobalState(TASK_STORE_KEY, []);
...
}
```and then you can use the same hook everywhere, data will be shared across components and component will rerender if changes happened in store:
```ts
const AddTaskButton = () => {
const [, setTasks] = useGlobalState(TASK_STORE_KEY, []);
const onTaskAdd = (newTask: stirng) => setTasks(prev => [...prev, newTask]);
...
}const TasksTotal = () => {
const [tasks] = useGlobalState(TASK_STORE_KEY, []);
return tasks.length;
}
```or use helper `createGlobalStore` to create custom hook with shared data:
```ts
import { createGlobalStore } from 'use-global-state-react';const useTasks = createGlobalStore(TASK_STORE_KEY, []);
const Tasks = () => {
const [tasks, setTasks] = useTasks();
...
}```
## Installation
```
npm i use-global-state-react
```or
```
yarn add use-global-state-react
```