{"id":22856101,"url":"https://github.com/raheesahmed/nextjs-state","last_synced_at":"2026-04-09T16:51:56.279Z","repository":{"id":267470384,"uuid":"901337864","full_name":"RaheesAhmed/nextjs-state","owner":"RaheesAhmed","description":"🚀 Type-safe state management solution for Next.js applications with built-in persistence and server component support.","archived":false,"fork":false,"pushed_at":"2024-12-15T19:29:37.000Z","size":220,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-06T12:22:08.064Z","etag":null,"topics":["nextjs","nextjs-state","persistence","react","react-hooks","server-components","state","state-management","state-management-in-react","typescript","web-development","web-development-tools"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/RaheesAhmed.png","metadata":{"files":{"readme":"README.MD","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-12-10T13:28:39.000Z","updated_at":"2024-12-15T19:29:41.000Z","dependencies_parsed_at":"2024-12-10T16:31:21.036Z","dependency_job_id":null,"html_url":"https://github.com/RaheesAhmed/nextjs-state","commit_stats":null,"previous_names":["raheesahmed/next-state","raheesahmed/nextjs-state"],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RaheesAhmed%2Fnextjs-state","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RaheesAhmed%2Fnextjs-state/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RaheesAhmed%2Fnextjs-state/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/RaheesAhmed%2Fnextjs-state/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/RaheesAhmed","download_url":"https://codeload.github.com/RaheesAhmed/nextjs-state/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246436094,"owners_count":20776965,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nextjs","nextjs-state","persistence","react","react-hooks","server-components","state","state-management","state-management-in-react","typescript","web-development","web-development-tools"],"created_at":"2024-12-13T08:07:07.563Z","updated_at":"2025-10-04T19:38:37.065Z","avatar_url":"https://github.com/RaheesAhmed.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Next State\n\nA modern, type-safe state management solution designed specifically for Next.js applications. Next State provides a minimal yet powerful API with built-in support for server components, persistence, and development tools.\n\n[![npm version](https://badge.fury.io/js/nextjs-state.svg)](https://badge.fury.io/js/nextjs-state)\n[![Bundle Size](https://img.shields.io/bundlephobia/minzip/nextjs-state)](https://bundlephobia.com/package/nextjs-state)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n## Features\n\n- 🎯 **Type-safe**: Full TypeScript support with type inference and strict null checks\n- ⚡ **Lightweight**: Less than 1KB minified and gzipped for optimal bundle size\n- 🔄 **Middleware**: Extensible middleware system for logging, persistence, validation, and more\n- 💾 **Persistence**: Built-in storage adapters for localStorage and indexedDB with migration support\n- 🎨 **Selectors**: Efficient state access with automatic memoization to prevent unnecessary re-renders\n- 🖥️ **DevTools**: Integrated development tools for debugging and time-travel\n- 🚀 **Server Components**: First-class support for Next.js App Router and Server Components\n- 🔄 **Optimistic Updates**: Built-in support for optimistic UI updates with server synchronization\n- 📦 **Zero dependencies**: Only React as a peer dependency for minimal footprint\n\n## Installation\n\n```bash\nnpm install nextjs-state\n# or\nyarn add nextjs-state\n# or\npnpm add nextjs-state\n```\n\n## Quick Start\n\n```tsx\nimport { createNextState } from 'nextjs-state';\n\n// 1. Define your state type\ninterface CounterState {\n  count: number;\n  lastUpdated: string;\n}\n\n// 2. Create your state\nconst { useNextState } = createNextState\u003cCounterState\u003e({\n  initialState: {\n    count: 0,\n    lastUpdated: new Date().toISOString(),\n  },\n  // Optional configuration\n  options: {\n    // Enable DevTools in development\n    devTools: process.env.NODE_ENV === 'development',\n    // Persist state to localStorage\n    storage: {\n      key: 'counter-app',\n      version: '1.0',\n    },\n  },\n});\n\n// 3. Use in your components\nfunction Counter() {\n  // Access the full state\n  const { state, setState } = useNextState();\n\n  // Or use a selector for better performance\n  // const count = useNextState(state =\u003e state.count);\n\n  const increment = () =\u003e {\n    setState({\n      count: state.count + 1,\n      lastUpdated: new Date().toISOString(),\n    });\n  };\n\n  return (\n    \u003cdiv\u003e\n      \u003cp\u003eCount: {state.count}\u003c/p\u003e\n      \u003cp\u003eLast Updated: {new Date(state.lastUpdated).toLocaleString()}\u003c/p\u003e\n      \u003cbutton onClick={increment}\u003eIncrement\u003c/button\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## Complete Example\n\nHere's a comprehensive example showcasing all features including state management, middleware, theming, and UI components:\n\n```tsx\n'use client';\n\nimport {\n  createNextState,\n  createLoggingMiddleware,\n  createPersistenceMiddleware,\n} from 'nextjs-state';\n\n// Define complete app state\ninterface AppState {\n  counter: {\n    value: number;\n    history: number[];\n    lastUpdated: string;\n  };\n  todos: {\n    items: Array\u003c{\n      id: number;\n      text: string;\n      completed: boolean;\n      priority: 'low' | 'medium' | 'high';\n    }\u003e;\n    filter: 'all' | 'active' | 'completed';\n  };\n  theme: {\n    mode: 'light' | 'dark';\n    fontSize: 'small' | 'medium' | 'large';\n    accentColor: string;\n  };\n  user: {\n    preferences: {\n      notifications: boolean;\n      autoSave: boolean;\n    };\n    lastActivity: string;\n  };\n}\n\n// Create middleware stack\nconst loggingMiddleware = createLoggingMiddleware\u003cAppState\u003e();\nconst persistenceMiddleware = createPersistenceMiddleware\u003cAppState\u003e('app-state');\n\n// Custom analytics middleware\nconst analyticsMiddleware = (state: AppState, nextState: AppState) =\u003e {\n  if (state.counter.value !== nextState.counter.value) {\n    console.log('Analytics: Counter changed', {\n      from: state.counter.value,\n      to: nextState.counter.value,\n    });\n  }\n  return nextState;\n};\n\n// Custom validation middleware\nconst validationMiddleware = (state: AppState, nextState: AppState) =\u003e {\n  if (nextState.counter.value \u003c 0) {\n    console.warn('Validation: Negative counter values not allowed');\n    return state;\n  }\n  return nextState;\n};\n\n// Initialize state\nconst { useNextState } = createNextState\u003cAppState\u003e({\n  initialState: {\n    counter: {\n      value: 0,\n      history: [],\n      lastUpdated: new Date().toISOString(),\n    },\n    todos: {\n      items: [],\n      filter: 'all',\n    },\n    theme: {\n      mode: 'light',\n      fontSize: 'medium',\n      accentColor: '#3b82f6',\n    },\n    user: {\n      preferences: {\n        notifications: true,\n        autoSave: true,\n      },\n      lastActivity: new Date().toISOString(),\n    },\n  },\n  middleware: [loggingMiddleware, validationMiddleware, analyticsMiddleware, persistenceMiddleware],\n});\n\n// Action creators\nconst actions = {\n  counter: {\n    increment: (state: AppState) =\u003e ({\n      ...state,\n      counter: {\n        value: state.counter.value + 1,\n        history: [...state.counter.history, state.counter.value],\n        lastUpdated: new Date().toISOString(),\n      },\n    }),\n  },\n  theme: {\n    toggleMode: (state: AppState) =\u003e ({\n      ...state,\n      theme: {\n        ...state.theme,\n        mode: state.theme.mode === 'light' ? 'dark' : 'light',\n      },\n    }),\n  },\n  // ... more actions\n};\n\n// Example component\nfunction Counter() {\n  const { state, setState } = useNextState();\n\n  return (\n    \u003cdiv className={state.theme.mode === 'dark' ? 'bg-gray-800' : 'bg-white'}\u003e\n      \u003ch2\u003eCounter: {state.counter.value}\u003c/h2\u003e\n      \u003cbutton onClick={() =\u003e setState(actions.counter.increment)}\u003eIncrement\u003c/button\u003e\n      \u003cdiv\u003eHistory: {state.counter.history.join(', ')}\u003c/div\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\nFor a complete working example with all features and beautiful UI components, check out our [demo repository](https://github.com/yourusername/nextjs-state-demo).\n\n## Advanced Usage\n\n### Using with Next.js App Router\n\n```tsx\n// app/providers.tsx\n'use client';\n\nimport { createNextState } from 'nextjs-state';\n\ninterface AppState {\n  theme: 'light' | 'dark';\n  user: {\n    name: string;\n    preferences: Record\u003cstring, any\u003e;\n  } | null;\n}\n\nexport const { useNextState } = createNextState\u003cAppState\u003e({\n  initialState: {\n    theme: 'light',\n    user: null,\n  },\n});\n\n// app/layout.tsx\nimport { Providers } from './providers';\n\nexport default function RootLayout({ children }) {\n  return (\n    \u003chtml\u003e\n      \u003cbody\u003e\n        \u003cProviders\u003e{children}\u003c/Providers\u003e\n      \u003c/body\u003e\n    \u003c/html\u003e\n  );\n}\n```\n\n### Using Selectors for Performance\n\n```tsx\nimport { createNextState, useSelector } from 'nextjs-state';\n\ninterface DeepState {\n  users: {\n    list: Array\u003c{\n      id: number;\n      name: string;\n      settings: {\n        theme: string;\n        notifications: boolean;\n      };\n    }\u003e;\n    selectedId: number | null;\n  };\n}\n\nconst { useNextState } = createNextState\u003cDeepState\u003e({\n  initialState: {\n    users: {\n      list: [],\n      selectedId: null,\n    },\n  },\n});\n\nfunction SelectedUserSettings() {\n  const state = useNextState();\n  const selectedUser = useSelector(state, (s) =\u003e\n    s.users.list.find((u) =\u003e u.id === s.users.selectedId)\n  );\n\n  if (!selectedUser) return \u003cdiv\u003eNo user selected\u003c/div\u003e;\n\n  return (\n    \u003cdiv\u003e\n      \u003ch2\u003e{selectedUser.name}'s Settings\u003c/h2\u003e\n      \u003cp\u003eTheme: {selectedUser.settings.theme}\u003c/p\u003e\n      \u003cp\u003eNotifications: {selectedUser.settings.notifications ? 'On' : 'Off'}\u003c/p\u003e\n    \u003c/div\u003e\n  );\n}\n```\n\n## Best Practices\n\n1. **State Organization**\n\n   - Keep state minimal and focused\n   - Split large state into smaller, focused states\n   - Use TypeScript interfaces for better type safety\n\n2. **Performance**\n\n   - Use selectors for expensive computations\n   - Avoid storing derived state\n   - Split large components into smaller ones\n\n3. **Middleware Usage**\n   - Order middleware from most to least important\n   - Use middleware for cross-cutting concerns\n   - Keep middleware pure and side-effect free\n\n## API Reference\n\n### `createNextState\u003cT\u003e`\n\nCreates a new state instance.\n\n```tsx\nfunction createNextState\u003cT\u003e(config: {\n  initialState: T;\n  middleware?: Array\u003c(state: T, nextState: T) =\u003e T\u003e;\n}): {\n  useNextState: () =\u003e {\n    state: T;\n    setState: (newState: T | ((prevState: T) =\u003e T)) =\u003e void;\n  };\n};\n```\n\n### `useSelector`\n\nCreates a memoized selector.\n\n```tsx\nfunction useSelector\u003cT, S\u003e(hook: NextStateHook\u003cT\u003e, selector: (state: T) =\u003e S): S;\n```\n\n### Middleware Creators\n\n#### `createLoggingMiddleware`\n\n```tsx\nfunction createLoggingMiddleware\u003cT\u003e(): (state: T, nextState: T) =\u003e T;\n```\n\n#### `createPersistenceMiddleware`\n\n```tsx\nfunction createPersistenceMiddleware\u003cT\u003e(key: string): (state: T, nextState: T) =\u003e T;\n```\n\n## Documentation\n\nFor more detailed documentation, please visit our documentation site:\n\n- [Getting Started](./docs/getting-started/core-concepts.md) - Learn the core concepts and philosophy\n- [API Reference](./docs/api/api-reference.md) - Complete API documentation\n- [Guides](./docs/guides/) - In-depth guides for specific use cases\n  - [Middleware Guide](./docs/guides/middleware.md) - Learn how to create and use middleware\n  - [Testing Guide](./docs/guides/testing.md) - Best practices for testing\n- [Technical Documentation](./docs/technical_documentation.md) - Detailed technical information\n\n## Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](./CONTRIBUTING.md) for more details.\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fraheesahmed%2Fnextjs-state","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fraheesahmed%2Fnextjs-state","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fraheesahmed%2Fnextjs-state/lists"}