Options
All
  • Public
  • Public/Protected
  • All
Menu

@spicy-hooks/core

API reference

This is a detailed API reference of the @spicy-hooks/core package.

For high-level information about this package and installation instructions, please see our GitHub repository.

Index

Type aliases

EqualityFunction

EqualityFunction<T>: (prev: T, next: T) => boolean

A simple function that should return true if the two arguments are considered equal, false otherwise. The requirements for "equality" are entirely up to the implementation.

Type parameters

  • T

Type declaration

    • (prev: T, next: T): boolean
    • Parameters

      • prev: T
      • next: T

      Returns boolean

OverrideComponent

OverrideComponent<T>: FunctionComponent<{ values: Partial<T> }>

A Provider like component through which you can override selected dependencies.

see

createUseDependencies

Type parameters

  • T: Record<string, any>

UseContext

UseContext<T>: () => T & { Provider: Provider<T> }

A hook that retrieves a value of a certain context when called. In addition to that it carries a Provider component that can be used to override the context's value.

see

createUseContext

Type parameters

  • T

    type of the value kept in the context

UseDependencies

UseDependencies<T>: () => T & { Override: OverrideComponent<T> }

A hook that fetches dependencies from a dependency injection layer. In addition to that it carries a Override component that can be used to override selected dependencies.

see

createUseDependencies

Type parameters

  • T: Record<string, any>

    shape of dependency object

Hook Functions

useCombinedRef

  • useCombinedRef<T>(...refs: Array<RefCallback<T> | MutableRefObject<T | null> | null | undefined>): RefCallback<T>
  • Aggregates multiple refs into a single one, so that multiple refs can be attached to a single element.

    Type parameters

    • T

      type of the value kept in the ref

    Parameters

    • Rest ...refs: Array<RefCallback<T> | MutableRefObject<T | null> | null | undefined>

    Returns RefCallback<T>

useComputedRef

  • useComputedRef<T>(factory: () => T): MutableRefObject<T>
  • Allocates a ref and initializes it with a computed value.

    Type parameters

    • T

      type of the generated value

    Parameters

    • factory: () => T

      the factory is used during the initial render only to compute the ref's value

        • (): T
        • Returns T

    Returns MutableRefObject<T>

useDependantState

  • useDependantState<S>(initialValue: S | (() => S), deps: DependencyList): []
  • An extension to the useState hook which resets the current value to the initialValue every time the deps change.

    Type parameters

    • S

      type of the state value

    Parameters

    • initialValue: S | (() => S)

      initial value or a factory to generate one

    • deps: DependencyList

      array of dependencies

    Returns []

    the same result as obtained from useState

useDisposable

  • useDisposable<T>(factory: () => [], deps: DependencyList): T
  • Allows you allocate resources synchronously while ensuring they will be properly disposed when the deps change or when the component gets unmounted.

    Works just like useMemo with the addition of the dispose callback.

    Note that it is ensured that the previous allocated value will be disposed prior allocating a new one.

    Type parameters

    • T

      type of the allocated value

    Parameters

    • factory: () => []

      factory function that returns a tuple of the allocated value and a dispose callback

        • (): []
        • Returns []

    • deps: DependencyList

      dependencies of the factory function

    Returns T

    the allocated value

useDistinctValue

  • Returns always the same instance of the value until it changes according to the equalityFn. Useful for keeping stable instance of objects whose instances change, but values stay the same.

    Type parameters

    • T

      type of the interned value

    Parameters

    • value: T

      value that is expected to change

    • equalityFn: EqualityFunction<T>

      function to evaluate whether the value changed

    Returns T

useGuaranteedCallback

  • useGuaranteedCallback<F>(callback: F, deps: DependencyList): F
  • Equivalent to useCallback but doesn't suffer from the following (quoting https://reactjs.org/docs/hooks-faq.html#how-to-memoize-calculations):

    You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

    Note: You should not blindly replace all usages of useCallback with this hook. The useGuaranteedCallback should be used only in scenarios where re-calculating the memoized value would cause issues.

    Type parameters

    • F: Function

      type of the callback function

    Parameters

    • callback: F

      the callback function to be memoized

    • deps: DependencyList

      dependencies for the callback (if any of them changes, the memoized callback is dropped and an recent one is stored)

    Returns F

