UNPKG

use-mutable-source

Version:

Minimal and elegant way to integrate any library with React

39 lines (38 loc) 2.45 kB
import { type DependencyList } from 'react'; import { Slice } from '../slice'; /** * Generates a source, and allows to use it safely inside any component. The * source is re-created every time a dependency changes. * * @param init - function that generates the source, it can optionally returns also a "destroy" function * @param deps - dependency list that define the source lifecycle * @param contract - function to register a callback that is called whenever the source changes * @returns an hook to derive snapshots and a function to lazily initialize the source */ export declare function useSource<Source>(init: () => [source: Source, destroy?: (source: Source) => void], ...rest: [ ...deps: [DependencyList?] | [], contract: (source: Source, onChange: () => void) => void | (() => void) ]): readonly [<Snapshot>(getSnapshot: (source: Source | null, currentSnapshot: Snapshot | null) => Snapshot, getSnapshotDeps?: DependencyList) => Snapshot, () => Source]; /** * Generates a pure source, and allows to use it safely inside any component. * The source is re-created every time a dependency changes. * The source generation and the contract should be side-effect free. * After the contract is signed, the source should be garbage collectable. * * @param init - function that generates the source * @param deps - dependency list that define the source lifecycle * @param contract - function to register a callback that is called whenever the source changes * @returns an hook to derive snapshots and the source */ export declare function usePureSource<Source>(init: () => Source, ...rest: [ ...deps: [DependencyList?] | [], contract: (source: Source, onChange: () => void) => void ]): readonly [<Snapshot>(getSnapshot: (source: Source, currentSnapshot: Snapshot | null) => Snapshot, getSnapshotDeps?: DependencyList) => Snapshot, Source]; /** * Allows to use a global source safely inside any component. * * @param source - the source * @param contract - function to register a callback that is called whenever the source changes * @returns an hook to derive snapshots and the source */ export declare function withContract<Source>(source: Source, contract: (source: Source, onChange: () => void) => void): readonly [<Snapshot>(getSnapshot: (source: Source, currentSnapshot: Snapshot | null) => Snapshot, getSnapshotDeps?: DependencyList) => Snapshot, Source, Slice];