1.1.11 • Published 3 years ago
@caredoc/rare v1.1.11
래어
Context 가 필요 없는 React 용 immer 베이스 반응형 상타관리 라이브러리
act ---fetch--> mutate ---update--> state
이 것 왜 필요한가?
1 글로벌 상태관리에 Context 가 왜 안 필요한가 를 https://recoiljs.org/ 에서 잘 설명해 주고 있다
2 작은 단위 상태 관리필요
예제
글로벌 상태 관리
// 컴포넌트 Foo 와 Bar 는 상태를 공유
import {Store, useReactive} from './src'
const fooStore = new Store({
name: 'foo',
deep: {
name: 'foo'
}
})
const useFoo = () => useReactive(fooStore)
const fakeGetName = () => Promise.resolve('bar')
const updateAllNames = fooStore.mutate((draft, name: string) => {
draft.name = name
draft.deep.name = name
})
const requestGetName = fooStore.action(async () => {
const result = await fakeGetName()
updateAllNames(result)
})
const Foo = () => {
const [state, dispatch] = useFoo()
return (
h('div', null, ...[
h('button', {onClick: () => dispatch((draft) => {
draft.name += '~'
})}, state.name),
h('button', {onClick: () => dispatch((draft) => {
draft.deep.name += '~'
})}, state.deep.name)
h('button', {onClick: () => updateAllNames(state.name + '~')}, 'update all names')
h('button', {onClick: () => requestGetName()}, 'requestGetName')
])
)
}
const Bar = () => {
const [state, dispatch] = useFoo()
return (
h('div', null, ...[
h('div', null, state.name)
h('div', null, state.deep.name)
])
)
}
작은 규모 범위 상태 공유
import {Store, useReactive, Rare} from './src'
interface State {
foo: string
}
const createFooStore = () => new Store({
foo: 'foo'
})
const useFoo = () => useLocalReactive<State>()
const Foo = () => {
const [state, dispatch] = useFoo()
return (
h('div', null, state.foo)
)
}
const Bar = () => {
const [state, dispatch] = useFoo()
return (
h('div', null, state.foo)
)
}
const SubRoot = () => {
return (
h('div', null, ...[
h(Rare, {store: createFooStore},
h(Foo)
)
h(Bar)
])
)
}