MIT License MIT License

npm

Logo

react-persist-store

A simple hook-based type-safe store for React with out-of-the-box browser persistence

View Demo · Report Bug · View on npm

A persistent storage abstraction for React backed by TypeScript.

Features

  • Store and persist data to browser storage by default
  • Declare default values and all types will be inferred automatically
  • Share state across multiple components with a functional approach to store creation

Getting Started

In react-persist-hook data is written to local storage by default. Types are inferred from the default values passed to the createStore function.

createStore returns another function that is called with a key at the top level of the store. This provides a hook function that is called without arguments.

Installation

  1. Install NPM package

    npm install react-persist-store
  2. Set up your Store and create your hook

    import createStore from "react-persist-store";
    
    // Types will be inferred from defaultStoreValues
    const defaultStoreValues = {
      // Here user is a namespace to a particular Document store
      user: {
        firstName: "",
        lastName: "",
        badges: [], // In TypeScript this is never[], you can change this behaviour with createStore<YourStoreType>(...)
      },
      posts: [
        /** ... */
      ],
    };
    
    // You can pass options to customise the type of storage, "local", "session", or false to disable persistence
    // The namespace is prepended to keys in browser storage to separate them from other state
    // const store = createStore(defaultStoreValues, { storage: 'session', namespace: 'custom' });
    const store = createStore(defaultStoreValues);
    
    export const useUser = store("user")
  3. Use the hook anywhere in your application

    import { useUser } from "./store"
    
    const Component = () => {
    // Hooks do not take arguments, and return only:
    // data - your data with types inferred from your store, or the generic you passed in
    // update - a function what takes a partial copy of data to update
    // clearAll - clear all state, including browser storage for this hook
    const { data, update, clearAll } = useUser()
    const { firstName, lastName } = data
    const fullName = `${firstName}${lastName ? ' ' + lastName : ''}`
    return (
      <p>
        {fullName}
      </p>
    )
    }
    
    export default Component

License

Distributed under the MIT License. See LICENSE for more information.

GitHub

View Github