https://github.com/adiathasan/react-store-maker
Utility function for creating stores for global state management with the context-API approach in react applications.
https://github.com/adiathasan/react-store-maker
context-api dispatch hooks react reducer typescript
Last synced: 3 months ago
JSON representation
Utility function for creating stores for global state management with the context-API approach in react applications.
- Host: GitHub
- URL: https://github.com/adiathasan/react-store-maker
- Owner: adiathasan
- Created: 2021-11-14T18:03:03.000Z (almost 4 years ago)
- Default Branch: master
- Last Pushed: 2023-03-22T19:46:01.000Z (over 2 years ago)
- Last Synced: 2025-06-08T22:26:04.362Z (4 months ago)
- Topics: context-api, dispatch, hooks, react, reducer, typescript
- Language: TypeScript
- Homepage: https://adiathasan.vercel.app
- Size: 16.6 KB
- Stars: 15
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# React Store maker
Create multiple stores with providers and get the store and dispatch hook for free with type safety!
## How to use it
**Install**
```bash
npm install react-store-maker
or
yarn add react-store-maker
```**Creating store with createStore function!**
```typescript
// ThemeConfig.ts
import { createStore } from 'react-store-maker';export type Theme = 'light' | 'dark';
const init: Theme = 'light';
export type ThemeActions = { type: 'SET_DARK'; payload: 'dark' } | { type: 'SET_LIGHT'; payload: 'light' };
const reducer = (state: Theme = init, action: ThemeActions) => {
switch (action.type) {
case 'SET_LIGHT':
return action.payload;
case 'SET_DARK':
return action.payload;
default:
return state;
}
};const [ThemeProvider, useThemeStore, useThemeDispatch] = createStore(init, reducer);
export { ThemeProvider, useThemeStore, useThemeDispatch };
// using with custom hook
export const useTheme = () => {
const theme = useThemeStore();
const dispatch = useThemeDispatch();const toggleTheme = () => {
const newThemeAction: ThemeActions =
theme === 'light' ? { type: 'SET_DARK', payload: 'dark' } : { type: 'SET_LIGHT', payload: 'light' };dispatch(newThemeAction);
};return {
toggleTheme,
theme,
};
};
```**Use it any where in your app after nesting at the top level**
```tsx
// App.tsx
import { ThemeProvider } from './ThemeConfig';
import { useTheme, useThemeStore } from './ThemeConfig';const App = () => {
return (
);
};const Header = () => {
const theme = useThemeStore();return (
The theme is - {theme}
);
};export const ToggleThemeBtn = () => {
const { toggleTheme } = useTheme();return Toggle theme;
};
```**Use multiple store providers for seperating logic**
```tsx
const App = () => {
return (
);
};// login.tsx
const Login = () => {
const { user } = useAuthStore();const dispatch = useAuthDispatch();
return (
welcome - {user}
dispatch({ type: 'LOGOUT' })}>Logout
);
};
```