useGuaranteedMemo

  • useGuaranteedMemo<T>(factory: () => T, deps: DependencyList): T
  • Equivalent to useMemo but doesn't suffer from the following (quoting https://reactjs.org/docs/hooks-faq.html#how-to-memoize-calculations):

    You may rely on useMemo as a performance optimization, not as a semantic guarantee. In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, e.g. to free memory for offscreen components. Write your code so that it still works without useMemo — and then add it to optimize performance.

    Note: You should not blindly replace all usages of useMemo with this hook. The useGuaranteedMemo should be used only in scenarios where re-calculating the memoized value would cause issues.

    Type parameters

    • T

      type of the memoized value

    Parameters

    • factory: () => T

      factory to generate the value that is to be memoized

        • (): T
        • Returns T

    • deps: DependencyList

      array of dependencies for the factory (if any of them changes, the memoized value is dropped and a new one is generated)

    Returns T

useImmediateEffect

  • useImmediateEffect(effect: EffectCallback, deps: DependencyList): void
  • Warning: It is usually a bad practice to trigger side-effects directly during the render phase. Make sure you really know what you are doing when using this hook!

    An alternative to useEffect where the callback is executed right within the render phase. In other words the effect is performed immediately when the useImmediateEffect is called and eventual side-effects can be observed right after the useImmediateEffect line.

    Note that just like useEffect the useImmediateEffect ensures that a teardown logic will be executed before any subsequent effect is triggered. Furthermore it is also guaranteed that the teardown logic will be run in case the component unmounts.

    Example:

      let sideEffect = 0
    
      useEffect(() => {
        sideEffect = 1
      },[])
    
      console.log(sideEffect) // outputs 1

    Parameters

    • effect: EffectCallback

      callback that performs the effect and optionally returns a tear-down logic

    • deps: DependencyList

      array of dependencies for the effect (if any of them changes, the effect is re-triggered)

    Returns void

useLastAvailable

  • useLastAvailable<T>(value: T, isAvailable?: boolean): T
  • Caches previous value for usages when current value is not available. Availability of value is by default determined using value != null. If more specific control is required, the second argument is here to the rescue. Passing true to isAvailable marks the provided value as available, while false will make the function return the cached one.

    This hook is useful to keep invalidated values around until a new valid one is obtained.

    Type parameters

    • T

      type of the cached value

    Parameters

    • value: T

      value to be cached

    • Default value isAvailable: boolean = value != null

      optional custom boolean flag to determine "availability"

    Returns T

    either cached or the provided value, based on availability

