Poly-state

website·Indexed 29 days ago

https://poly-state.github.io

A boilerplate-free state management library for React, Next.js, Preact, and SolidJS applications. It features a fully typed API without reducers or actions, support for Redux DevTools, and specialized hooks via createStoreHooks.

Tokens
3.5K
Snippets
18
Records
29
Agent score
75%

What's inside Poly-state

  1. Overview of poly-state state management library

    poly-state is a boilerplate-free state management library designed for use with React, Next.js, Preact, and SolidJS applications.
  2. Understand poly-state core concepts and workflow

    Poly-state manages state through a store-and-hook pattern that does not require a Provider wrapper.

    1. Store Creation: The createStore function accepts an initial state and returns an instance of an internal Store class along with setter methods for each property in the state.
    2. State Updates: State values are modified using the generated setter methods.
    3. UI Synchronization: The useStore hook subscribes to state updates. When the internal state changes, the hook updates the returned value, triggering a UI re-render. The hook automatically handles cleanup on component unmount.
  3. Install Redux DevTools extension

    Redux DevTools can be installed across various environments:

    • Chrome: Install via the Chrome Web Store or load the unpacked extension folder from the source build.
    • Firefox: Install via Mozilla Add-ons or load the unpacked extension folder.
    • Electron: Use the electron-devtools-installer and specify REDUX_DEVTOOLS.
    • Other/Non-browser: Use remote-redux-devtools.
  4. Apply middleware to a poly-state store

    Middleware can be used to enhance store functionality, such as adding logging for debugging. You can chain multiple middlewares using the .use() method on the store instance.
    const todoStore = new TodoStore(initialState);
    todoStore
        .use(loggerMiddleware) // Add the logger middleware
        .use(anotherMiddleware); // You can use multiple middlewares
  5. Install @poly-state/poly-state

    Install the stable version of the poly-state library using npm or yarn. Ensure your environment meets the requirements: Node.js version 14 or higher and npm version 6 or higher. Familiarity with the ReactJS ecosystem is recommended.
    # Using npm
    npm install @poly-state/poly-state
    
    # Using yarn
    yarn add @poly-state/poly-state
  6. Handle asynchronous logic in a poly-state store

    Asynchronous operations (such as API calls) can be implemented as async methods within a store class. Once the asynchronous operation completes and the data is retrieved, call this.setState() to update the store with the result.
    class TodoStore extends getStoreClass<TodoStoreState>() {
        async addAsyncTodo(text: string) {
            const response = await fetch('/api/todos', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ text }),
            });
            const todo = (await response.json()) as Todo;
    
            if (response.ok) {
                this.setState((state) => ({
                    ...state,
                    todos: [...state.todos, todo],
                    count: state.count + 1,
                }));
            }
        }
    }
  7. Enable Redux DevTools for a Poly-State store

    To debug store changes using Redux DevTools, wrap your store with the withDevTools middleware. The second argument to withDevTools serves as the store identifier within the Redux DevTools interface.
    import { createStore, withDevTools } from '@poly-state/poly-state';
    import { useStore } from '@poly-state/react';
    
    const counterStore = createStore({ count: 0 });
    withDevTools(counterStore, 'Counter Store');
    
    const useCounterStore = () => useStore(counterStore);
  8. Install Poly State for React or Next.js

    To use Poly State in a React or Next.js project, install the @poly-state/react package using npm or yarn.
    # Using npm
    npm install @poly-state/react
    
    # Using yarn
    yarn add @poly-state/react
  9. Conditionally enable Redux DevTools in development

    To prevent Redux DevTools from running in production environments, wrap the withDevTools call in a conditional check using process.env.NODE_ENV.
    import { createStore, withDevTools } from '@poly-state/poly-state';
    
    const counterStore = createStore({ count: 0 });
    if (process.env.NODE_ENV === 'development') {
        withDevTools(counterStore, 'Counter Store');
    }
  10. Create custom store hooks using createStoreHooks

    The createStoreHooks function takes a store instance and returns a tuple containing two custom hooks: UseStore (to access the entire store state) and UseStoreSelector (to access a specific key from the store state). This is the recommended way to create typed, reusable hooks for a specific store instance instead of calling the generic hooks repeatedly.
    import { createStore, createStoreHooks } from '@poly-state/react';
    
    const counterStore = createStore({ count: 0 });
    const [useCounterStore, useCounterSelector] = createStoreHooks(counterStore);
    
    // Usage in a component:
    function Component() {
      const { count } = useCounterStore(); // Access full state
      const countValue = useCounterSelector('count'); // Access specific key
      return <div>{countValue}</div>;
    }
  11. Install poly-state for React or Next.js

    To use poly-state for state binding in a ReactJS or Next.js application, install both the core library and the React-specific binding library.
    yarn add @poly-state/poly-state @poly-state/react
  12. Create a poly-state store with React hooks

    Use createStore from @poly-state/poly-state to define the initial state and createStoreHooks from @poly-state/react to generate a hook for accessing that state within React components. createStoreHooks returns a tuple containing a store hook and a selector hook.
    import { createStore } from '@poly-state/poly-state';
    import { createStoreHooks } from '@poly-state/react';
    
    const counterStore = createStore({ count: 0 });
    const [useCounterStore, useCounterSelector] = createStoreHooks(counterStore);