react-hook-svc
v0.0.16
Published
[![npm][react-hook-svc-icon]][react-hook-svc-npm] [![npm][react-hook-svc-bundle]][react-hook-svc-npm] [![Build Status](https://img.shields.io/github/workflow/status/shalldie/hook-service/ci?label=build&logo=github&style=flat-square)](https://github.com/sh
Downloads
7
Readme
react-hook-svc
A service、state manager for React. minzipped
less than 300 bytes
。
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