Only use observer do react state, only 0.4kb in gzip.
- Add
ObProvider
in App.tsx
<ObProvider>
<App />
</ObProvider>
- Use
useChannel
andOb
in Page
function Page() {
const value = useChannel(0);
return (
<div>
<Ob channels={[value]}>{(value) => <div>num: {value}</div>}</Ob>
<button onClick={() => value.set(value() + 1)}></button>
</div>
);
}
- Use global
channel
:
const name = channel("");
function UserPage() {
return (
<Subscribe channels={[name]}>
{(_name) => <div>User name: {_name}</div>}
</Subscribe>
);
}
function UserSettingPage() {
return (
<div>
<div> setting username:</div>
<input onChange={(e) => name.set(e.target.value)} />
</div>
);
}
- Use localStorage
channel
:
const name = channelWithStorage("user-name", "");
function UserPage() {
return (
<Subscribe channels={[name]}>
{(_name) => <div>User name: {_name}</div>}
</Subscribe>
);
}
function UserSettingPage() {
return (
<div>
<div> setting username:</div>
<input onChange={(e) => name.set(e.target.value)} />
</div>
);
}