Create React State

React state management you already know how to use

  • ? Easy to use outside of react
  • ? Easy to use inside of react – drop in replacement for useState
  • ? Wait for state with promises
  • ? Very performant
  • ? Native typescript support
  • ? Tiny bundle size (<1KB minified)

import React from 'react';
import { createState } from 'create-react-state';

// Create the state with an initial value
const counterState = createState(0)

function Counter() {
    // Use this hook in any component that needs to react to the state
    const [count, setCount] = counterState.useState();
    return (
        <div>
            <p>{count}</p>
            <button onClick={() => setCount(count + 1)}>+</button>
        </div>
    );
}

Read state without a hook

Always returns the current state value. Can be used inside or outside of react components.

console.log(counterState.value)

Write state without a hook

Mutate the state inside or outside of react components

counterState.set(counterState.value + 1)

Subscribe to state without a hook

Subscribe to state inside or outside of react components

counterState.subscribe(x => {
    console.log('counterState changed', x)
})

Wait for state with promises

Wait until state is ready with a promise.

// Resolves when count goes above 5. 
// If the count is already above 5 it will resolve immediately.
const highCount = await counterState.waitFor(x => x > 5 ? x : false)

Note the promise will resolve if anything other than false, undefined or null is returned.

Hook usage

const [count, setCount] = counterState.useState()

Hook usage, with a custom selector function

// Component only re-renders if the value of the count is even
const [isEven] = counterState.useState(x => x % 2 == 0)

Hook usage, with a dynamic selector function

By default the selector function is cached. In some rarer cases the function might be dynamic. For example:

const users = createState({
    alice: { name: 'Alice', age: 20 },
    bob: { name: 'Bob', age: 30 },
    chad: { name: 'Chad', age: 40 },
});


function Foo() {
    const [name, setName] = useState('alice')
    // Add name as a dependency to the selector
    const [user] = users.useState(x => x[name], [name]);
    return (
        <div>
            <p>{user.name} {user.age}</p>
            <button onClick={() => setName('alice')}>Alice</button>
            <button onClick={() => setName('bob')}>Bob</button>
            <button onClick={() => setName('chad')}>Chad</button>
        </div>
    );
}

GitHub

View Github