0.0.16 • Published 1 year ago

react-hook-svc v0.0.16

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

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

0.0.16

1 year ago

0.0.13

2 years ago

0.0.15

2 years ago

0.0.11

2 years ago

0.0.12

2 years ago

0.0.7

2 years ago

0.0.5

2 years ago

0.0.4

2 years ago

0.0.6

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago