react-hook-svc
TypeScript icon, indicating that this package has built-in type declarations

0.0.16 • Public • Published

react-hook-svc

npm npm Build Status License

A service、state manager for React. minzipped less than 300 bytes

English | 中文

Advantage

  • ~300 bytes min+gz.
  • Minimal API 5 minutes to learn, easy to use.
  • Written in TypeScript offer you more types.

Installation

npm install react-hook-svc --save

Usage & Example

declare a service

// declare a service
// service.ts
import { svc } from 'react-hook-svc';

class SomeState {
    show = true;
}

export class SomeService extends svc.ServiceBase<SomeState> {
    state = new SomeState();

    toggle() {
        this.setState({
            show: !this.state.show
        });
    }
}

// create a service func depends on the component's lifecycle
export const { useService, getService, withProvider } = svc.createServiceCtx(SomeService);

wrap the component with withProvider

// wrap the component with withProvider
import { svc } from 'react-hook-svc';
import { useService, withProvider } from './service';

function AppBase() {
    // after wrapper, current component and it's children will get the same instance with `useService`
    const svc = useService();

    const show = useMemo(() => svc.state.show, [svc.state]);

    return (
        <>
            <button onClick={() => svc.toggle()}></button>
            {show && <span>...</span>}
        </>
    );
}

export const App = withProvider(AppBase);
// this may be usefull with lots of withProviders
// export const App = svc.connect(withProvider)(App);

use it outside the component, anywhere

// when withProvider the root component of App, the service may be a global one.
// you can get it with `getService`
import { getService } from './service';

function demo() {
    const svc = getService();
    svc.setState({
        show: true
    });
}

License

MIT

Readme

Keywords

Package Sidebar

Install

npm i react-hook-svc

Weekly Downloads

0

Version

0.0.16

License

MIT

Unpacked Size

10.9 kB

Total Files

8

Last publish

Collaborators

  • shalldie