useProperty

  • useProperty<O, P>(object: O, updateObject: Dispatch<(prevState: O) => O>, property: P): []
  • Treats a property of an object as a stand-alone state.

    This hook can be used to access a property of a complex state in a transparent way. The returned value and setter can be treated in the same way as the ones returned by useState directly.

    Usage example:

    const [object, setObject] = useState({ a: 'a', b: 1 })
    const [b, setB] = useProperty(object, setObject, 'b')
    ...
    return (
      <div>
        Current value of B: {b}
        <button onClick={() => setB(prevB => prevB + 1)}>Increment</button>
      </div>
    )

    Note that the above shows very simple case in which it would probably be better to allocate two different states, there are situations though when you either cannot influence this (the object comes from above) or it is beneficial to use the whole object as an atomic unit.

    Type parameters

    • O

      type of the complex state

    • P: keyof O

      the actual managed property of O

    Parameters

    • object: O

      complex state value

    • updateObject: Dispatch<(prevState: O) => O>

      function that updates the complex state by passing the current state into the callback and expecting a modified state back (just like setState(prev => prev + 1)

    • property: P

      name of the property of the object that is to be managed

    Returns []

    the same output as ˙useState˙, but scoping everything to the provided property

useSingleton

  • useSingleton<T>(factory: () => T): T
  • Returns a value computed during the first render using the provided factory. The value is guaranteed to never change.

    Type parameters

    • T

      type of the generated value

    Parameters

    • factory: () => T

      factory function to generate the singleton value on the first render (ignored for any subsequent render)

        • (): T
        • Returns T

    Returns T

useUpdatedRef

  • useUpdatedRef<T>(value: T): MutableRefObject<T>
  • Use a ref of the latest value passed to the useUpdatedRef hook.

    Type parameters

    • T

      type of the value kept in the ref

    Parameters

    • value: T

      new value to update the captured one

    Returns MutableRefObject<T>

Hook Factory Functions

createUseContext

  • createUseContext<T>(__namedParameters: { contextName: string }): UseContext<T | undefined>
  • createUseContext<T>(__namedParameters: { contextName: string; defaultValue: T }): UseContext<T>
  • createUseContext<T>(__namedParameters: { contextName: string; nonNull: true; nullMessage: undefined | string }): UseContext<T>
  • Creates a useContext hook for a newly allocated context with the specified name.

    Example:

    const useMyContext = createUseContext({contextName: 'MyContext'})
    
    const MyComponent = () => {
      const myValue = useMyContext()
    }
    
    const MyApp = () => (
      <useMyContext.Provider value={...}>
        ...
      </useMyContext.Provider
    )

    Type parameters

    • T

      type of the value kept in the context

    Parameters

    • __namedParameters: { contextName: string }
      • contextName: string

        name of the new context

    Returns UseContext<T | undefined>

  • Creates a useContext hook for a newly allocated context with the specified name and a given default value.

    Example:

    const useMyContext = createUseContext({contextName: 'MyContext', defaultValue: ... })
    
    const MyComponent = () => {
      const myValue = useMyContext()
    }
    
    const MyApp = () => (
      <useMyContext.Provider value={...}>
        ...
      </useMyContext.Provider
    )
    category

    Hook Factory

    Type parameters

    • T

      type of the value kept in the context

    Parameters

    • __namedParameters: { contextName: string; defaultValue: T }
      • contextName: string

        name of the new context

      • defaultValue: T

        default value for the context to be used when no Provider is mounted

    Returns UseContext<T>

  • Creates a useContext hook for a newly allocated context with the specified name.

    Invocation of the hook will fail if there is no value provided through the Provider component.

    Example:

    const useMyContext = createUseContext({contextName: 'MyContext', nonNull: true, nullMessage: 'Value not available, did you use <useMyContext.Provider> ?' })
    
    const MyComponent = () => {
      const myValue = useMyContext()
    }
    
    const MyApp = () => (
      <useMyContext.Provider value={...}>
        ...
      </useMyContext.Provider
    )
    category

    Hook Factory

    Type parameters

    • T

      type of the value kept in the context

    Parameters

    • __namedParameters: { contextName: string; nonNull: true; nullMessage: undefined | string }
      • contextName: string

        name of the new context

      • nonNull: true

        always true

      • nullMessage: undefined | string

        a custom error message to be displayed when there is no value provided

    Returns UseContext<T>

createUseDependencies

  • createUseDependencies<T>(defaultsOrFactory: T | (() => T)): UseDependencies<T>
  • This function sets up a very simple context based dependency injection layer. It creates a useDependencies hook that can be used to fetch the dependencies from any component.

    Example:

    const useMyDependencies = createUseContext({foo: 'X', bar: 1})
    
    const MyComponent = () => {
      const {foo} = useMyDependencies()
      ...
    }
    
    const MyApp = () => (
      <useMyDependencies.Override value={{bar: 2}}>
        ...
      </useMyDependencies.Override
    )

    Type parameters

    • T: Record<string, any>

      shape of the dependency object

    Parameters

    • defaultsOrFactory: T | (() => T)

      default dependencies or a factory that helps overcome issues with circular dependencies

    Returns UseDependencies<T>

Legend

  • Module
  • Object literal
  • Variable
  • Function
  • Function with type parameter
  • Index signature
  • Type alias
  • Type alias with type parameter
  • Enumeration
  • Enumeration member
  • Property
  • Method
  • Interface
  • Interface with type parameter
  • Constructor
  • Property
  • Method
  • Index signature
  • Class
  • Class with type parameter
  • Constructor
  • Property
  • Method
  • Accessor
  • Index signature
  • Inherited constructor
  • Inherited property
  • Inherited method
  • Inherited accessor
  • Protected property
  • Protected method
  • Protected accessor
  • Private property
  • Private method
  • Private accessor
  • Static property
  • Static method

Generated using TypeDoc