Effortless global state management for React
& React Native
& Preact
! 🚀 Define a global state in just one line of code and enjoy lightweight, flexible, and scalable state management. Try it now on CodePen and see it in action! ✨
- Live Example 📘
- Video Overview 🎥
-
react-hooks-global-states compatible with both
React & React Native
- react-global-state-hooks specific for web applications (local-storage integration).
- react-native-global-state-hooks specific for React Native projects (async-storage integration).
React Hooks Global States includes a dedicated, devTools extension
to streamline your development workflow! Easily visualize, inspect, debug, and modify your application's global state in real-time right within your browser.
Track State Changes | Modify the State |
---|---|
![]() |
![]() |
Effortlessly monitor state updates and history. | Instantly edit global states directly from the extension. |
Restore the State | Custom Actions Granularity |
---|---|
![]() |
![]() |
Quickly revert your application to a previous state. | Precisely debug specific actions affecting state changes. |
Define a global state in one line:
import { createGlobalState } from 'react-hooks-global-states/createGlobalState';
export const useCount = createGlobalState(0);
Now, use it inside a component:
const [count, setCount] = useCount();
return <Button onClick={() => setCount((count) => count + 1)}>{count}</Button>;
Works just like useState, but the state is shared globally! 🎉
For complex state objects, you can subscribe to specific properties instead of the entire state:
export const useContacts = createGlobalState({ entities: [], selected: new Set<number>() });
To access only the entities
property:
const [contacts] = useContacts((state) => state.entities);
return (
<ul>
{contacts.map((contact) => (
<li key={contact.id}>{contact.name}</li>
))}
</ul>
);
You can also add dependencies to a selector. This is useful when you want to derive state based on another piece of state (e.g., a filtered list). For example, if you're filtering contacts based on a filter
value:
const [contacts] = useContacts(
(state) => state.entities.filter((item) => item.name.includes(filter)),
[filter]
);
Alternatively, you can pass dependencies inside an options object:
const [contacts] = useContacts((state) => state.entities.filter((item) => item.name.includes(filter)), {
dependencies: [filter],
isEqualRoot: (a, b) => a.entities === b.entities,
});
Unlike Redux, where only root state changes trigger re-selection, this approach ensures that derived values recompute when dependencies change while maintaining performance.
export const useContactsArray = useContacts.createSelectorHook((state) => state.entities);
export const useContactsCount = useContactsArray.createSelectorHook((entities) => entities.length);
const [contacts] = useContactsArray();
const [count] = useContactsCount();
You can still use dependencies inside a selector hook:
const [filteredContacts] = useContactsArray(
(contacts) => contacts.filter((c) => c.name.includes(filter)),
[filter]
);
The stateMutator remains the same across all derived selectors, meaning actions and setState functions stay consistent.
const [actions1] = useContactsArray();
const [actions2] = useContactsCount();
console.log(actions1 === actions2); // true
Restrict state modifications by defining custom actions:
export const useContacts = createGlobalState(
{ filter: '', items: [] },
{
actions: {
async fetch() {
return async ({ setState }) => {
const items = await fetchItems();
setState({ items });
};
},
setFilter(filter: string) {
return ({ setState }) => {
setState((state) => ({ ...state, filter }));
};
},
},
}
);
Now, instead of setState
, the hook returns actions:
const [filter, { setFilter }] = useContacts();
Use stateControls()
to retrieve or update state outside React components:
const [contactsRetriever, contactsApi] = useContacts.stateControls();
console.log(contactsRetriever()); // Retrieves the current state
const unsubscribe = contactsRetriever((state) => {
console.log('State updated:', state);
});
const useSelectedContact = createGlobalState(null, {
callbacks: {
onInit: ({ setState, getState }) => {
contactsRetriever(
(state) => state.contacts,
(contacts) => {
if (!contacts.has(getState())) setState(null);
}
);
},
},
});
- Scoped State – Context state is isolated inside the provider.
- Same API – Context supports selectors, actions, and state controls.
import { createContext } from 'react-global-state-hooks/createContext';
export const [useCounterContext, CounterProvider] = createContext(0);
Wrap your app:
<CounterProvider>
<MyComponent />
</CounterProvider>
Use the context state:
const [count] = useCounterContext();
Works just like global state, but within the provider.
Observables let you react to state changes via subscriptions.
export const useCounter = createGlobalState(0);
export const counterLogs = useCounter.createObservable((count) => `Counter is at ${count}`);
const unsubscribe = counterLogs((message) => {
console.log(message);
});
export const [useStateControls, useObservableBuilder] = useCounterContext.stateControls();
const createObservable = useObservableBuilder();
useEffect(() => {
const unsubscribe = createObservable((count) => {
console.log(`Updated count: ${count}`);
});
return unsubscribe;
}, []);
Feature | createGlobalState |
createContext |
---|---|---|
Scope | Available globally across the entire app | Scoped to the Provider where it’s used |
How to Use | const useCount = createGlobalState(0) |
const [useCountContext, Provider] = createContext(0) |
createSelectorHook | useCount.createSelectorHook |
useCountContext.createSelectorHook |
inline selectors? | ✅ Supported | ✅ Supported |
Custom Actions | ✅ Supported | ✅ Supported |
Observables | useCount.createObservable |
const [, useObservableBuilder] = useCountContext.stateControls() |
State Controls | useCount.stateControls() |
const [useStateControls] = useCountContext.stateControls() |
Best For | Global app state (auth, settings, cache) | Scoped module state, reusable component state, or state shared between child components without being fully global |
Global state hooks support lifecycle callbacks for additional control.
const useData = createGlobalState(
{ value: 1 },
{
callbacks: {
onInit: ({ setState }) => {
console.log('Store initialized');
},
onStateChanged: ({ state, previousState }) => {
console.log('State changed:', previousState, '→', state);
},
computePreventStateChange: ({ state, previousState }) => {
return state.value === previousState.value;
},
},
}
);
Use onInit
for setup, onStateChanged
to listen to updates, and computePreventStateChange
to prevent unnecessary updates.
There is a possibility to add non reactive information in the global state:
const useCount = createGlobalState(0, { metadata: { renders: 0 } });
How to use it?
const [count, , metadata] = useCount();
metadata.renders += 1;
📦 NPM Package: react-hooks-global-states
🚀 Simplify your global state management in React & React Native today! 🚀