Skip to content

createGlobalState

Category
Export Size
253 B
Last Changed
5 days ago
Related

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>
]

Source

Source · Demo · react-use

Contributors

hairyf

Changelog

v0.1.0 on
529c1 - fix(shared): resolve createGlobalState audit findings (#699)

Released under the MIT License. v0.1.8