Skip to main content

API @hookstate/core

Table of contents

Interfaces

Type Aliases

Variables

Functions

Type Aliases

ExtensionFactory

Ƭ ExtensionFactory<S, I, E>: (typemarker?: __State<S, I>) => Extension<S, I, E>

Type parameters

Name
S
I
E

Type declaration

▸ (typemarker?): Extension<S, I, E>

Parameters
NameType
typemarker?__State<S, I>
Returns

Extension<S, I, E>

Defined in

index.ts:371


Immutable

Ƭ Immutable<T>: T extends ImmutablePrimitive ? T : T extends infer U[] ? ImmutableArray<U> : T extends Map<infer K, infer V> ? ImmutableMap<K, V> : T extends Set<infer M> ? ImmutableSet<M> : ImmutableObject<T>

Makes a value deep readonly

Type parameters

Name
T

Defined in

index.ts:81


ImmutableArray

Ƭ ImmutableArray<T>: ReadonlyArray<Immutable<T>>

Type parameters

Name
T

Defined in

index.ts:87


ImmutableMap

Ƭ ImmutableMap<K, V>: ReadonlyMap<Immutable<K>, Immutable<V>>

Type parameters

Name
K
V

Defined in

index.ts:88


ImmutableObject

Ƭ ImmutableObject<T>: { readonly [K in keyof T]: Immutable<T[K]> }

Type parameters

Name
T

Defined in

index.ts:90


ImmutablePrimitive

Ƭ ImmutablePrimitive: undefined | null | boolean | string | number | Function

Defined in

index.ts:86


ImmutableSet

Ƭ ImmutableSet<T>: ReadonlySet<Immutable<T>>

Type parameters

Name
T

Defined in

index.ts:89


InferKeysOfType

Ƭ InferKeysOfType<T, U, B>: { [P in keyof T]: B extends true ? T[P] extends U ? U extends T[P] ? P : never : never : T[P] extends U ? P : never }[keyof T]

Returns an interface stripped of all keys that don't resolve to U, defaulting to a non-strict comparison of T[key] extends U. Setting B to true performs a strict type comparison of T[key] extends U & U extends T[key]

Type parameters

NameType
TT
UU
Bfalse

Defined in

index.ts:235


InferReturnType

Ƭ InferReturnType<V>: V extends (...args: any) => infer R ? InferReturnType<R> : V

Type parameters

Name
V

Defined in

index.ts:278


InferStateExtensionType

Ƭ InferStateExtensionType<V>: InferReturnType<V> extends __State<infer _, infer E> ? E : InferReturnType<V> extends Extension<infer _, infer _, infer E> ? E : V

A routine which allows to extract extension methods / properties type of a state. Useful for extension developers.

Type parameters

Name
V

Defined in

index.ts:274


InferStateKeysType

Ƭ InferStateKeysType<S>: S extends ReadonlyArray<infer _> ? ReadonlyArray<number> : S extends null ? undefined : S extends object ? ReadonlyArray<string> : undefined

Return type of State.keys.

Typeparam

S Type of a value of a state

Type parameters

Name
S

Defined in

index.ts:63


InferStateOrnullType

Ƭ InferStateOrnullType<S, E>: S extends undefined ? undefined : S extends null ? null : State<S, E>

Return type of State.ornull.

Typeparam

S Type of a value of a state

Type parameters

Name
S
E

Defined in

index.ts:74


InferStateValueType

Ƭ InferStateValueType<V>: InferReturnType<V> extends __State<infer S, infer _> ? S : V

A routine which allows to extract value type of a state. Useful for extension developers.

Type parameters

Name
V

Defined in

index.ts:269


Path

Ƭ Path: ReadonlyArray<string | number>

'JSON path' from root of a state object to a nested property. Return type of StateMethod.path.

For example, an object { a: [{ b: 1 }, { 1000: 'value' }, '3rd'] }, has got the following paths pointing to existing properties:

  • []
  • ['a']
  • ['a', 0]
  • ['a', 0, 'b']
  • ['a', 1]
  • ['a', 1, 1000]
  • ['a', 2]

Defined in

index.ts:23


SetInitialStateAction

Ƭ SetInitialStateAction<S>: S | Promise<S> | () => S | Promise<S>

Type of an argument of hookstate and useHookstate.

Typeparam

S Type of a value of a state

Type parameters

Name
S

Defined in

index.ts:48


SetPartialStateAction

Ƭ SetPartialStateAction<S>: S extends ReadonlyArray<infer U> ? ReadonlyArray<U | Immutable<U>> | Record<number, U | Immutable<U>> | (prevValue: S) => ReadonlyArray<U | Immutable<U>> | Record<number, U | Immutable<U>> : S extends object | string ? Partial<S | Immutable<S>> | (prevValue: S) => Partial<S | Immutable<S>> : S | Immutable<S> | (prevState: S) => S | Immutable<S>

Type of an argument of State.merge.

Typeparam

S Type of a value of a state

Type parameters

Name
S

Defined in

index.ts:37


SetStateAction

Ƭ SetStateAction<S>: S | Immutable<S> | Promise<S | Immutable<S>> | (prevState: S) => S | Immutable<S> | Promise<S | Immutable<S>>

Type of an argument of State.set.

Typeparam

S Type of a value of a state

Type parameters

Name
S

Defined in

index.ts:30


State

Ƭ State<S, E>: __State<S, E> & StateMethods<S, E> & E & S extends ReadonlyArray<infer U> ? ReadonlyArray<State<U, E>> : S extends object ? Omit<{ readonly [K in keyof Required<S>]: State<S[K], E> }, keyof StateMethods<S, E> | InferKeysOfType<S, Function> | keyof E> : {}

Type of a result of hookstate and useHookstate functions

Typeparam

S Type of a value of a state

Learn more about global states... Learn more about local states... Learn more about nested states...

Type parameters

NameType
SS
E{}

Defined in

index.ts:289

Variables

none

Const none: any

Special symbol which might be used to delete properties from an object calling State.set or State.merge.

Learn more...

Defined in

index.ts:56

Functions

StateFragment

StateFragment<S, E>(props): never

Type parameters

NameType
SS
Eextends Object

Parameters

NameType
propsObject
props.children(state: State<S, E>) => ReactElement<any, string | JSXElementConstructor<any>>
props.extensionExtensionFactory<S, E, any>
props.state__State<S, E>
props.suspend?boolean

Returns

never

StateFragment<S, E>(props): React.ReactElement

Allows to use a state without defining a functional react component. It can be also used in class-based React components. It is also particularly useful for creating scoped states.

Learn more...

Typeparam

S Type of a value of a state

Type parameters

NameType
SS
Eextends Object

Parameters

NameType
propsObject
props.children(state: State<S, E>) => ReactElement<any, string | JSXElementConstructor<any>>
props.state__State<S, E>
props.suspend?boolean

Returns

React.ReactElement

StateFragment<S, E>(props): React.ReactElement

Allows to use a state without defining a functional react component. See more at StateFragment

Learn more...

Typeparam

S Type of a value of a state

Type parameters

NameType
SS
Eextends Object

Parameters

NameType
propsObject
props.children(state: State<S, E>) => ReactElement<any, string | JSXElementConstructor<any>>
props.extension?ExtensionFactory<S, {}, E>
props.stateSetInitialStateAction<S>
props.suspend?boolean

Returns

React.ReactElement


configure

configure(config): void

Configures Hookstate behavior globally. This is for special cases only, when default heuristics fail to work in a specific environment.

Parameters

NameType
configPartial<Configuration>

Returns

void


destroy

destroy<S, E>(state): void

A method to destroy a global state and resources allocated by the extensions

Type parameters

Name
S
E

Parameters

NameType
state__State<S, E>

Returns

void


extend

extend<S, E, E1, E2, E3, E4, E5>(e1?, e2?, e3?, e4?, e5?): ExtensionFactory<S, E, E5 & E4 & E3 & E2 & E1>

A function combines multiple extensions into one extension and returns it Browse an example here

Type parameters

NameType
SS
EE
E1extends Object = {}
E2extends Object = {}
E3extends Object = {}
E4extends Object = {}
E5extends Object = {}

Parameters

NameType
e1?ExtensionFactory<S, E, E1>
e2?ExtensionFactory<S, E1 & E, E2>
e3?ExtensionFactory<S, E2 & E1 & E, E3>
e4?ExtensionFactory<S, E3 & E2 & E1 & E, E4>
e5?ExtensionFactory<S, E4 & E3 & E2 & E1 & E, E5>

Returns

ExtensionFactory<S, E, E5 & E4 & E3 & E2 & E1>


hookstate

hookstate<S, E>(source, extension?): never

Type parameters

NameType
SS
E{}

Parameters

NameType
source__State<S, E>
extension?ExtensionFactory<S, E, any>

