1.0.9 • Published 2 years ago

minimal-react-state v1.0.9

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

Minimal React State

A minimal global state management library for React with almost no boilerplate code. Built on top of Zustand.

npm install minimal-react-state # or yarn add minimal-react-state

Define your store

Configure your store using a simple object, this will also serve as the type definition for your store. Actions are just functions in the object where you can use this to modify the state. (Just don't use arrow function expressions or your function will not have access to the correct this)

// store.ts

import { defineStore } from "minimal-react-state";

export const useStore = defineStore({
    count: 0,
    double() {
        this.count *= 2
    }
})

Use in your React component

Simply import your store and use it as a hook in your React component or function!

// buttons.tsx

import { useStore } from "./store"

function Buttons() {
    const store = useStore()

    return (
        <>
            <button onClick={() => store.count += 1}>
                increment
            </button>
            <br />
            <button onClick={() => store.double()}>
                double
            </button>
        </>
    )
}

export default Buttons

Store is global

Access your store from any component, removing the need for prop drilling.

// displayCount.tsx

import { useStore } from "./store"

function DisplayCount() {
    const store = useStore()

    return (
        <div>
            Count: {store.count}
        </div>
    )
}

export default Display

Optimise for performance

As your store grows, you can choose a subset of keys to hook into to stop the component from updating on every state change.

// displayPage.tsx

import { useStore } from "./store"

function DisplayPage() {
    const store = useStore(['page']) // this component won't update when store.count is changed

    return (
        <div>
            Page: {store.page}
        </div>
    )
}

export default DisplayPage

Fully type safe

Typescript will shout at you if you mispell one of the store keys.

const store = useStore()
// Property 'cont' does not exist on type '{ count: number; double: () => void; }'. Did you mean 'count'?
const count = store.cont

When specifying store subsets, it will also warn you if that key doesn't exist.

// Type '"cont"' is not assignable to type '"count" | "double"'. Did you mean '"count"'?
const store = useStore(['cont'])

For a store that has a certain subset selected, keys that are not part of that subset will also raise warnings.

// Property 'count' does not exist on type '{ double: () => void; }'.
const store = useStore(['double'])
const count = store.count
1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago