react-hooks-global-state
[NOT MAINTAINED] Simple global state for React with Hooks API without Context API
Top Related Projects
A JS library for predictable global state management
Simple, scalable state management.
🐻 Bear necessities for state management in React
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Vegetarian friendly state for React
Quick Overview
React Hooks Global State is a lightweight library for managing global state in React applications using hooks. It provides a simple and efficient way to share state across components without the complexity of traditional state management solutions like Redux.
Pros
- Simple API that leverages React Hooks
- Minimal boilerplate code required
- TypeScript support out of the box
- Small bundle size (less than 1KB gzipped)
Cons
- Limited features compared to more comprehensive state management libraries
- May not be suitable for very large or complex applications
- Less ecosystem support and tooling compared to Redux or MobX
Code Examples
Creating a global state:
import { createGlobalState } from 'react-hooks-global-state';
const initialState = { count: 0 };
const { useGlobalState } = createGlobalState(initialState);
Using global state in a component:
import React from 'react';
import { useGlobalState } from './state';
const Counter = () => {
const [count, setCount] = useGlobalState('count');
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
Creating a custom hook with global state:
import { createGlobalState } from 'react-hooks-global-state';
const initialState = { theme: 'light' };
const { useGlobalState } = createGlobalState(initialState);
export const useTheme = () => {
const [theme, setTheme] = useGlobalState('theme');
const toggleTheme = () => setTheme(theme === 'light' ? 'dark' : 'light');
return { theme, toggleTheme };
};
Getting Started
-
Install the package:
npm install react-hooks-global-state
-
Create a global state:
import { createGlobalState } from 'react-hooks-global-state'; const initialState = { count: 0, user: null }; export const { useGlobalState } = createGlobalState(initialState);
-
Use the global state in your components:
import React from 'react'; import { useGlobalState } from './state'; const MyComponent = () => { const [count, setCount] = useGlobalState('count'); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
Competitor Comparisons
A JS library for predictable global state management
Pros of Redux
- Mature ecosystem with extensive middleware, dev tools, and community support
- Predictable state management with a single source of truth
- Time-travel debugging and easy state persistence
Cons of Redux
- Steeper learning curve and more boilerplate code
- Overkill for smaller applications or simpler state management needs
- Performance overhead for large state trees or frequent updates
Code Comparison
Redux:
const store = createStore(rootReducer);
const action = { type: 'INCREMENT' };
store.dispatch(action);
react-hooks-global-state:
const { useGlobalState } = createGlobalState({ count: 0 });
const [count, setCount] = useGlobalState('count');
setCount(count + 1);
Key Differences
- Redux follows a more structured approach with actions, reducers, and a single store
- react-hooks-global-state leverages React Hooks for a simpler, more lightweight solution
- Redux offers more advanced features like middleware and time-travel debugging
- react-hooks-global-state provides a more straightforward API with less boilerplate
Use Cases
- Redux: Large-scale applications with complex state management needs
- react-hooks-global-state: Smaller to medium-sized applications or those transitioning from local state to global state management
Both libraries aim to solve state management in React applications, but Redux offers a more comprehensive solution at the cost of complexity, while react-hooks-global-state provides a simpler alternative for less demanding use cases.
Simple, scalable state management.
Pros of MobX
- More mature and widely adopted, with a larger ecosystem and community support
- Provides automatic tracking of observable state changes, reducing boilerplate code
- Offers more advanced features like computed values, reactions, and actions
Cons of MobX
- Steeper learning curve due to its more complex API and concepts
- Requires more setup and configuration compared to the simpler react-hooks-global-state
- Can lead to potential performance issues if not used carefully in large applications
Code Comparison
react-hooks-global-state:
import { createGlobalState } from 'react-hooks-global-state';
const { useGlobalState } = createGlobalState({ count: 0 });
function Counter() {
const [count, setCount] = useGlobalState('count');
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
MobX:
import { makeAutoObservable } from 'mobx';
import { observer } from 'mobx-react-lite';
class CounterStore {
count = 0;
constructor() {
makeAutoObservable(this);
}
increment() {
this.count++;
}
}
const Counter = observer(({ store }) => (
<button onClick={() => store.increment()}>{store.count}</button>
));
🐻 Bear necessities for state management in React
Pros of zustand
- Simpler API with less boilerplate code
- Better TypeScript support out of the box
- More flexible, allowing for middleware and custom store enhancers
Cons of zustand
- Slightly larger bundle size
- Less focus on React-specific optimizations
- May require more setup for complex state management scenarios
Code Comparison
react-hooks-global-state:
import { createGlobalState } from 'react-hooks-global-state';
const { useGlobalState } = createGlobalState({ count: 0 });
const Counter = () => {
const [count, setCount] = useGlobalState('count');
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
};
zustand:
import create from 'zustand';
const useStore = create(set => ({
count: 0,
increment: () => set(state => ({ count: state.count + 1 })),
}));
const Counter = () => {
const { count, increment } = useStore();
return <button onClick={increment}>{count}</button>;
};
Both libraries offer simple state management solutions for React applications, but zustand provides more flexibility and better TypeScript support. react-hooks-global-state focuses on a more React-centric approach with its API design. The choice between the two depends on specific project requirements and developer preferences.
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Pros of Recoil
- More powerful and flexible state management with atom-based architecture
- Built-in support for asynchronous and derived state
- Better performance optimization for large-scale applications
Cons of Recoil
- Steeper learning curve due to new concepts and APIs
- Larger bundle size compared to react-hooks-global-state
- Still in experimental phase, potentially less stable
Code Comparison
react-hooks-global-state:
import { createGlobalState } from 'react-hooks-global-state';
const { useGlobalState } = createGlobalState({ count: 0 });
function Counter() {
const [count, setCount] = useGlobalState('count');
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
Recoil:
import { atom, useRecoilState } from 'recoil';
const countState = atom({ key: 'countState', default: 0 });
function Counter() {
const [count, setCount] = useRecoilState(countState);
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}
Both libraries offer simple APIs for managing global state in React applications. react-hooks-global-state provides a more straightforward approach with minimal setup, while Recoil introduces a more powerful but complex atom-based system. The choice between them depends on the specific needs of your project, considering factors such as scalability, performance requirements, and team familiarity with the concepts.
Vegetarian friendly state for React
Pros of easy-peasy
- More feature-rich, offering built-in support for computed properties, listeners, and side effects
- Provides TypeScript support out of the box
- Includes devtools integration for better debugging experience
Cons of easy-peasy
- Larger bundle size due to additional features
- Steeper learning curve for developers new to the library
- May be considered "overkill" for simpler state management needs
Code Comparison
react-hooks-global-state:
import { createGlobalState } from 'react-hooks-global-state';
const { useGlobalState } = createGlobalState({ count: 0 });
const Counter = () => {
const [count, setCount] = useGlobalState('count');
return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
};
easy-peasy:
import { createStore, useStoreState, useStoreActions } from 'easy-peasy';
const store = createStore({ count: 0, increment: state => state.count++ });
const Counter = () => {
const count = useStoreState(state => state.count);
const increment = useStoreActions(actions => actions.increment);
return <button onClick={increment}>{count}</button>;
};
Both libraries offer simple APIs for managing global state in React applications. react-hooks-global-state provides a lightweight solution focused on hooks, while easy-peasy offers a more comprehensive state management experience with additional features and tooling support.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
This project is no longer maintained. Please directly use Zustand.
react-hooks-global-state
Simple global state for React with Hooks API without Context API
Introduction
This is a library to provide a global state with React Hooks. It has following characteristics.
- Optimization for shallow state getter and setter.
- The library cares the state object only one-level deep.
- TypeScript type definitions
- A creator function creates hooks with types inferred.
- Redux middleware support to some extent
- Some of libraries in Redux ecosystem can be used.
Install
npm install react-hooks-global-state
Usage
setState style
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 (
<div>
<span>Counter: {count}</span>
{/* update state by passing callback function */}
<button onClick={() => setCount(v => v + 1)}>+1</button>
{/* update state by passing new value */}
<button onClick={() => setCount(count - 1)}>-1</button>
</div>
);
};
const App = () => (
<>
<Counter />
<Counter />
</>
);
reducer style
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, useStoreState } = createStore(reducer, initialState);
const Counter = () => {
const value = useStoreState('count');
return (
<div>
<span>Counter: {value}</span>
<button onClick={() => dispatch({ type: 'increment' })}>+1</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-1</button>
</div>
);
};
const App = () => (
<>
<Counter />
<Counter />
</>
);
API
createGlobalState
Create a global state.
It returns a set of functions
useGlobalState
: a custom hook works like React.useStategetGlobalState
: a function to get a global state by key outside ReactsetGlobalState
: a function to set a global state by key outside Reactsubscribe
: a function that subscribes to state changes
Parameters
initialState
State
Examples
import { createGlobalState } from 'react-hooks-global-state';
const { useGlobalState } = createGlobalState({ count: 0 });
const Component = () => {
const [count, setCount] = useGlobalState('count');
...
};
createStore
Create a global store.
It returns a set of functions
useStoreState
: a custom hook to read store state by keygetState
: a function to get store state by key outside Reactdispatch
: a function to dispatch an action to store
A store works somewhat similarly to Redux, but not the same.
Parameters
reducer
Reducer<State, Action>initialState
State (optional, default(reducer as any)(undefined,{type:undefined})
)enhancer
any?
Examples
import { createStore } from 'react-hooks-global-state';
const initialState = { count: 0 };
const reducer = ...;
const store = createStore(reducer, initialState);
const { useStoreState, dispatch } = store;
const Component = () => {
const count = useStoreState('count');
...
};
Returns Store<State, Action>
useGlobalState
useGlobalState created by createStore is deprecated.
Type: function (stateKey: StateKey): any
Meta
- deprecated: useStoreState instead
Examples
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 13
Blogs
- TypeScript-aware React hooks for global state
- An alternative to React Redux by React Hooks API (For both JavaScript and TypeScript)
- Redux middleware compatible React Hooks library for easy global state management
- React Hooks Tutorial on pure useReducer + useContext for global state like Redux and comparison with react-hooks-global-state
- Four patterns for global state with React hooks: Context or Redux
- Steps to Develop Global State for React With Hooks Without Context
Community Wiki
Top Related Projects
A JS library for predictable global state management
Simple, scalable state management.
🐻 Bear necessities for state management in React
Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
Vegetarian friendly state for React
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot