1.0.9 β€’ Published 8 months ago

easyprostate v1.0.9

Weekly downloads
-
License
MIT
Repository
-
Last release
8 months ago

Easy Pro State

Easy Pro State is an advanced yet incredibly simple state management library for React. Designed for modern applications, it offers a powerful, intuitive API to manage global state, with built-in support for real-time synchronization, state persistence, and debugging tools.

Features

  • πŸ“¦ Zero Boilerplate: Manage global state effortlesslyβ€”just useProState!
  • πŸ”„ Real-Time Sync: Synchronize state across users and devices with WebSocket or SSE
  • πŸ’Ύ Persistent State: Automatically save and restore state across sessions with LocalStorage
  • 🧩 DevTools Support: Debug global state directly from your browser
  • ⚑ Performance Optimized: Subscriptions are scoped to specific state keys to avoid unnecessary re-renders
  • πŸ§‘β€πŸ’» TypeScript Support: Fully typed for seamless integration with TypeScript projects

Installation

Install the library via npm:

npm install easyprostate

Or yarn:

yarn add easyprostate

Quick Start

Basic Usage

Import useProState from Easy Pro State and use it to manage global state in your React components:

import { useProState } from 'easyprostate';

function App() {
  const [user, setUser] = useProState('user', { name: 'Guest', loggedIn: false });

  return (
    <div>
      <h1>Welcome, {user.name}!</h1>
      <button onClick={() => setUser({ ...user, name: 'John Doe', loggedIn: true })}>
        Login as John
      </button>
    </div>
  );
}

export default App;

Real-Time State Sync

Enable real-time synchronization using WebSocket:

import { setupWebSocket, useProState } from 'easyprostate';

// Initialize WebSocket connection
setupWebSocket('wss://your-server.com');

function ChatApp() {
  const [message, setMessage] = useProState('chatMessage', '');

  return (
    <input
      value={message}
      onChange={(e) => setMessage(e.target.value)}
      placeholder="Type a message"
    />
  );
}

State Persistence

Easily persist state to LocalStorage for offline support:

import { enablePersistence, useProState } from 'easyprostate';

// Enable persistence
enablePersistence();

function Cart() {
  const [cart, setCart] = useProState('cart', []);

  return (
    <div>
      <h1>My Cart</h1>
      <button onClick={() => setCart([...cart, { id: 1, name: 'Product A' }])}>
        Add Product A
      </button>
    </div>
  );
}

Debugging with DevTools

Enable DevTools to inspect and modify state from the browser console:

import { enableDevTools } from 'easyprostate';

// Enable DevTools
enableDevTools();

Access global state via window.__EASY_PRO_STATE__:

console.log(window.__EASY_PRO_STATE__.state); // View the entire global state

API Reference

1. useProState(key, defaultValue)

Hook to manage global state.

Parameters:

  • key (string): The unique key for the state
  • defaultValue (any): The initial value of the state

Returns:

  • [state, setState]: An array containing the current state and a function to update it

Example:

const [count, setCount] = useProState('count', 0);

2. setupWebSocket(url)

Sets up real-time synchronization using WebSocket.

Parameters:

  • url (string): The WebSocket server URL

Example:

setupWebSocket('wss://your-server.com');

3. enablePersistence()

Enables automatic state persistence using LocalStorage.

Example:

enablePersistence();

4. enableDevTools()

Enables debugging tools for inspecting and modifying global state.

Example:

enableDevTools();

Advanced Use Cases

Real-Time Collaborative Applications

Synchronize state across users for real-time collaboration:

import { setupWebSocket, useProState } from 'easyprostate';

// Enable WebSocket
setupWebSocket('wss://your-server.com');

function CollaborativeEditor() {
  const [document, setDocument] = useProState('sharedDoc', '');

  return (
    <textarea
      value={document}
      onChange={(e) => setDocument(e.target.value)}
    />
  );
}

Cross-Tab State Sharing

State is automatically shared across browser tabs:

const [theme, setTheme] = useProState('theme', 'light');
// Changing theme in one tab will update it in all open tabs

Technical Details

The library is built with several key technical considerations:

  1. Store Implementation

    • Uses a singleton pattern for global state management
    • Maintains separate maps for state and listeners
    • Supports middleware and sync methods
  2. React Integration

    • Built on React's useState and useEffect hooks
    • Efficient subscription model to prevent unnecessary renders
    • Automatic cleanup of listeners on component unmount
  3. Persistence Layer

    • Uses localStorage for state persistence
    • Automatically saves state on page unload
    • Restores state on page load
  4. WebSocket Integration

    • Bidirectional real-time updates
    • Automatic state synchronization across clients
    • Robust error handling and reconnection logic

Comparison with Other Libraries

FeatureEasy Pro StateReduxZustandMobXReact ContextJotaiRecoil
Zero Config Setupβœ…βŒβœ…βŒβœ…βœ…βŒ
Built-in WebSocket Syncβœ…βŒβŒβŒβŒβŒβŒ
Automatic Persistenceβœ…βŒ*❌*❌*❌❌*❌*
DevTools Supportβœ…βœ…βœ…βœ…βŒβœ…βœ…
Key-based State Updatesβœ…βŒ**βœ…βœ…βŒβœ…βœ…
Cross-Tab Syncβœ…βŒ*❌*❌*❌❌*❌*
TypeScript Supportβœ…βœ…βœ…βœ…βœ…βœ…βœ…
Middleware Supportβœ…βœ…βœ…βœ…βŒβŒβŒ
Bundle SizeSmallLargeSmallMediumZeroSmallMedium
Learning CurveEasySteepEasyModerateEasyEasyModerate
React Native Supportβœ…βœ…βœ…βœ…βœ…βœ…βœ…
Hook-based APIβœ…βŒ***βœ…βœ…βœ…βœ…βœ…

Key Advantages of Easy Pro State

  1. Built-in Real-time Sync:

    • Your implementation includes WebSocket integration out of the box
    • Other libraries require separate implementation or third-party solutions
  2. Automatic Persistence:

    • Built-in localStorage persistence with enablePersistence()
    • Other libraries typically require middleware or external packages
  3. Simplified API:

    • Single hook (useProState) for all operations
    • No actions, reducers, or complex setup required
    • Similar to useState but with global state capabilities
  4. DevTools Integration:

    • Simple enableDevTools() function
    • Direct access via window.__EASY_PRO_STATE__
    • No complex configuration needed
  5. Cross-Tab Synchronization:

    • Automatic state sharing across browser tabs
    • Works in conjunction with persistence feature
    • Other libraries often require additional setup
  6. Key-based Subscriptions:

    • Your store implementation efficiently handles subscriptions per key
    • Prevents unnecessary re-renders
    • More granular than Context API's full-tree re-renders
  7. Middleware Support:

    • Built-in middleware system for intercepting state changes
    • Simpler than Redux middleware
    • More flexible than Context API

Performance Considerations

OperationEasy Pro StateReduxContextMobX
State UpdatesFast (Key-based)Fast (Selector)Slow (Full tree)Fast (Observable)
Initial SetupInstantComplexInstantModerate
Memory UsageLowModerateLowModerate
Re-render OptimizationAutomaticManualManualAutomatic

FAQs

Q: Can I use this with server-side rendering (SSR)?
A: Yes! Easy Pro State checks for window availability before accessing browser APIs.

Q: Does it support TypeScript?
A: Yes, Easy Pro State is fully typed for seamless integration with TypeScript projects.

Q: How does the real-time sync work?
A: The library uses WebSocket to broadcast state changes to all connected clients automatically.

Q: Is there a size limit for persistent state?
A: The limit is based on localStorage capacity (typically 5-10MB depending on the browser).

Requirements

  • React ^16.8.0 || ^17.0.0 || ^18.0.0
  • Modern browser with WebSocket and localStorage support

Contributing

We welcome contributions! Please submit a pull request or open an issue on GitHub.

License

MIT Β© Rajan Dev

1.0.9

8 months ago

1.0.8

8 months ago

1.0.7

8 months ago

1.0.6

8 months ago

1.0.5

8 months ago

1.0.4

8 months ago

1.0.3

8 months ago

1.0.2

8 months ago

1.0.1

8 months ago

1.0.0

8 months ago