|
1 |
| -# use-global-state-react |
| 1 | +## useGlobalState |
| 2 | + |
| 3 | +**Simple useGlobalState hook for React!** |
| 4 | + |
| 5 | +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? |
| 6 | + |
| 7 | +Just use `useGlobalState`, it's really simple and does all the magic for you: |
| 8 | +- first argument is a key for your store |
| 9 | +- second argument is optional - initial value |
| 10 | + |
| 11 | +### Example: |
| 12 | +```ts |
| 13 | +import { useGlobalState } from 'use-global-state-react'; |
| 14 | + |
| 15 | +const TASK_STORE_KEY = 'tasks'; |
| 16 | + |
| 17 | +const Tasks = () => { |
| 18 | + const [tasks, setTasks] = useGlobalState<string[]>(TASK_STORE_KEY, []); |
| 19 | + |
| 20 | + ... |
| 21 | +} |
| 22 | +``` |
| 23 | + |
| 24 | +and then you can use the same hook everywhere, data will be shared across components and component will rerender if changes happened in store: |
| 25 | + |
| 26 | +```ts |
| 27 | +const AddTaskButton = () => { |
| 28 | + const [, setTasks] = useGlobalState(TASK_STORE_KEY, []); |
| 29 | + |
| 30 | + const onTaskAdd = (newTask: stirng) => setTasks(prev => [...prev, newTask]); |
| 31 | + |
| 32 | + ... |
| 33 | +} |
| 34 | + |
| 35 | +const TasksTotal = () => { |
| 36 | + const [tasks] = useGlobalState<string[]>(TASK_STORE_KEY, []); |
| 37 | + |
| 38 | + return tasks.length; |
| 39 | +} |
| 40 | +``` |
| 41 | + |
| 42 | + |
| 43 | +or use helper `createGlobalStore` to create custom hook with shared data: |
| 44 | + |
| 45 | +```ts |
| 46 | +import { createGlobalStore } from 'use-global-state-react'; |
| 47 | + |
| 48 | +const useTasks = createGlobalStore<string[]>(TASK_STORE_KEY, []); |
| 49 | + |
| 50 | + |
| 51 | +const Tasks = () => { |
| 52 | + const [tasks, setTasks] = useTasks(); |
| 53 | + ... |
| 54 | +} |
| 55 | + |
| 56 | +``` |
| 57 | + |
| 58 | +## Installation |
| 59 | + |
| 60 | +``` |
| 61 | + npm i use-global-state-react |
| 62 | +``` |
| 63 | + |
| 64 | +or |
| 65 | + |
| 66 | +``` |
| 67 | + yarn add use-global-state-react |
| 68 | +``` |
0 commit comments