Returns

never

hookstate<S, E>(initial, extension?): State<S, E>

Creates new state and returns it.

You can create as many global states as you need.

When you the state is not needed anymore, it should be destroyed by calling destroy() function. This is necessary for some extensions, which allocate native resources, like subscription to databases, broadcast channels, etc. In most cases, a global state is used during whole life time of an application and would not require destruction. However, if you have got, for example, a catalog of dynamically created and destroyed global states, the states should be destroyed as advised above.

Typeparam

S Type of a value of the state

Type parameters

NameType
SS
Eextends Object = {}

Parameters

NameTypeDescription
initialSetInitialStateAction<S>Initial value of the state. It can be a value OR a promise, which asynchronously resolves to a value, OR a function returning a value or a promise.
extension?ExtensionFactory<S, {}, E>-

Returns

State<S, E>

State instance, which can be used directly to get and set state value outside of React components. When you need to use the state in a functional React component, pass the created state to useHookstate function and use the returned result in the component's logic.


hookstateMemo

hookstateMemo<T>(Component, propsAreEqual?): React.MemoExoticComponent<T>

Type parameters

NameType
Textends ComponentType<any>

Parameters

NameType
ComponentT
propsAreEqual?(prevProps: Readonly<ComponentProps<T>>, nextProps: Readonly<ComponentProps<T>>) => boolean

Returns

React.MemoExoticComponent<T>


isHookstate

isHookstate(v): boolean

A method to check if a variable is an instance of Hookstate State

Parameters

NameType
vany

Returns

boolean


isHookstateValue

isHookstateValue(v): boolean

A method to check if a variable is an instance of traced (wrapped in a proxy) Hookstate Value

Parameters

NameType
vany

Returns

boolean


suspend

suspend<S, E>(state): undefined | FunctionComponentElement<any>

If state is promised, then it returns a component which integrates with React 18 Suspend feature automatically. Note, that React 18 Suspend support for data loading is still experimental, but it worked as per our experiments and testing.

Type parameters

Name
S
E

Parameters

NameType
stateState<S, E>

Returns

undefined | FunctionComponentElement<any>


useHookstate

useHookstate<S, E>(source, extension?): never

Warning

Initializing a local state to a promise without using an initializer callback function, which returns a Promise, is almost always a mistake. So, it is blocked. Use useHookstate(() => your_promise) instead of useHookstate(your_promise).

Type parameters

NameType
SS
Eextends Object = {}

Parameters

NameType
sourcePromise<S>
extension?ExtensionFactory<S, {}, E>

Returns

never

useHookstate<S, E>(source, extension): never

Type parameters

NameType
SS
Eextends Object = {}

Parameters

NameType
source__State<S, E>
extensionExtensionFactory<S, E, any>

Returns

never

useHookstate<S, E>(source): State<S, E>

Enables a functional React component to use a state, either created by hookstate (global state) or derived from another call to useHookstate (scoped state).

The useHookstate forces a component to rerender every time, when:

  • a segment/part of the state data is updated AND only if
  • this segment was used by the component during or after the latest rendering.

For example, if the state value is { a: 1, b: 2 } and a component uses only a property of the state, it will rerender only when the whole state object is updated or when a property is updated. Setting the state value/property to the same value is also considered as an update.

A component can use one or many states, i.e. you may call useHookstate multiple times for multiple states.

The same state can be used by multiple different components.

Type parameters

NameType
SS
Eextends Object = {}

Parameters

NameTypeDescription
source__State<S, E>a reference to the state to hook into The useHookstate is a hook and should follow React's rules of hooks.

Returns

State<S, E>

an instance of State, which must be used within the component (during rendering or in effects) or it's children.

useHookstate<S, E>(source, extension?): State<S, E>

This function enables a functional React component to use a state, created per component by useHookstate (local state). In this case useHookstate behaves similarly to React.useState, but the returned instance of State has got more features.

When a state is used by only one component, and maybe it's children, it is recommended to use local state instead of global, which is created by hookstate.

Local (per component) state is created when a component is mounted and automatically destroyed when a component is unmounted.

The same as with the usage of a global state, useHookstate forces a component to rerender when:

  • a segment/part of the state data is updated AND only if
  • this segment was used by the component during or after the latest rendering.

You can use as many local states within the same component as you need.

Type parameters

NameType
SS
Eextends Object = {}

Parameters

NameTypeDescription
sourceSetInitialStateAction<S>An initial value state.
extension?ExtensionFactory<S, {}, E>-

Returns

State<S, E>

an instance of State, which must be used within the component (during rendering or in effects) or it's children.


useHookstateCallback

useHookstateCallback<T>(callback, deps): T

Type parameters

NameType
Textends Function

Parameters

NameType
callbackT
depsDependencyList

Returns

T


useHookstateEffect

useHookstateEffect(effect, deps?): void

Parameters

NameType
effectEffectCallback
deps?DependencyList

Returns

void


useHookstateImperativeHandle

useHookstateImperativeHandle<T, R>(ref, init, deps?): void

Type parameters

Name
T
R

Parameters

NameType
refundefined | Ref<T>
init() => R
deps?DependencyList

Returns

void


useHookstateInsertionEffect

useHookstateInsertionEffect(effect, deps?): void

Parameters

NameType
effectEffectCallback
deps?DependencyList

Returns

void


useHookstateLayoutEffect

useHookstateLayoutEffect(effect, deps?): void

Parameters

NameType
effectEffectCallback
deps?DependencyList

Returns

void


useHookstateMemo

useHookstateMemo<T>(factory, deps): T

Type parameters

Name
T

Parameters

NameType
factory() => T
depsundefined | DependencyList

Returns

T

Interfaces

Interface: Configuration

A type of an argument of the configure function

Table of contents

Properties

Properties

interceptDependencyListsMode

interceptDependencyListsMode: "always" | "development" | "never"

By default Hookstate intercepts calls to useEffect, useMemo and other functions where a dependency lists are used as arguments. This allows these hook functions to have Hookstate State objects in dependency lists and everything to work as 'expected'.

It is possible to opt-out from this mode, configuring the option to never.

Alternatively, it is possible to set it to intercept only during development, which will raise HOOKSTATE-100 error whenever Hookstate State is used in a dependency list of standard React hook function. This error can be fixed by replacing standard React hooks by Hookstate provided hooks, for example useEffect by useHookstateEffect

Defined in

index.ts:1983


isDevelopmentMode

isDevelopmentMode: boolean

Defines is Hookstate is running in a development mode. Development mode enables additional checking and HMR support. By default, it detects if process.env.NODE_ENV is set to 'development'. It might not work in all environments and so expected to be provided by an application explicitly.

Defined in

index.ts:1990


promiseDetector

promiseDetector: (p: any) => boolean

Type declaration

▸ (p): boolean

A callback which allows Hookstate to detect if a provided variable is a promise or not. This allows to enable Hookstate working in Angular environment when Promises are wrapped by zone.js, which breaks standard promise resolution / detection convention.

Parameters
NameType
pany
Returns

boolean

Defined in

index.ts:1996

Interface: Extension<S, I, E>

For extension developers only. Set of callbacks, an extension may subscribe to.

Learn more...

Type parameters

Name
S
I
E

Table of contents

Properties

Properties

onCreate

Optional Readonly onCreate: (state: State<S, {}>, extensionsCallbacks: { [K in string | number | symbol]: Function }) => { readonly [K in string | number | symbol]: Function }

Type declaration

▸ (state, extensionsCallbacks): { readonly [K in string | number | symbol]: Function }

Parameters
NameType
stateState<S, {}>
extensionsCallbacks{ [K in string | number | symbol]: Function }
Returns

{ readonly [K in string | number | symbol]: Function }

Defined in

index.ts:353


onDestroy

Optional Readonly onDestroy: (state: State<S, E & I>) => void

Type declaration

▸ (state): void

Parameters
NameType
stateState<S, E & I>
Returns

void

Defined in

index.ts:368


onInit

Optional Readonly onInit: (state: State<S, E & I>, extensionsCallbacks: { [K in string | number | symbol]: Function }) => void

Type declaration

▸ (state, extensionsCallbacks): void

Parameters
NameType
stateState<S, E & I>
extensionsCallbacks{ [K in string | number | symbol]: Function }
Returns

void

Defined in

index.ts:359


onPremerge

Optional Readonly onPremerge: (state: State<any, E & I>, value: any, rootState: State<any, E & I>) => void

Type declaration

▸ (state, value, rootState): void

Parameters
NameType
stateState<any, E & I>
valueany
rootStateState<any, E & I>
Returns

void

Defined in

index.ts:366


onPreset

Optional Readonly onPreset: (state: State<any, E & I>, value: any, rootState: State<any, E & I>) => void

Type declaration

▸ (state, value, rootState): void

Parameters
NameType
stateState<any, E & I>
valueany
rootStateState<any, E & I>
Returns

void

Defined in

index.ts:365


onSet

Optional Readonly onSet: (state: State<any, E & I>, descriptor: SetActionDescriptor, rootState: State<any, E & I>) => void

Type declaration

▸ (state, descriptor, rootState): void

Parameters
NameType
stateState<any, E & I>
descriptorSetActionDescriptor
rootStateState<any, E & I>
Returns

void

Defined in

index.ts:367

Interface: StateMethods<S, E>

An interface to manage a state in Hookstate.

Typeparam

S Type of a value of a state

Type parameters

Name
S
E

Table of contents

Properties

Methods

Properties

error

Readonly error: any

If a state was set to a promise and the promise was rejected, this property will return the error captured from the promise rejection

Defined in

index.ts:160


keys

Readonly keys: InferStateKeysType<S>

Return the keys of nested states. For a given state of State type, state.keys will be structurally equal to Object.keys(state), with two minor difference:

  1. if state.value is an array, the returned result will be an array of numbers, not strings like with Object.keys.
  2. if state.value is not an object, the returned result will be undefined.
Defined in

index.ts:120


ornull

ornull: InferStateOrnullType<S, E>

If state value is null or undefined, returns state value. Otherwise, it returns this state instance but with null and undefined removed from the type parameter.

Learn more...

Defined in

index.ts:227


path

Readonly path: Path

'Javascript' object 'path' to an element relative to the root object in the state. For example:

const state = useHookstate([{ name: 'First Task' }])
state.path IS []
state[0].path IS [0]
state.[0].name.path IS [0, 'name']
Defined in

index.ts:109


promise

Readonly promise: undefined | Promise<State<S, E>>

If the State is promised, this will be a defined promise which an application can use to subscribe to with 'then' callback.

Defined in

index.ts:154


promised

Readonly promised: boolean

True if state value is not yet available (eg. equal to a promise)

Defined in

index.ts:148


value

Readonly value: Immutable<S>

Unwraps and returns the underlying state value referred by path of this state instance.

It returns the same result as State.get method.

This property is more useful than get method for the cases, when a value may hold null or undefined values. Typescript compiler does not handle elimination of undefined with get(), like in the following examples, but value does:

const state = useHookstate<number | undefined>(0)
const myvalue: number = state.value
? state.value + 1
: 0; // <-- compiles
const myvalue: number = state.get()
? state.get() + 1
: 0; // <-- does not compile
Defined in

index.ts:143

Methods

get

get(options?): Immutable<S>

Unwraps and returns the underlying state value referred by path of this state instance.

It returns the same result as State.value method.

If the additional option noproxy is set, the method will return the original data object without wrapping it by proxy. All properties of the object will be marked as used and on change will trigger the rerender.

If the additional option stealth is set, the method will not mark the object as used and it will not trigger the rerender if it is changed. It might be helpful to use it during debugging, for example: console.log(state.get({ stealth: true })). If you use it, make sure you know what you are doing.

Parameters
NameType
options?Object
options.noproxy?boolean
options.stealth?boolean
Returns

Immutable<S>


merge

merge(newValue): void

Similarly to set method updates state value.

  • If current state value is an object, it does partial update for the object.
  • If state value is an array and the argument is an array too, it concatenates the current value with the value of the argument and sets it to the state.
  • If state value is an array and the merge argument is an object, it does partial update for the current array value.
  • If current state value is a string, it concatenates the current state value with the argument converted to string and sets the result to the state.
Parameters
NameType
newValueSetPartialStateAction<S>
Returns

void


nested

nested<K>(key): State<S[K], E>

Returns nested state by key. state.nested('myprop') returns the same as state.myprop or state['myprop'], but also works for properties, which names collide with names of state methods.

Learn more about nested states...

Type parameters
NameType
Kextends string | number | symbol
Parameters
NameTypeDescription
keyKchild property name or index
Returns

State<S[K], E>


set

set(newValue): void

Sets new value for a state. If this.path === [], it is similar to the setState variable returned by React.useState hook. If this.path !== [], it sets only the segment of the state value, pointed out by the path. Unlike merge method, this method will not accept partial updates. Partial updates can be also done by walking the nested states and setting those.

Parameters
NameTypeDescription
newValueSetStateAction<S>new value to set to a state. It can be a value, a promise resolving to a value (only if this.path is []), or a function returning one of these. The function receives the current state value as an argument.
Returns

void