A service、state manager for React. minzipped
less than 300 bytes
。
- ~300 bytes min+gz.
- Minimal API 5 minutes to learn, easy to use.
- Written in TypeScript offer you more types.
npm install react-hook-svc --save
// 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
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);
// 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
});
}
MIT