Appearance
createGlobalState
Keep state in the global scope, reusable across React components.
Demo
Usage
tsx
import { createGlobalState } from '@reause/shared'
// called once, at module scope: every component below reads the same state
const useGlobalValue = createGlobalState(0)
function CompA() {
const [value, setValue] = useGlobalValue()
return <button onClick={() => setValue(value + 1)}>+</button>
}
function CompB() {
const [value, setValue] = useGlobalValue()
return <button onClick={() => setValue(value - 1)}>-</button>
}
function Demo() {
const [value] = useGlobalValue()
return (
<div>
<p>{value}</p>
<CompA />
<CompB />
</div>
)
}Type Declarations
ts
export type IHookStateInitAction<S> = S | (() => S)
export type IHookStateSetAction<S> = S | ((prevState: S) => S) | (() => S)
export function createGlobalState<S = any>(initialState: IHookStateInitAction<S>): () => [
S,
(state: IHookStateSetAction<S>) => void
]
export function createGlobalState<S = undefined>(): () => [
S,
(state: IHookStateSetAction<S>) => void
]
export function useList<T>(initialList?: IHookStateInitAction<T[]>): [
T[],
ListActions<T>
]