@opentf/react-state
TypeScript icon, indicating that this package has built-in type declarations

0.15.0 • Public • Published

 OPEN TECH FOUNDATION

React State

Build

A global state manager for ReactJS.

View Demo | Documentation

Features

  • Simple API
  • No context providers
  • Components are re-rendered only when the selector value changes
  • It can shallow diff custom selector objects
  • It supports async actions
  • TypeScript support

Installation

npm install @opentf/react-state
yarn add @opentf/react-state
pnpm add @opentf/react-state
bun add @opentf/react-state

Usage

import { create } from '@opentf/react-state';

const [useAppState, setAppState, api] = create({ count: 0 });

api.subscribe(console.log);

function App() {
  const count = useAppState((s) => s.count);

  return (
    <>
      <p>Count: {count}</p>
      <button onClick={() => setAppState((s) => ({ count: s.count + 1 }))}>
        Change State
      </button>
    </>
  );
}

Usage (TypeScript)

import React from 'react';
import { create } from '@opentf/react-state';

interface AppState {
  isLogin: boolean;
  user: {
    id: string;
    name: string;
  } | null;
  theme: string;
}

const appState: AppState = {
  isLogin: true,
  user: { id: 'abcdef', name: 'XXX' },
  theme: 'Dark',
};

const [useAppState, setAppState, api] = create(appState);

api.subscribe(console.log);

export default function App() {
  const { isLogin, user, theme } = useAppState((s) => s);

  function handleLogout() {
    setAppState((s) => ({ ...s, user: null, isLogin: false }));
  }

  return (
    <div data-theme={theme}>
      <p>Welcome {isLogin ? user?.name : 'Guest!'}</p>
      <button onClick={handleLogout}>Logout</button>
    </div>
  );
}

License

Copyright (c) 2021, Thanga Ganapathy (MIT License).

Package Sidebar

Install

npm i @opentf/react-state

Weekly Downloads

47

Version

0.15.0

License

MIT

Unpacked Size

13.1 kB

Total Files

8

Last publish

Collaborators

  • ganapathy