Simple global state for React with Hooks API without Context API
Simple global state for React with Hooks API without Context API
This is a library to provide a global state with React Hooks. It has following characteristics.
useGlobalStateProvidersupports CM without React Context.
npm install react-hooks-global-state
import React from 'react'; import { createGlobalState } from 'react-hooks-global-state';const initialState = { count: 0 }; const { useGlobalState } = createGlobalState(initialState);
const Counter = () => { const [count, setCount] = useGlobalState('count'); return (
Counter: {count} {/* update state by passing callback function /} setCount(v => v + 1)}>+1 {/ update state by passing new value */} setCount(count - 1)}>-1); };const App = () => ( <> > );
import React from 'react'; import { createStore } from 'react-hooks-global-state';const reducer = (state, action) => { switch (action.type) { case 'increment': return { ...state, count: state.count + 1 }; case 'decrement': return { ...state, count: state.count - 1 }; default: return state; } }; const initialState = { count: 0 }; const { dispatch, useGlobalState } = createStore(reducer, initialState);
const Counter = () => { const [value] = useGlobalState('count'); return (
Counter: {value} dispatch({ type: 'increment' })}>+1 dispatch({ type: 'decrement' })}>-1); };const App = () => ( <> > );
create a global state
It returns a set of functions
useGlobalState: a custom hook works like React.useState
getGlobalState: a function to get a global state by key outside React
setGlobalState: a function to set a global state by key outside React
initialStateState
import { createGlobalState } from 'react-hooks-global-state';const { useGlobalState } = createGlobalState({ count: 0 });
const Component = () => { const [count, setCount] = useGlobalState('count'); ... };
create a global store
In additon to
useGlobalStatewhich is the same hook as in createGlobalState, a store has
getStateand
dispatch. A store works somewhat similarly to Redux, but not the same.
reducerReducer<State, Action>
initialStateState (optional, default
(reducer as any)(undefined,{type:undefined}))
enhancerEnhancer<any>?
import { createStore } from 'react-hooks-global-state';const initialState = { count: 0 }; const reducer = ...;
const store = createStore(reducer, initialState); const { useGlobalState } = store;
const Component = () => { const [count, setCount] = useGlobalState('count'); ... };
The examples folder contains working examples. You can run one of them with
PORT=8080 npm run examples:01_minimal
and open http://localhost:8080 in your web browser.
You can also try them in codesandbox.io: 01 02 03 04 05 06 07 08 09 10 11 12 13